three.webgpu.nodes.js 1.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix2, Matrix3, Matrix4, EventDispatcher, MathUtils, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, InterleavedBufferAttribute, DynamicDrawUsage, NoColorSpace, UnsignedIntType, IntType, NearestFilter, Sphere, BackSide, Euler, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, OrthographicCamera, PerspectiveCamera, RenderTarget, LinearSRGBColorSpace, RGBAFormat, HalfFloatType, CubeUVReflectionMapping, BufferGeometry, BufferAttribute, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, DoubleSide, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, VSMShadowMap, LessCompare, RGFormat, BasicShadowMap, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFShadowMap, FrustumArray, Frustum, DataTexture, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, warnOnce, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'aoMapIntensity',
  16. 'attenuationColor',
  17. 'attenuationDistance',
  18. 'bumpMap',
  19. 'clearcoat',
  20. 'clearcoatMap',
  21. 'clearcoatNormalMap',
  22. 'clearcoatNormalScale',
  23. 'clearcoatRoughness',
  24. 'color',
  25. 'dispersion',
  26. 'displacementMap',
  27. 'emissive',
  28. 'emissiveIntensity',
  29. 'emissiveMap',
  30. 'envMap',
  31. 'envMapIntensity',
  32. 'gradientMap',
  33. 'ior',
  34. 'iridescence',
  35. 'iridescenceIOR',
  36. 'iridescenceMap',
  37. 'iridescenceThicknessMap',
  38. 'lightMap',
  39. 'lightMapIntensity',
  40. 'map',
  41. 'matcap',
  42. 'metalness',
  43. 'metalnessMap',
  44. 'normalMap',
  45. 'normalScale',
  46. 'opacity',
  47. 'roughness',
  48. 'roughnessMap',
  49. 'sheen',
  50. 'sheenColor',
  51. 'sheenColorMap',
  52. 'sheenRoughnessMap',
  53. 'shininess',
  54. 'specular',
  55. 'specularColor',
  56. 'specularColorMap',
  57. 'specularIntensity',
  58. 'specularIntensityMap',
  59. 'specularMap',
  60. 'thickness',
  61. 'transmission',
  62. 'transmissionMap'
  63. ];
  64. /**
  65. * This class is used by {@link WebGPURenderer} as management component.
  66. * It's primary purpose is to determine whether render objects require a
  67. * refresh right before they are going to be rendered or not.
  68. */
  69. class NodeMaterialObserver {
  70. /**
  71. * Constructs a new node material observer.
  72. *
  73. * @param {NodeBuilder} builder - The node builder.
  74. */
  75. constructor( builder ) {
  76. /**
  77. * A node material can be used by more than one render object so the
  78. * monitor must maintain a list of render objects.
  79. *
  80. * @type {WeakMap<RenderObject,Object>}
  81. */
  82. this.renderObjects = new WeakMap();
  83. /**
  84. * Whether the material uses node objects or not.
  85. *
  86. * @type {boolean}
  87. */
  88. this.hasNode = this.containsNode( builder );
  89. /**
  90. * Whether the node builder's 3D object is animated or not.
  91. *
  92. * @type {boolean}
  93. */
  94. this.hasAnimation = builder.object.isSkinnedMesh === true;
  95. /**
  96. * A list of all possible material uniforms
  97. *
  98. * @type {Array<string>}
  99. */
  100. this.refreshUniforms = refreshUniforms;
  101. /**
  102. * Holds the current render ID from the node frame.
  103. *
  104. * @type {number}
  105. * @default 0
  106. */
  107. this.renderId = 0;
  108. }
  109. /**
  110. * Returns `true` if the given render object is verified for the first time of this observer.
  111. *
  112. * @param {RenderObject} renderObject - The render object.
  113. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  114. */
  115. firstInitialization( renderObject ) {
  116. const hasInitialized = this.renderObjects.has( renderObject );
  117. if ( hasInitialized === false ) {
  118. this.getRenderObjectData( renderObject );
  119. return true;
  120. }
  121. return false;
  122. }
  123. /**
  124. * Returns `true` if the current rendering produces motion vectors.
  125. *
  126. * @param {Renderer} renderer - The renderer.
  127. * @return {boolean} Whether the current rendering produces motion vectors or not.
  128. */
  129. needsVelocity( renderer ) {
  130. const mrt = renderer.getMRT();
  131. return ( mrt !== null && mrt.has( 'velocity' ) );
  132. }
  133. /**
  134. * Returns monitoring data for the given render object.
  135. *
  136. * @param {RenderObject} renderObject - The render object.
  137. * @return {Object} The monitoring data.
  138. */
  139. getRenderObjectData( renderObject ) {
  140. let data = this.renderObjects.get( renderObject );
  141. if ( data === undefined ) {
  142. const { geometry, material, object } = renderObject;
  143. data = {
  144. material: this.getMaterialData( material ),
  145. geometry: {
  146. id: geometry.id,
  147. attributes: this.getAttributesData( geometry.attributes ),
  148. indexVersion: geometry.index ? geometry.index.version : null,
  149. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  150. },
  151. worldMatrix: object.matrixWorld.clone()
  152. };
  153. if ( object.center ) {
  154. data.center = object.center.clone();
  155. }
  156. if ( object.morphTargetInfluences ) {
  157. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  158. }
  159. if ( renderObject.bundle !== null ) {
  160. data.version = renderObject.bundle.version;
  161. }
  162. if ( data.material.transmission > 0 ) {
  163. const { width, height } = renderObject.context;
  164. data.bufferWidth = width;
  165. data.bufferHeight = height;
  166. }
  167. this.renderObjects.set( renderObject, data );
  168. }
  169. return data;
  170. }
  171. /**
  172. * Returns an attribute data structure holding the attributes versions for
  173. * monitoring.
  174. *
  175. * @param {Object} attributes - The geometry attributes.
  176. * @return {Object} An object for monitoring the versions of attributes.
  177. */
  178. getAttributesData( attributes ) {
  179. const attributesData = {};
  180. for ( const name in attributes ) {
  181. const attribute = attributes[ name ];
  182. attributesData[ name ] = {
  183. version: attribute.version
  184. };
  185. }
  186. return attributesData;
  187. }
  188. /**
  189. * Returns `true` if the node builder's material uses
  190. * node properties.
  191. *
  192. * @param {NodeBuilder} builder - The current node builder.
  193. * @return {boolean} Whether the node builder's material uses node properties or not.
  194. */
  195. containsNode( builder ) {
  196. const material = builder.material;
  197. for ( const property in material ) {
  198. if ( material[ property ] && material[ property ].isNode )
  199. return true;
  200. }
  201. if ( builder.renderer.overrideNodes.modelViewMatrix !== null || builder.renderer.overrideNodes.modelNormalViewMatrix !== null )
  202. return true;
  203. return false;
  204. }
  205. /**
  206. * Returns a material data structure holding the material property values for
  207. * monitoring.
  208. *
  209. * @param {Material} material - The material.
  210. * @return {Object} An object for monitoring material properties.
  211. */
  212. getMaterialData( material ) {
  213. const data = {};
  214. for ( const property of this.refreshUniforms ) {
  215. const value = material[ property ];
  216. if ( value === null || value === undefined ) continue;
  217. if ( typeof value === 'object' && value.clone !== undefined ) {
  218. if ( value.isTexture === true ) {
  219. data[ property ] = { id: value.id, version: value.version };
  220. } else {
  221. data[ property ] = value.clone();
  222. }
  223. } else {
  224. data[ property ] = value;
  225. }
  226. }
  227. return data;
  228. }
  229. /**
  230. * Returns `true` if the given render object has not changed its state.
  231. *
  232. * @param {RenderObject} renderObject - The render object.
  233. * @return {boolean} Whether the given render object has changed its state or not.
  234. */
  235. equals( renderObject ) {
  236. const { object, material, geometry } = renderObject;
  237. const renderObjectData = this.getRenderObjectData( renderObject );
  238. // world matrix
  239. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  240. renderObjectData.worldMatrix.copy( object.matrixWorld );
  241. return false;
  242. }
  243. // material
  244. const materialData = renderObjectData.material;
  245. for ( const property in materialData ) {
  246. const value = materialData[ property ];
  247. const mtlValue = material[ property ];
  248. if ( value.equals !== undefined ) {
  249. if ( value.equals( mtlValue ) === false ) {
  250. value.copy( mtlValue );
  251. return false;
  252. }
  253. } else if ( mtlValue.isTexture === true ) {
  254. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  255. value.id = mtlValue.id;
  256. value.version = mtlValue.version;
  257. return false;
  258. }
  259. } else if ( value !== mtlValue ) {
  260. materialData[ property ] = mtlValue;
  261. return false;
  262. }
  263. }
  264. if ( materialData.transmission > 0 ) {
  265. const { width, height } = renderObject.context;
  266. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  267. renderObjectData.bufferWidth = width;
  268. renderObjectData.bufferHeight = height;
  269. return false;
  270. }
  271. }
  272. // geometry
  273. const storedGeometryData = renderObjectData.geometry;
  274. const attributes = geometry.attributes;
  275. const storedAttributes = storedGeometryData.attributes;
  276. const storedAttributeNames = Object.keys( storedAttributes );
  277. const currentAttributeNames = Object.keys( attributes );
  278. if ( storedGeometryData.id !== geometry.id ) {
  279. storedGeometryData.id = geometry.id;
  280. return false;
  281. }
  282. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  283. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  284. return false;
  285. }
  286. // compare each attribute
  287. for ( const name of storedAttributeNames ) {
  288. const storedAttributeData = storedAttributes[ name ];
  289. const attribute = attributes[ name ];
  290. if ( attribute === undefined ) {
  291. // attribute was removed
  292. delete storedAttributes[ name ];
  293. return false;
  294. }
  295. if ( storedAttributeData.version !== attribute.version ) {
  296. storedAttributeData.version = attribute.version;
  297. return false;
  298. }
  299. }
  300. // check index
  301. const index = geometry.index;
  302. const storedIndexVersion = storedGeometryData.indexVersion;
  303. const currentIndexVersion = index ? index.version : null;
  304. if ( storedIndexVersion !== currentIndexVersion ) {
  305. storedGeometryData.indexVersion = currentIndexVersion;
  306. return false;
  307. }
  308. // check drawRange
  309. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  310. storedGeometryData.drawRange.start = geometry.drawRange.start;
  311. storedGeometryData.drawRange.count = geometry.drawRange.count;
  312. return false;
  313. }
  314. // morph targets
  315. if ( renderObjectData.morphTargetInfluences ) {
  316. let morphChanged = false;
  317. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  318. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  319. morphChanged = true;
  320. }
  321. }
  322. if ( morphChanged ) return true;
  323. }
  324. // center
  325. if ( renderObjectData.center ) {
  326. if ( renderObjectData.center.equals( object.center ) === false ) {
  327. renderObjectData.center.copy( object.center );
  328. return true;
  329. }
  330. }
  331. // bundle
  332. if ( renderObject.bundle !== null ) {
  333. renderObjectData.version = renderObject.bundle.version;
  334. }
  335. return true;
  336. }
  337. /**
  338. * Checks if the given render object requires a refresh.
  339. *
  340. * @param {RenderObject} renderObject - The render object.
  341. * @param {NodeFrame} nodeFrame - The current node frame.
  342. * @return {boolean} Whether the given render object requires a refresh or not.
  343. */
  344. needsRefresh( renderObject, nodeFrame ) {
  345. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  346. return true;
  347. const { renderId } = nodeFrame;
  348. if ( this.renderId !== renderId ) {
  349. this.renderId = renderId;
  350. return true;
  351. }
  352. const isStatic = renderObject.object.static === true;
  353. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  354. if ( isStatic || isBundle )
  355. return false;
  356. const notEqual = this.equals( renderObject ) !== true;
  357. return notEqual;
  358. }
  359. }
  360. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  361. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  362. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  363. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  364. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  365. function cyrb53( value, seed = 0 ) {
  366. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  367. if ( value instanceof Array ) {
  368. for ( let i = 0, val; i < value.length; i ++ ) {
  369. val = value[ i ];
  370. h1 = Math.imul( h1 ^ val, 2654435761 );
  371. h2 = Math.imul( h2 ^ val, 1597334677 );
  372. }
  373. } else {
  374. for ( let i = 0, ch; i < value.length; i ++ ) {
  375. ch = value.charCodeAt( i );
  376. h1 = Math.imul( h1 ^ ch, 2654435761 );
  377. h2 = Math.imul( h2 ^ ch, 1597334677 );
  378. }
  379. }
  380. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  381. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  382. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  383. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  384. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  385. }
  386. /**
  387. * Computes a hash for the given string.
  388. *
  389. * @method
  390. * @param {string} str - The string to be hashed.
  391. * @return {number} The hash.
  392. */
  393. const hashString = ( str ) => cyrb53( str );
  394. /**
  395. * Computes a hash for the given array.
  396. *
  397. * @method
  398. * @param {Array<number>} array - The array to be hashed.
  399. * @return {number} The hash.
  400. */
  401. const hashArray = ( array ) => cyrb53( array );
  402. /**
  403. * Computes a hash for the given list of parameters.
  404. *
  405. * @method
  406. * @param {...number} params - A list of parameters.
  407. * @return {number} The hash.
  408. */
  409. const hash$1 = ( ...params ) => cyrb53( params );
  410. /**
  411. * Computes a cache key for the given node.
  412. *
  413. * @method
  414. * @param {Object|Node} object - The object to be hashed.
  415. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  416. * @return {number} The hash.
  417. */
  418. function getCacheKey$1( object, force = false ) {
  419. const values = [];
  420. if ( object.isNode === true ) {
  421. values.push( object.id );
  422. object = object.getSelf();
  423. }
  424. for ( const { property, childNode } of getNodeChildren( object ) ) {
  425. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  426. }
  427. return cyrb53( values );
  428. }
  429. /**
  430. * This generator function can be used to iterate over the node children
  431. * of the given object.
  432. *
  433. * @generator
  434. * @param {Object} node - The object to be hashed.
  435. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  436. * @yields {Object} A result node holding the property, index (if available) and the child node.
  437. */
  438. function* getNodeChildren( node, toJSON = false ) {
  439. for ( const property in node ) {
  440. // Ignore private properties.
  441. if ( property.startsWith( '_' ) === true ) continue;
  442. const object = node[ property ];
  443. if ( Array.isArray( object ) === true ) {
  444. for ( let i = 0; i < object.length; i ++ ) {
  445. const child = object[ i ];
  446. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  447. yield { property, index: i, childNode: child };
  448. }
  449. }
  450. } else if ( object && object.isNode === true ) {
  451. yield { property, childNode: object };
  452. } else if ( typeof object === 'object' ) {
  453. for ( const subProperty in object ) {
  454. const child = object[ subProperty ];
  455. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  456. yield { property, index: subProperty, childNode: child };
  457. }
  458. }
  459. }
  460. }
  461. }
  462. const typeFromLength = /*@__PURE__*/ new Map( [
  463. [ 1, 'float' ],
  464. [ 2, 'vec2' ],
  465. [ 3, 'vec3' ],
  466. [ 4, 'vec4' ],
  467. [ 9, 'mat3' ],
  468. [ 16, 'mat4' ]
  469. ] );
  470. const dataFromObject = /*@__PURE__*/ new WeakMap();
  471. /**
  472. * Returns the data type for the given the length.
  473. *
  474. * @method
  475. * @param {number} length - The length.
  476. * @return {string} The data type.
  477. */
  478. function getTypeFromLength( length ) {
  479. return typeFromLength.get( length );
  480. }
  481. /**
  482. * Returns the typed array for the given data type.
  483. *
  484. * @method
  485. * @param {string} type - The data type.
  486. * @return {TypedArray} The typed array.
  487. */
  488. function getTypedArrayFromType( type ) {
  489. // Handle component type for vectors and matrices
  490. if ( /[iu]?vec\d/.test( type ) ) {
  491. // Handle int vectors
  492. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  493. // Handle uint vectors
  494. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  495. // Default to float vectors
  496. return Float32Array;
  497. }
  498. // Handle matrices (always float)
  499. if ( /mat\d/.test( type ) ) return Float32Array;
  500. // Basic types
  501. if ( /float/.test( type ) ) return Float32Array;
  502. if ( /uint/.test( type ) ) return Uint32Array;
  503. if ( /int/.test( type ) ) return Int32Array;
  504. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  505. }
  506. /**
  507. * Returns the length for the given data type.
  508. *
  509. * @method
  510. * @param {string} type - The data type.
  511. * @return {number} The length.
  512. */
  513. function getLengthFromType( type ) {
  514. if ( /float|int|uint/.test( type ) ) return 1;
  515. if ( /vec2/.test( type ) ) return 2;
  516. if ( /vec3/.test( type ) ) return 3;
  517. if ( /vec4/.test( type ) ) return 4;
  518. if ( /mat2/.test( type ) ) return 4;
  519. if ( /mat3/.test( type ) ) return 9;
  520. if ( /mat4/.test( type ) ) return 16;
  521. console.error( 'THREE.TSL: Unsupported type:', type );
  522. }
  523. /**
  524. * Returns the gpu memory length for the given data type.
  525. *
  526. * @method
  527. * @param {string} type - The data type.
  528. * @return {number} The length.
  529. */
  530. function getMemoryLengthFromType( type ) {
  531. if ( /float|int|uint/.test( type ) ) return 1;
  532. if ( /vec2/.test( type ) ) return 2;
  533. if ( /vec3/.test( type ) ) return 3;
  534. if ( /vec4/.test( type ) ) return 4;
  535. if ( /mat2/.test( type ) ) return 4;
  536. if ( /mat3/.test( type ) ) return 12;
  537. if ( /mat4/.test( type ) ) return 16;
  538. console.error( 'THREE.TSL: Unsupported type:', type );
  539. }
  540. /**
  541. * Returns the byte boundary for the given data type.
  542. *
  543. * @method
  544. * @param {string} type - The data type.
  545. * @return {number} The byte boundary.
  546. */
  547. function getByteBoundaryFromType( type ) {
  548. if ( /float|int|uint/.test( type ) ) return 4;
  549. if ( /vec2/.test( type ) ) return 8;
  550. if ( /vec3/.test( type ) ) return 16;
  551. if ( /vec4/.test( type ) ) return 16;
  552. if ( /mat2/.test( type ) ) return 8;
  553. if ( /mat3/.test( type ) ) return 48;
  554. if ( /mat4/.test( type ) ) return 64;
  555. console.error( 'THREE.TSL: Unsupported type:', type );
  556. }
  557. /**
  558. * Returns the data type for the given value.
  559. *
  560. * @method
  561. * @param {any} value - The value.
  562. * @return {?string} The data type.
  563. */
  564. function getValueType( value ) {
  565. if ( value === undefined || value === null ) return null;
  566. const typeOf = typeof value;
  567. if ( value.isNode === true ) {
  568. return 'node';
  569. } else if ( typeOf === 'number' ) {
  570. return 'float';
  571. } else if ( typeOf === 'boolean' ) {
  572. return 'bool';
  573. } else if ( typeOf === 'string' ) {
  574. return 'string';
  575. } else if ( typeOf === 'function' ) {
  576. return 'shader';
  577. } else if ( value.isVector2 === true ) {
  578. return 'vec2';
  579. } else if ( value.isVector3 === true ) {
  580. return 'vec3';
  581. } else if ( value.isVector4 === true ) {
  582. return 'vec4';
  583. } else if ( value.isMatrix2 === true ) {
  584. return 'mat2';
  585. } else if ( value.isMatrix3 === true ) {
  586. return 'mat3';
  587. } else if ( value.isMatrix4 === true ) {
  588. return 'mat4';
  589. } else if ( value.isColor === true ) {
  590. return 'color';
  591. } else if ( value instanceof ArrayBuffer ) {
  592. return 'ArrayBuffer';
  593. }
  594. return null;
  595. }
  596. /**
  597. * Returns the value/object for the given data type and parameters.
  598. *
  599. * @method
  600. * @param {string} type - The given type.
  601. * @param {...any} params - A parameter list.
  602. * @return {any} The value/object.
  603. */
  604. function getValueFromType( type, ...params ) {
  605. const last4 = type ? type.slice( -4 ) : undefined;
  606. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  607. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  608. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  609. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  610. }
  611. if ( type === 'color' ) {
  612. return new Color( ...params );
  613. } else if ( last4 === 'vec2' ) {
  614. return new Vector2( ...params );
  615. } else if ( last4 === 'vec3' ) {
  616. return new Vector3( ...params );
  617. } else if ( last4 === 'vec4' ) {
  618. return new Vector4( ...params );
  619. } else if ( last4 === 'mat2' ) {
  620. return new Matrix2( ...params );
  621. } else if ( last4 === 'mat3' ) {
  622. return new Matrix3( ...params );
  623. } else if ( last4 === 'mat4' ) {
  624. return new Matrix4( ...params );
  625. } else if ( type === 'bool' ) {
  626. return params[ 0 ] || false;
  627. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  628. return params[ 0 ] || 0;
  629. } else if ( type === 'string' ) {
  630. return params[ 0 ] || '';
  631. } else if ( type === 'ArrayBuffer' ) {
  632. return base64ToArrayBuffer( params[ 0 ] );
  633. }
  634. return null;
  635. }
  636. /**
  637. * Gets the object data that can be shared between different rendering steps.
  638. *
  639. * @param {Object} object - The object to get the data for.
  640. * @return {Object} The object data.
  641. */
  642. function getDataFromObject( object ) {
  643. let data = dataFromObject.get( object );
  644. if ( data === undefined ) {
  645. data = {};
  646. dataFromObject.set( object, data );
  647. }
  648. return data;
  649. }
  650. /**
  651. * Converts the given array buffer to a Base64 string.
  652. *
  653. * @method
  654. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  655. * @return {string} The Base64 string.
  656. */
  657. function arrayBufferToBase64( arrayBuffer ) {
  658. let chars = '';
  659. const array = new Uint8Array( arrayBuffer );
  660. for ( let i = 0; i < array.length; i ++ ) {
  661. chars += String.fromCharCode( array[ i ] );
  662. }
  663. return btoa( chars );
  664. }
  665. /**
  666. * Converts the given Base64 string to an array buffer.
  667. *
  668. * @method
  669. * @param {string} base64 - The Base64 string.
  670. * @return {ArrayBuffer} The array buffer.
  671. */
  672. function base64ToArrayBuffer( base64 ) {
  673. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  674. }
  675. var NodeUtils = /*#__PURE__*/Object.freeze({
  676. __proto__: null,
  677. arrayBufferToBase64: arrayBufferToBase64,
  678. base64ToArrayBuffer: base64ToArrayBuffer,
  679. getByteBoundaryFromType: getByteBoundaryFromType,
  680. getCacheKey: getCacheKey$1,
  681. getDataFromObject: getDataFromObject,
  682. getLengthFromType: getLengthFromType,
  683. getMemoryLengthFromType: getMemoryLengthFromType,
  684. getNodeChildren: getNodeChildren,
  685. getTypeFromLength: getTypeFromLength,
  686. getTypedArrayFromType: getTypedArrayFromType,
  687. getValueFromType: getValueFromType,
  688. getValueType: getValueType,
  689. hash: hash$1,
  690. hashArray: hashArray,
  691. hashString: hashString
  692. });
  693. /**
  694. * Possible shader stages.
  695. *
  696. * @property {string} VERTEX The vertex shader stage.
  697. * @property {string} FRAGMENT The fragment shader stage.
  698. */
  699. const NodeShaderStage = {
  700. VERTEX: 'vertex',
  701. FRAGMENT: 'fragment'
  702. };
  703. /**
  704. * Update types of a node.
  705. *
  706. * @property {string} NONE The update method is not executed.
  707. * @property {string} FRAME The update method is executed per frame.
  708. * @property {string} RENDER The update method is executed per render. A frame might be produced by multiple render calls so this value allows more detailed updates than FRAME.
  709. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  710. */
  711. const NodeUpdateType = {
  712. NONE: 'none',
  713. FRAME: 'frame',
  714. RENDER: 'render',
  715. OBJECT: 'object'
  716. };
  717. /**
  718. * Data types of a node.
  719. *
  720. * @property {string} BOOLEAN Boolean type.
  721. * @property {string} INTEGER Integer type.
  722. * @property {string} FLOAT Float type.
  723. * @property {string} VECTOR2 Two-dimensional vector type.
  724. * @property {string} VECTOR3 Three-dimensional vector type.
  725. * @property {string} VECTOR4 Four-dimensional vector type.
  726. * @property {string} MATRIX2 2x2 matrix type.
  727. * @property {string} MATRIX3 3x3 matrix type.
  728. * @property {string} MATRIX4 4x4 matrix type.
  729. */
  730. const NodeType = {
  731. BOOLEAN: 'bool',
  732. INTEGER: 'int',
  733. FLOAT: 'float',
  734. VECTOR2: 'vec2',
  735. VECTOR3: 'vec3',
  736. VECTOR4: 'vec4',
  737. MATRIX2: 'mat2',
  738. MATRIX3: 'mat3',
  739. MATRIX4: 'mat4'
  740. };
  741. /**
  742. * Access types of a node. These are relevant for compute and storage usage.
  743. *
  744. * @property {string} READ_ONLY Read-only access
  745. * @property {string} WRITE_ONLY Write-only access.
  746. * @property {string} READ_WRITE Read and write access.
  747. */
  748. const NodeAccess = {
  749. READ_ONLY: 'readOnly',
  750. WRITE_ONLY: 'writeOnly',
  751. READ_WRITE: 'readWrite',
  752. };
  753. const defaultShaderStages = [ 'fragment', 'vertex' ];
  754. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  755. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  756. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  757. const _parentBuildStage = {
  758. analyze: 'setup',
  759. generate: 'analyze'
  760. };
  761. let _nodeId = 0;
  762. /**
  763. * Base class for all nodes.
  764. *
  765. * @augments EventDispatcher
  766. */
  767. class Node extends EventDispatcher {
  768. static get type() {
  769. return 'Node';
  770. }
  771. /**
  772. * Constructs a new node.
  773. *
  774. * @param {?string} nodeType - The node type.
  775. */
  776. constructor( nodeType = null ) {
  777. super();
  778. /**
  779. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  780. *
  781. * @type {?string}
  782. * @default null
  783. */
  784. this.nodeType = nodeType;
  785. /**
  786. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  787. *
  788. * @type {string}
  789. * @default 'none'
  790. */
  791. this.updateType = NodeUpdateType.NONE;
  792. /**
  793. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  794. *
  795. * @type {string}
  796. * @default 'none'
  797. */
  798. this.updateBeforeType = NodeUpdateType.NONE;
  799. /**
  800. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  801. *
  802. * @type {string}
  803. * @default 'none'
  804. */
  805. this.updateAfterType = NodeUpdateType.NONE;
  806. /**
  807. * The UUID of the node.
  808. *
  809. * @type {string}
  810. * @readonly
  811. */
  812. this.uuid = MathUtils.generateUUID();
  813. /**
  814. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  815. *
  816. * @type {number}
  817. * @readonly
  818. * @default 0
  819. */
  820. this.version = 0;
  821. /**
  822. * Whether this node is global or not. This property is relevant for the internal
  823. * node caching system. All nodes which should be declared just once should
  824. * set this flag to `true` (a typical example is {@link AttributeNode}).
  825. *
  826. * @type {boolean}
  827. * @default false
  828. */
  829. this.global = false;
  830. /**
  831. * Create a list of parents for this node during the build process.
  832. *
  833. * @type {boolean}
  834. * @default false
  835. */
  836. this.parents = false;
  837. /**
  838. * This flag can be used for type testing.
  839. *
  840. * @type {boolean}
  841. * @readonly
  842. * @default true
  843. */
  844. this.isNode = true;
  845. // private
  846. /**
  847. * The cache key of this node.
  848. *
  849. * @private
  850. * @type {?number}
  851. * @default null
  852. */
  853. this._cacheKey = null;
  854. /**
  855. * The cache key 's version.
  856. *
  857. * @private
  858. * @type {number}
  859. * @default 0
  860. */
  861. this._cacheKeyVersion = 0;
  862. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  863. }
  864. /**
  865. * Set this property to `true` when the node should be regenerated.
  866. *
  867. * @type {boolean}
  868. * @default false
  869. * @param {boolean} value
  870. */
  871. set needsUpdate( value ) {
  872. if ( value === true ) {
  873. this.version ++;
  874. }
  875. }
  876. /**
  877. * The type of the class. The value is usually the constructor name.
  878. *
  879. * @type {string}
  880. * @readonly
  881. */
  882. get type() {
  883. return this.constructor.type;
  884. }
  885. /**
  886. * Convenient method for defining {@link Node#update}.
  887. *
  888. * @param {Function} callback - The update method.
  889. * @param {string} updateType - The update type.
  890. * @return {Node} A reference to this node.
  891. */
  892. onUpdate( callback, updateType ) {
  893. this.updateType = updateType;
  894. this.update = callback.bind( this.getSelf() );
  895. return this;
  896. }
  897. /**
  898. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  899. * this method automatically sets the update type to `FRAME`.
  900. *
  901. * @param {Function} callback - The update method.
  902. * @return {Node} A reference to this node.
  903. */
  904. onFrameUpdate( callback ) {
  905. return this.onUpdate( callback, NodeUpdateType.FRAME );
  906. }
  907. /**
  908. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  909. * this method automatically sets the update type to `RENDER`.
  910. *
  911. * @param {Function} callback - The update method.
  912. * @return {Node} A reference to this node.
  913. */
  914. onRenderUpdate( callback ) {
  915. return this.onUpdate( callback, NodeUpdateType.RENDER );
  916. }
  917. /**
  918. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  919. * this method automatically sets the update type to `OBJECT`.
  920. *
  921. * @param {Function} callback - The update method.
  922. * @return {Node} A reference to this node.
  923. */
  924. onObjectUpdate( callback ) {
  925. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  926. }
  927. /**
  928. * Convenient method for defining {@link Node#updateReference}.
  929. *
  930. * @param {Function} callback - The update method.
  931. * @return {Node} A reference to this node.
  932. */
  933. onReference( callback ) {
  934. this.updateReference = callback.bind( this.getSelf() );
  935. return this;
  936. }
  937. /**
  938. * The `this` reference might point to a Proxy so this method can be used
  939. * to get the reference to the actual node instance.
  940. *
  941. * @return {Node} A reference to the node.
  942. */
  943. getSelf() {
  944. // Returns non-node object.
  945. return this.self || this;
  946. }
  947. /**
  948. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  949. * to such objects based on a given state (e.g. the current node frame or builder).
  950. *
  951. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  952. * @return {any} The updated reference.
  953. */
  954. updateReference( /*state*/ ) {
  955. return this;
  956. }
  957. /**
  958. * By default this method returns the value of the {@link Node#global} flag. This method
  959. * can be overwritten in derived classes if an analytical way is required to determine the
  960. * global cache referring to the current shader-stage.
  961. *
  962. * @param {NodeBuilder} builder - The current node builder.
  963. * @return {boolean} Whether this node is global or not.
  964. */
  965. isGlobal( /*builder*/ ) {
  966. return this.global;
  967. }
  968. /**
  969. * Generator function that can be used to iterate over the child nodes.
  970. *
  971. * @generator
  972. * @yields {Node} A child node.
  973. */
  974. * getChildren() {
  975. for ( const { childNode } of getNodeChildren( this ) ) {
  976. yield childNode;
  977. }
  978. }
  979. /**
  980. * Calling this method dispatches the `dispose` event. This event can be used
  981. * to register event listeners for clean up tasks.
  982. */
  983. dispose() {
  984. this.dispatchEvent( { type: 'dispose' } );
  985. }
  986. /**
  987. * Callback for {@link Node#traverse}.
  988. *
  989. * @callback traverseCallback
  990. * @param {Node} node - The current node.
  991. */
  992. /**
  993. * Can be used to traverse through the node's hierarchy.
  994. *
  995. * @param {traverseCallback} callback - A callback that is executed per node.
  996. */
  997. traverse( callback ) {
  998. callback( this );
  999. for ( const childNode of this.getChildren() ) {
  1000. childNode.traverse( callback );
  1001. }
  1002. }
  1003. /**
  1004. * Returns the cache key for this node.
  1005. *
  1006. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1007. * @return {number} The cache key of the node.
  1008. */
  1009. getCacheKey( force = false ) {
  1010. force = force || this.version !== this._cacheKeyVersion;
  1011. if ( force === true || this._cacheKey === null ) {
  1012. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  1013. this._cacheKeyVersion = this.version;
  1014. }
  1015. return this._cacheKey;
  1016. }
  1017. /**
  1018. * Generate a custom cache key for this node.
  1019. *
  1020. * @return {number} The cache key of the node.
  1021. */
  1022. customCacheKey() {
  1023. return 0;
  1024. }
  1025. /**
  1026. * Returns the references to this node which is by default `this`.
  1027. *
  1028. * @return {Node} A reference to this node.
  1029. */
  1030. getScope() {
  1031. return this;
  1032. }
  1033. /**
  1034. * Returns the hash of the node which is used to identify the node. By default it's
  1035. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1036. * depending on their implementation.
  1037. *
  1038. * @param {NodeBuilder} builder - The current node builder.
  1039. * @return {string} The hash.
  1040. */
  1041. getHash( /*builder*/ ) {
  1042. return this.uuid;
  1043. }
  1044. /**
  1045. * Returns the update type of {@link Node#update}.
  1046. *
  1047. * @return {NodeUpdateType} The update type.
  1048. */
  1049. getUpdateType() {
  1050. return this.updateType;
  1051. }
  1052. /**
  1053. * Returns the update type of {@link Node#updateBefore}.
  1054. *
  1055. * @return {NodeUpdateType} The update type.
  1056. */
  1057. getUpdateBeforeType() {
  1058. return this.updateBeforeType;
  1059. }
  1060. /**
  1061. * Returns the update type of {@link Node#updateAfter}.
  1062. *
  1063. * @return {NodeUpdateType} The update type.
  1064. */
  1065. getUpdateAfterType() {
  1066. return this.updateAfterType;
  1067. }
  1068. /**
  1069. * Certain types are composed of multiple elements. For example a `vec3`
  1070. * is composed of three `float` values. This method returns the type of
  1071. * these elements.
  1072. *
  1073. * @param {NodeBuilder} builder - The current node builder.
  1074. * @return {string} The type of the node.
  1075. */
  1076. getElementType( builder ) {
  1077. const type = this.getNodeType( builder );
  1078. const elementType = builder.getElementType( type );
  1079. return elementType;
  1080. }
  1081. /**
  1082. * Returns the node member type for the given name.
  1083. *
  1084. * @param {NodeBuilder} builder - The current node builder.
  1085. * @param {string} name - The name of the member.
  1086. * @return {string} The type of the node.
  1087. */
  1088. getMemberType( /*builder, name*/ ) {
  1089. return 'void';
  1090. }
  1091. /**
  1092. * Returns the node's type.
  1093. *
  1094. * @param {NodeBuilder} builder - The current node builder.
  1095. * @return {string} The type of the node.
  1096. */
  1097. getNodeType( builder ) {
  1098. const nodeProperties = builder.getNodeProperties( this );
  1099. if ( nodeProperties.outputNode ) {
  1100. return nodeProperties.outputNode.getNodeType( builder );
  1101. }
  1102. return this.nodeType;
  1103. }
  1104. /**
  1105. * This method is used during the build process of a node and ensures
  1106. * equal nodes are not built multiple times but just once. For example if
  1107. * `attribute( 'uv' )` is used multiple times by the user, the build
  1108. * process makes sure to process just the first node.
  1109. *
  1110. * @param {NodeBuilder} builder - The current node builder.
  1111. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1112. */
  1113. getShared( builder ) {
  1114. const hash = this.getHash( builder );
  1115. const nodeFromHash = builder.getNodeFromHash( hash );
  1116. return nodeFromHash || this;
  1117. }
  1118. /**
  1119. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1120. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1121. * The output node must be returned in the `return` statement.
  1122. *
  1123. * @param {NodeBuilder} builder - The current node builder.
  1124. * @return {?Node} The output node.
  1125. */
  1126. setup( builder ) {
  1127. const nodeProperties = builder.getNodeProperties( this );
  1128. let index = 0;
  1129. for ( const childNode of this.getChildren() ) {
  1130. nodeProperties[ 'node' + index ++ ] = childNode;
  1131. }
  1132. // return a outputNode if exists or null
  1133. return nodeProperties.outputNode || null;
  1134. }
  1135. /**
  1136. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1137. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1138. *
  1139. * @param {NodeBuilder} builder - The current node builder.
  1140. * @param {?Node} output - The target output node.
  1141. */
  1142. analyze( builder, output = null ) {
  1143. const usageCount = builder.increaseUsage( this );
  1144. if ( this.parents === true ) {
  1145. const nodeData = builder.getDataFromNode( this, 'any' );
  1146. nodeData.stages = nodeData.stages || {};
  1147. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1148. nodeData.stages[ builder.shaderStage ].push( output );
  1149. }
  1150. if ( usageCount === 1 ) {
  1151. // node flow children
  1152. const nodeProperties = builder.getNodeProperties( this );
  1153. for ( const childNode of Object.values( nodeProperties ) ) {
  1154. if ( childNode && childNode.isNode === true ) {
  1155. childNode.build( builder, this );
  1156. }
  1157. }
  1158. }
  1159. }
  1160. /**
  1161. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1162. * This state builds the output node and returns the resulting shader string.
  1163. *
  1164. * @param {NodeBuilder} builder - The current node builder.
  1165. * @param {?string} output - Can be used to define the output type.
  1166. * @return {?string} The generated shader string.
  1167. */
  1168. generate( builder, output ) {
  1169. const { outputNode } = builder.getNodeProperties( this );
  1170. if ( outputNode && outputNode.isNode === true ) {
  1171. return outputNode.build( builder, output );
  1172. }
  1173. }
  1174. /**
  1175. * The method can be implemented to update the node's internal state before it is used to render an object.
  1176. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1177. *
  1178. * @abstract
  1179. * @param {NodeFrame} frame - A reference to the current node frame.
  1180. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1181. */
  1182. updateBefore( /*frame*/ ) {
  1183. console.warn( 'Abstract function.' );
  1184. }
  1185. /**
  1186. * The method can be implemented to update the node's internal state after it was used to render an object.
  1187. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1188. *
  1189. * @abstract
  1190. * @param {NodeFrame} frame - A reference to the current node frame.
  1191. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1192. */
  1193. updateAfter( /*frame*/ ) {
  1194. console.warn( 'Abstract function.' );
  1195. }
  1196. /**
  1197. * The method can be implemented to update the node's internal state when it is used to render an object.
  1198. * The {@link Node#updateType} property defines how often the update is executed.
  1199. *
  1200. * @abstract
  1201. * @param {NodeFrame} frame - A reference to the current node frame.
  1202. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1203. */
  1204. update( /*frame*/ ) {
  1205. console.warn( 'Abstract function.' );
  1206. }
  1207. /**
  1208. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1209. * - **setup**: Prepares the node and its children for the build process. This process can also create new nodes. Returns the node itself or a variant.
  1210. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1211. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1212. *
  1213. * @param {NodeBuilder} builder - The current node builder.
  1214. * @param {string|Node|null} [output=null] - Can be used to define the output type.
  1215. * @return {Node|string|null} The result of the build process, depending on the build stage.
  1216. */
  1217. build( builder, output = null ) {
  1218. const refNode = this.getShared( builder );
  1219. if ( this !== refNode ) {
  1220. return refNode.build( builder, output );
  1221. }
  1222. //
  1223. const nodeData = builder.getDataFromNode( this );
  1224. nodeData.buildStages = nodeData.buildStages || {};
  1225. nodeData.buildStages[ builder.buildStage ] = true;
  1226. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1227. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1228. // force parent build stage (setup or analyze)
  1229. const previousBuildStage = builder.getBuildStage();
  1230. builder.setBuildStage( parentBuildStage );
  1231. this.build( builder );
  1232. builder.setBuildStage( previousBuildStage );
  1233. }
  1234. //
  1235. builder.addNode( this );
  1236. builder.addChain( this );
  1237. /* Build stages expected results:
  1238. - "setup" -> Node
  1239. - "analyze" -> null
  1240. - "generate" -> String
  1241. */
  1242. let result = null;
  1243. const buildStage = builder.getBuildStage();
  1244. if ( buildStage === 'setup' ) {
  1245. this.updateReference( builder );
  1246. const properties = builder.getNodeProperties( this );
  1247. if ( properties.initialized !== true ) {
  1248. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1249. properties.initialized = true;
  1250. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1251. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1252. // !! no outputNode !!
  1253. //outputNode = builder.stack;
  1254. }*/
  1255. for ( const childNode of Object.values( properties ) ) {
  1256. if ( childNode && childNode.isNode === true ) {
  1257. if ( childNode.parents === true ) {
  1258. const childProperties = builder.getNodeProperties( childNode );
  1259. childProperties.parents = childProperties.parents || [];
  1260. childProperties.parents.push( this );
  1261. }
  1262. childNode.build( builder );
  1263. }
  1264. }
  1265. }
  1266. result = properties.outputNode;
  1267. } else if ( buildStage === 'analyze' ) {
  1268. this.analyze( builder, output );
  1269. } else if ( buildStage === 'generate' ) {
  1270. const isGenerateOnce = this.generate.length === 1;
  1271. if ( isGenerateOnce ) {
  1272. const type = this.getNodeType( builder );
  1273. const nodeData = builder.getDataFromNode( this );
  1274. result = nodeData.snippet;
  1275. if ( result === undefined ) {
  1276. if ( nodeData.generated === undefined ) {
  1277. nodeData.generated = true;
  1278. result = this.generate( builder ) || '';
  1279. nodeData.snippet = result;
  1280. } else {
  1281. console.warn( 'THREE.Node: Recursion detected.', this );
  1282. result = '';
  1283. }
  1284. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1285. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1286. }
  1287. result = builder.format( result, type, output );
  1288. } else {
  1289. result = this.generate( builder, output ) || '';
  1290. }
  1291. }
  1292. builder.removeChain( this );
  1293. builder.addSequentialNode( this );
  1294. return result;
  1295. }
  1296. /**
  1297. * Returns the child nodes as a JSON object.
  1298. *
  1299. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1300. */
  1301. getSerializeChildren() {
  1302. return getNodeChildren( this );
  1303. }
  1304. /**
  1305. * Serializes the node to JSON.
  1306. *
  1307. * @param {Object} json - The output JSON object.
  1308. */
  1309. serialize( json ) {
  1310. const nodeChildren = this.getSerializeChildren();
  1311. const inputNodes = {};
  1312. for ( const { property, index, childNode } of nodeChildren ) {
  1313. if ( index !== undefined ) {
  1314. if ( inputNodes[ property ] === undefined ) {
  1315. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1316. }
  1317. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1318. } else {
  1319. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1320. }
  1321. }
  1322. if ( Object.keys( inputNodes ).length > 0 ) {
  1323. json.inputNodes = inputNodes;
  1324. }
  1325. }
  1326. /**
  1327. * Deserializes the node from the given JSON.
  1328. *
  1329. * @param {Object} json - The JSON object.
  1330. */
  1331. deserialize( json ) {
  1332. if ( json.inputNodes !== undefined ) {
  1333. const nodes = json.meta.nodes;
  1334. for ( const property in json.inputNodes ) {
  1335. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1336. const inputArray = [];
  1337. for ( const uuid of json.inputNodes[ property ] ) {
  1338. inputArray.push( nodes[ uuid ] );
  1339. }
  1340. this[ property ] = inputArray;
  1341. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1342. const inputObject = {};
  1343. for ( const subProperty in json.inputNodes[ property ] ) {
  1344. const uuid = json.inputNodes[ property ][ subProperty ];
  1345. inputObject[ subProperty ] = nodes[ uuid ];
  1346. }
  1347. this[ property ] = inputObject;
  1348. } else {
  1349. const uuid = json.inputNodes[ property ];
  1350. this[ property ] = nodes[ uuid ];
  1351. }
  1352. }
  1353. }
  1354. }
  1355. /**
  1356. * Serializes the node into the three.js JSON Object/Scene format.
  1357. *
  1358. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1359. * @return {Object} The serialized node.
  1360. */
  1361. toJSON( meta ) {
  1362. const { uuid, type } = this;
  1363. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1364. if ( isRoot ) {
  1365. meta = {
  1366. textures: {},
  1367. images: {},
  1368. nodes: {}
  1369. };
  1370. }
  1371. // serialize
  1372. let data = meta.nodes[ uuid ];
  1373. if ( data === undefined ) {
  1374. data = {
  1375. uuid,
  1376. type,
  1377. meta,
  1378. metadata: {
  1379. version: 4.7,
  1380. type: 'Node',
  1381. generator: 'Node.toJSON'
  1382. }
  1383. };
  1384. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1385. this.serialize( data );
  1386. delete data.meta;
  1387. }
  1388. // TODO: Copied from Object3D.toJSON
  1389. function extractFromCache( cache ) {
  1390. const values = [];
  1391. for ( const key in cache ) {
  1392. const data = cache[ key ];
  1393. delete data.metadata;
  1394. values.push( data );
  1395. }
  1396. return values;
  1397. }
  1398. if ( isRoot ) {
  1399. const textures = extractFromCache( meta.textures );
  1400. const images = extractFromCache( meta.images );
  1401. const nodes = extractFromCache( meta.nodes );
  1402. if ( textures.length > 0 ) data.textures = textures;
  1403. if ( images.length > 0 ) data.images = images;
  1404. if ( nodes.length > 0 ) data.nodes = nodes;
  1405. }
  1406. return data;
  1407. }
  1408. }
  1409. /**
  1410. * Base class for representing element access on an array-like
  1411. * node data structures.
  1412. *
  1413. * @augments Node
  1414. */
  1415. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1416. static get type() {
  1417. return 'ArrayElementNode';
  1418. }
  1419. /**
  1420. * Constructs an array element node.
  1421. *
  1422. * @param {Node} node - The array-like node.
  1423. * @param {Node} indexNode - The index node that defines the element access.
  1424. */
  1425. constructor( node, indexNode ) {
  1426. super();
  1427. /**
  1428. * The array-like node.
  1429. *
  1430. * @type {Node}
  1431. */
  1432. this.node = node;
  1433. /**
  1434. * The index node that defines the element access.
  1435. *
  1436. * @type {Node}
  1437. */
  1438. this.indexNode = indexNode;
  1439. /**
  1440. * This flag can be used for type testing.
  1441. *
  1442. * @type {boolean}
  1443. * @readonly
  1444. * @default true
  1445. */
  1446. this.isArrayElementNode = true;
  1447. }
  1448. /**
  1449. * This method is overwritten since the node type is inferred from the array-like node.
  1450. *
  1451. * @param {NodeBuilder} builder - The current node builder.
  1452. * @return {string} The node type.
  1453. */
  1454. getNodeType( builder ) {
  1455. return this.node.getElementType( builder );
  1456. }
  1457. generate( builder ) {
  1458. const indexType = this.indexNode.getNodeType( builder );
  1459. const nodeSnippet = this.node.build( builder );
  1460. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1461. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1462. }
  1463. }
  1464. /**
  1465. * This module is part of the TSL core and usually not used in app level code.
  1466. * It represents a convert operation during the shader generation process
  1467. * meaning it converts the data type of a node to a target data type.
  1468. *
  1469. * @augments Node
  1470. */
  1471. class ConvertNode extends Node {
  1472. static get type() {
  1473. return 'ConvertNode';
  1474. }
  1475. /**
  1476. * Constructs a new convert node.
  1477. *
  1478. * @param {Node} node - The node which type should be converted.
  1479. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1480. */
  1481. constructor( node, convertTo ) {
  1482. super();
  1483. /**
  1484. * The node which type should be converted.
  1485. *
  1486. * @type {Node}
  1487. */
  1488. this.node = node;
  1489. /**
  1490. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1491. *
  1492. * @type {string}
  1493. */
  1494. this.convertTo = convertTo;
  1495. }
  1496. /**
  1497. * This method is overwritten since the implementation tries to infer the best
  1498. * matching type from the {@link ConvertNode#convertTo} property.
  1499. *
  1500. * @param {NodeBuilder} builder - The current node builder.
  1501. * @return {string} The node type.
  1502. */
  1503. getNodeType( builder ) {
  1504. const requestType = this.node.getNodeType( builder );
  1505. let convertTo = null;
  1506. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1507. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1508. convertTo = overloadingType;
  1509. }
  1510. }
  1511. return convertTo;
  1512. }
  1513. serialize( data ) {
  1514. super.serialize( data );
  1515. data.convertTo = this.convertTo;
  1516. }
  1517. deserialize( data ) {
  1518. super.deserialize( data );
  1519. this.convertTo = data.convertTo;
  1520. }
  1521. generate( builder, output ) {
  1522. const node = this.node;
  1523. const type = this.getNodeType( builder );
  1524. const snippet = node.build( builder, type );
  1525. return builder.format( snippet, type, output );
  1526. }
  1527. }
  1528. /**
  1529. * This module uses cache management to create temporary variables
  1530. * if the node is used more than once to prevent duplicate calculations.
  1531. *
  1532. * The class acts as a base class for many other nodes types.
  1533. *
  1534. * @augments Node
  1535. */
  1536. class TempNode extends Node {
  1537. static get type() {
  1538. return 'TempNode';
  1539. }
  1540. /**
  1541. * Constructs a temp node.
  1542. *
  1543. * @param {?string} nodeType - The node type.
  1544. */
  1545. constructor( nodeType = null ) {
  1546. super( nodeType );
  1547. /**
  1548. * This flag can be used for type testing.
  1549. *
  1550. * @type {boolean}
  1551. * @readonly
  1552. * @default true
  1553. */
  1554. this.isTempNode = true;
  1555. }
  1556. /**
  1557. * Whether this node is used more than once in context of other nodes.
  1558. *
  1559. * @param {NodeBuilder} builder - The node builder.
  1560. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1561. */
  1562. hasDependencies( builder ) {
  1563. return builder.getDataFromNode( this ).usageCount > 1;
  1564. }
  1565. build( builder, output ) {
  1566. const buildStage = builder.getBuildStage();
  1567. if ( buildStage === 'generate' ) {
  1568. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1569. const nodeData = builder.getDataFromNode( this );
  1570. if ( nodeData.propertyName !== undefined ) {
  1571. return builder.format( nodeData.propertyName, type, output );
  1572. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1573. const snippet = super.build( builder, type );
  1574. const nodeVar = builder.getVarFromNode( this, null, type );
  1575. const propertyName = builder.getPropertyName( nodeVar );
  1576. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1577. nodeData.snippet = snippet;
  1578. nodeData.propertyName = propertyName;
  1579. return builder.format( nodeData.propertyName, type, output );
  1580. }
  1581. }
  1582. return super.build( builder, output );
  1583. }
  1584. }
  1585. /**
  1586. * This module is part of the TSL core and usually not used in app level code.
  1587. * It represents a join operation during the shader generation process.
  1588. * For example in can compose/join two single floats into a `vec2` type.
  1589. *
  1590. * @augments TempNode
  1591. */
  1592. class JoinNode extends TempNode {
  1593. static get type() {
  1594. return 'JoinNode';
  1595. }
  1596. /**
  1597. * Constructs a new join node.
  1598. *
  1599. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1600. * @param {?string} [nodeType=null] - The node type.
  1601. */
  1602. constructor( nodes = [], nodeType = null ) {
  1603. super( nodeType );
  1604. /**
  1605. * An array of nodes that should be joined.
  1606. *
  1607. * @type {Array<Node>}
  1608. */
  1609. this.nodes = nodes;
  1610. }
  1611. /**
  1612. * This method is overwritten since the node type must be inferred from the
  1613. * joined data length if not explicitly defined.
  1614. *
  1615. * @param {NodeBuilder} builder - The current node builder.
  1616. * @return {string} The node type.
  1617. */
  1618. getNodeType( builder ) {
  1619. if ( this.nodeType !== null ) {
  1620. return builder.getVectorType( this.nodeType );
  1621. }
  1622. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1623. }
  1624. generate( builder, output ) {
  1625. const type = this.getNodeType( builder );
  1626. const maxLength = builder.getTypeLength( type );
  1627. const nodes = this.nodes;
  1628. const primitiveType = builder.getComponentType( type );
  1629. const snippetValues = [];
  1630. let length = 0;
  1631. for ( const input of nodes ) {
  1632. if ( length >= maxLength ) {
  1633. console.error( `THREE.TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1634. break;
  1635. }
  1636. let inputType = input.getNodeType( builder );
  1637. let inputTypeLength = builder.getTypeLength( inputType );
  1638. let inputSnippet;
  1639. if ( length + inputTypeLength > maxLength ) {
  1640. console.error( `THREE.TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1641. inputTypeLength = maxLength - length;
  1642. inputType = builder.getTypeFromLength( inputTypeLength );
  1643. }
  1644. length += inputTypeLength;
  1645. inputSnippet = input.build( builder, inputType );
  1646. const inputPrimitiveType = builder.getComponentType( inputType );
  1647. if ( inputPrimitiveType !== primitiveType ) {
  1648. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1649. }
  1650. snippetValues.push( inputSnippet );
  1651. }
  1652. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1653. return builder.format( snippet, type, output );
  1654. }
  1655. }
  1656. const _stringVectorComponents = vectorComponents.join( '' );
  1657. /**
  1658. * This module is part of the TSL core and usually not used in app level code.
  1659. * `SplitNode` represents a property access operation which means it is
  1660. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1661. * For example:
  1662. * ```js
  1663. * const redValue = color.r;
  1664. * ```
  1665. *
  1666. * @augments Node
  1667. */
  1668. class SplitNode extends Node {
  1669. static get type() {
  1670. return 'SplitNode';
  1671. }
  1672. /**
  1673. * Constructs a new split node.
  1674. *
  1675. * @param {Node} node - The node that should be accessed.
  1676. * @param {string} [components='x'] - The components that should be accessed.
  1677. */
  1678. constructor( node, components = 'x' ) {
  1679. super();
  1680. /**
  1681. * The node that should be accessed.
  1682. *
  1683. * @type {Node}
  1684. */
  1685. this.node = node;
  1686. /**
  1687. * The components that should be accessed.
  1688. *
  1689. * @type {string}
  1690. */
  1691. this.components = components;
  1692. /**
  1693. * This flag can be used for type testing.
  1694. *
  1695. * @type {boolean}
  1696. * @readonly
  1697. * @default true
  1698. */
  1699. this.isSplitNode = true;
  1700. }
  1701. /**
  1702. * Returns the vector length which is computed based on the requested components.
  1703. *
  1704. * @return {number} The vector length.
  1705. */
  1706. getVectorLength() {
  1707. let vectorLength = this.components.length;
  1708. for ( const c of this.components ) {
  1709. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1710. }
  1711. return vectorLength;
  1712. }
  1713. /**
  1714. * Returns the component type of the node's type.
  1715. *
  1716. * @param {NodeBuilder} builder - The current node builder.
  1717. * @return {string} The component type.
  1718. */
  1719. getComponentType( builder ) {
  1720. return builder.getComponentType( this.node.getNodeType( builder ) );
  1721. }
  1722. /**
  1723. * This method is overwritten since the node type is inferred from requested components.
  1724. *
  1725. * @param {NodeBuilder} builder - The current node builder.
  1726. * @return {string} The node type.
  1727. */
  1728. getNodeType( builder ) {
  1729. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1730. }
  1731. generate( builder, output ) {
  1732. const node = this.node;
  1733. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1734. let snippet = null;
  1735. if ( nodeTypeLength > 1 ) {
  1736. let type = null;
  1737. const componentsLength = this.getVectorLength();
  1738. if ( componentsLength >= nodeTypeLength ) {
  1739. // needed expand the input node
  1740. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1741. }
  1742. const nodeSnippet = node.build( builder, type );
  1743. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1744. // unnecessary swizzle
  1745. snippet = builder.format( nodeSnippet, type, output );
  1746. } else {
  1747. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1748. }
  1749. } else {
  1750. // ignore .components if .node returns float/integer
  1751. snippet = node.build( builder, output );
  1752. }
  1753. return snippet;
  1754. }
  1755. serialize( data ) {
  1756. super.serialize( data );
  1757. data.components = this.components;
  1758. }
  1759. deserialize( data ) {
  1760. super.deserialize( data );
  1761. this.components = data.components;
  1762. }
  1763. }
  1764. /**
  1765. * This module is part of the TSL core and usually not used in app level code.
  1766. * `SetNode` represents a set operation which means it is used to implement any
  1767. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1768. * For example:
  1769. * ```js
  1770. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1771. * ```
  1772. *
  1773. * @augments TempNode
  1774. */
  1775. class SetNode extends TempNode {
  1776. static get type() {
  1777. return 'SetNode';
  1778. }
  1779. /**
  1780. * Constructs a new set node.
  1781. *
  1782. * @param {Node} sourceNode - The node that should be updated.
  1783. * @param {string} components - The components that should be updated.
  1784. * @param {Node} targetNode - The value node.
  1785. */
  1786. constructor( sourceNode, components, targetNode ) {
  1787. super();
  1788. /**
  1789. * The node that should be updated.
  1790. *
  1791. * @type {Node}
  1792. */
  1793. this.sourceNode = sourceNode;
  1794. /**
  1795. * The components that should be updated.
  1796. *
  1797. * @type {string}
  1798. */
  1799. this.components = components;
  1800. /**
  1801. * The value node.
  1802. *
  1803. * @type {Node}
  1804. */
  1805. this.targetNode = targetNode;
  1806. }
  1807. /**
  1808. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1809. *
  1810. * @param {NodeBuilder} builder - The current node builder.
  1811. * @return {string} The node type.
  1812. */
  1813. getNodeType( builder ) {
  1814. return this.sourceNode.getNodeType( builder );
  1815. }
  1816. generate( builder ) {
  1817. const { sourceNode, components, targetNode } = this;
  1818. const sourceType = this.getNodeType( builder );
  1819. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1820. const targetType = builder.getTypeFromLength( components.length, componentType );
  1821. const targetSnippet = targetNode.build( builder, targetType );
  1822. const sourceSnippet = sourceNode.build( builder, sourceType );
  1823. const length = builder.getTypeLength( sourceType );
  1824. const snippetValues = [];
  1825. for ( let i = 0; i < length; i ++ ) {
  1826. const component = vectorComponents[ i ];
  1827. if ( component === components[ 0 ] ) {
  1828. snippetValues.push( targetSnippet );
  1829. i += components.length - 1;
  1830. } else {
  1831. snippetValues.push( sourceSnippet + '.' + component );
  1832. }
  1833. }
  1834. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1835. }
  1836. }
  1837. /**
  1838. * This module is part of the TSL core and usually not used in app level code.
  1839. * It represents a flip operation during the shader generation process
  1840. * meaning it flips normalized values with the following formula:
  1841. * ```
  1842. * x = 1 - x;
  1843. * ```
  1844. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1845. * `flipSTPQ()` method invocations on node objects. For example:
  1846. * ```js
  1847. * uvNode = uvNode.flipY();
  1848. * ```
  1849. *
  1850. * @augments TempNode
  1851. */
  1852. class FlipNode extends TempNode {
  1853. static get type() {
  1854. return 'FlipNode';
  1855. }
  1856. /**
  1857. * Constructs a new flip node.
  1858. *
  1859. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1860. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1861. */
  1862. constructor( sourceNode, components ) {
  1863. super();
  1864. /**
  1865. * The node which component(s) should be flipped.
  1866. *
  1867. * @type {Node}
  1868. */
  1869. this.sourceNode = sourceNode;
  1870. /**
  1871. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1872. *
  1873. * @type {string}
  1874. */
  1875. this.components = components;
  1876. }
  1877. /**
  1878. * This method is overwritten since the node type is inferred from the source node.
  1879. *
  1880. * @param {NodeBuilder} builder - The current node builder.
  1881. * @return {string} The node type.
  1882. */
  1883. getNodeType( builder ) {
  1884. return this.sourceNode.getNodeType( builder );
  1885. }
  1886. generate( builder ) {
  1887. const { components, sourceNode } = this;
  1888. const sourceType = this.getNodeType( builder );
  1889. const sourceSnippet = sourceNode.build( builder );
  1890. const sourceCache = builder.getVarFromNode( this );
  1891. const sourceProperty = builder.getPropertyName( sourceCache );
  1892. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1893. const length = builder.getTypeLength( sourceType );
  1894. const snippetValues = [];
  1895. let componentIndex = 0;
  1896. for ( let i = 0; i < length; i ++ ) {
  1897. const component = vectorComponents[ i ];
  1898. if ( component === components[ componentIndex ] ) {
  1899. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1900. componentIndex ++;
  1901. } else {
  1902. snippetValues.push( sourceProperty + '.' + component );
  1903. }
  1904. }
  1905. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1906. }
  1907. }
  1908. /**
  1909. * Base class for representing data input nodes.
  1910. *
  1911. * @augments Node
  1912. */
  1913. class InputNode extends Node {
  1914. static get type() {
  1915. return 'InputNode';
  1916. }
  1917. /**
  1918. * Constructs a new input node.
  1919. *
  1920. * @param {any} value - The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1921. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1922. */
  1923. constructor( value, nodeType = null ) {
  1924. super( nodeType );
  1925. /**
  1926. * This flag can be used for type testing.
  1927. *
  1928. * @type {boolean}
  1929. * @readonly
  1930. * @default true
  1931. */
  1932. this.isInputNode = true;
  1933. /**
  1934. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1935. *
  1936. * @type {any}
  1937. */
  1938. this.value = value;
  1939. /**
  1940. * The precision of the value in the shader.
  1941. *
  1942. * @type {?('low'|'medium'|'high')}
  1943. * @default null
  1944. */
  1945. this.precision = null;
  1946. }
  1947. getNodeType( /*builder*/ ) {
  1948. if ( this.nodeType === null ) {
  1949. return getValueType( this.value );
  1950. }
  1951. return this.nodeType;
  1952. }
  1953. /**
  1954. * Returns the input type of the node which is by default the node type. Derived modules
  1955. * might overwrite this method and use a fixed type or compute one analytically.
  1956. *
  1957. * A typical example for different input and node types are textures. The input type of a
  1958. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1959. *
  1960. * @param {NodeBuilder} builder - The current node builder.
  1961. * @return {string} The input type.
  1962. */
  1963. getInputType( builder ) {
  1964. return this.getNodeType( builder );
  1965. }
  1966. /**
  1967. * Sets the precision to the given value. The method can be
  1968. * overwritten in derived classes if the final precision must be computed
  1969. * analytically.
  1970. *
  1971. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1972. * @return {InputNode} A reference to this node.
  1973. */
  1974. setPrecision( precision ) {
  1975. this.precision = precision;
  1976. return this;
  1977. }
  1978. serialize( data ) {
  1979. super.serialize( data );
  1980. data.value = this.value;
  1981. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1982. data.valueType = getValueType( this.value );
  1983. data.nodeType = this.nodeType;
  1984. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1985. data.precision = this.precision;
  1986. }
  1987. deserialize( data ) {
  1988. super.deserialize( data );
  1989. this.nodeType = data.nodeType;
  1990. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1991. this.precision = data.precision || null;
  1992. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1993. }
  1994. generate( /*builder, output*/ ) {
  1995. console.warn( 'Abstract function.' );
  1996. }
  1997. }
  1998. const _regNum = /float|u?int/;
  1999. /**
  2000. * Class for representing a constant value in the shader.
  2001. *
  2002. * @augments InputNode
  2003. */
  2004. class ConstNode extends InputNode {
  2005. static get type() {
  2006. return 'ConstNode';
  2007. }
  2008. /**
  2009. * Constructs a new input node.
  2010. *
  2011. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2012. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2013. */
  2014. constructor( value, nodeType = null ) {
  2015. super( value, nodeType );
  2016. /**
  2017. * This flag can be used for type testing.
  2018. *
  2019. * @type {boolean}
  2020. * @readonly
  2021. * @default true
  2022. */
  2023. this.isConstNode = true;
  2024. }
  2025. /**
  2026. * Generates the shader string of the value with the current node builder.
  2027. *
  2028. * @param {NodeBuilder} builder - The current node builder.
  2029. * @return {string} The generated value as a shader string.
  2030. */
  2031. generateConst( builder ) {
  2032. return builder.generateConst( this.getNodeType( builder ), this.value );
  2033. }
  2034. generate( builder, output ) {
  2035. const type = this.getNodeType( builder );
  2036. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2037. return builder.generateConst( output, this.value );
  2038. }
  2039. return builder.format( this.generateConst( builder ), type, output );
  2040. }
  2041. }
  2042. /**
  2043. * Base class for representing member access on an object-like
  2044. * node data structures.
  2045. *
  2046. * @augments Node
  2047. */
  2048. class MemberNode extends Node {
  2049. static get type() {
  2050. return 'MemberNode';
  2051. }
  2052. /**
  2053. * Constructs an array element node.
  2054. *
  2055. * @param {Node} node - The array-like node.
  2056. * @param {string} property - The property name.
  2057. */
  2058. constructor( node, property ) {
  2059. super();
  2060. /**
  2061. * The array-like node.
  2062. *
  2063. * @type {Node}
  2064. */
  2065. this.node = node;
  2066. /**
  2067. * The property name.
  2068. *
  2069. * @type {Node}
  2070. */
  2071. this.property = property;
  2072. /**
  2073. * This flag can be used for type testing.
  2074. *
  2075. * @type {boolean}
  2076. * @readonly
  2077. * @default true
  2078. */
  2079. this.isMemberNode = true;
  2080. }
  2081. getNodeType( builder ) {
  2082. return this.node.getMemberType( builder, this.property );
  2083. }
  2084. generate( builder ) {
  2085. const propertyName = this.node.build( builder );
  2086. return propertyName + '.' + this.property;
  2087. }
  2088. }
  2089. let currentStack = null;
  2090. const NodeElements = new Map();
  2091. function addMethodChaining( name, nodeElement ) {
  2092. if ( NodeElements.has( name ) ) {
  2093. console.warn( `THREE.TSL: Redefinition of method chaining '${ name }'.` );
  2094. return;
  2095. }
  2096. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2097. NodeElements.set( name, nodeElement );
  2098. }
  2099. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2100. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2101. const shaderNodeHandler = {
  2102. setup( NodeClosure, params ) {
  2103. const inputs = params.shift();
  2104. return NodeClosure( nodeObjects( inputs ), ...params );
  2105. },
  2106. get( node, prop, nodeObj ) {
  2107. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2108. if ( node.isStackNode !== true && prop === 'assign' ) {
  2109. return ( ...params ) => {
  2110. currentStack.assign( nodeObj, ...params );
  2111. return nodeObj;
  2112. };
  2113. } else if ( NodeElements.has( prop ) ) {
  2114. const nodeElement = NodeElements.get( prop );
  2115. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2116. } else if ( prop === 'self' ) {
  2117. return node;
  2118. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2119. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2120. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2121. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2122. // accessing properties ( swizzle )
  2123. prop = parseSwizzle( prop );
  2124. return nodeObject( new SplitNode( nodeObj, prop ) );
  2125. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2126. // set properties ( swizzle ) and sort to xyzw sequence
  2127. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2128. return ( value ) => nodeObject( new SetNode( node, prop, nodeObject( value ) ) );
  2129. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2130. // set properties ( swizzle ) and sort to xyzw sequence
  2131. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2132. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2133. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2134. // accessing property
  2135. if ( prop === 'width' ) prop = 'x';
  2136. else if ( prop === 'height' ) prop = 'y';
  2137. else if ( prop === 'depth' ) prop = 'z';
  2138. return nodeObject( new SplitNode( node, prop ) );
  2139. } else if ( /^\d+$/.test( prop ) === true ) {
  2140. // accessing array
  2141. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2142. } else if ( /^get$/.test( prop ) === true ) {
  2143. // accessing properties
  2144. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2145. }
  2146. }
  2147. return Reflect.get( node, prop, nodeObj );
  2148. },
  2149. set( node, prop, value, nodeObj ) {
  2150. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2151. // setting properties
  2152. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2153. nodeObj[ prop ].assign( value );
  2154. return true;
  2155. }
  2156. }
  2157. return Reflect.set( node, prop, value, nodeObj );
  2158. }
  2159. };
  2160. const nodeObjectsCacheMap = new WeakMap();
  2161. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2162. const ShaderNodeObject = function ( obj, altType = null ) {
  2163. const type = getValueType( obj );
  2164. if ( type === 'node' ) {
  2165. let nodeObject = nodeObjectsCacheMap.get( obj );
  2166. if ( nodeObject === undefined ) {
  2167. nodeObject = new Proxy( obj, shaderNodeHandler );
  2168. nodeObjectsCacheMap.set( obj, nodeObject );
  2169. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2170. }
  2171. return nodeObject;
  2172. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2173. return nodeObject( getConstNode( obj, altType ) );
  2174. } else if ( type === 'shader' ) {
  2175. return Fn( obj );
  2176. }
  2177. return obj;
  2178. };
  2179. const ShaderNodeObjects = function ( objects, altType = null ) {
  2180. for ( const name in objects ) {
  2181. objects[ name ] = nodeObject( objects[ name ], altType );
  2182. }
  2183. return objects;
  2184. };
  2185. const ShaderNodeArray = function ( array, altType = null ) {
  2186. const len = array.length;
  2187. for ( let i = 0; i < len; i ++ ) {
  2188. array[ i ] = nodeObject( array[ i ], altType );
  2189. }
  2190. return array;
  2191. };
  2192. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2193. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2194. let fn, name = scope, minParams, maxParams;
  2195. function verifyParamsLimit( params ) {
  2196. let tslName;
  2197. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2198. else tslName = NodeClass.type;
  2199. if ( minParams !== undefined && params.length < minParams ) {
  2200. console.error( `THREE.TSL: "${ tslName }" parameter length is less than minimum required.` );
  2201. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2202. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2203. console.error( `THREE.TSL: "${ tslName }" parameter length exceeds limit.` );
  2204. return params.slice( 0, maxParams );
  2205. }
  2206. return params;
  2207. }
  2208. if ( scope === null ) {
  2209. fn = ( ...params ) => {
  2210. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2211. };
  2212. } else if ( factor !== null ) {
  2213. factor = nodeObject( factor );
  2214. fn = ( ...params ) => {
  2215. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2216. };
  2217. } else {
  2218. fn = ( ...params ) => {
  2219. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2220. };
  2221. }
  2222. fn.setParameterLength = ( ...params ) => {
  2223. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2224. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2225. return fn;
  2226. };
  2227. fn.setName = ( value ) => {
  2228. name = value;
  2229. return fn;
  2230. };
  2231. return fn;
  2232. };
  2233. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2234. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2235. };
  2236. class ShaderCallNodeInternal extends Node {
  2237. constructor( shaderNode, inputNodes ) {
  2238. super();
  2239. this.shaderNode = shaderNode;
  2240. this.inputNodes = inputNodes;
  2241. this.isShaderCallNodeInternal = true;
  2242. }
  2243. getNodeType( builder ) {
  2244. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2245. }
  2246. getMemberType( builder, name ) {
  2247. return this.getOutputNode( builder ).getMemberType( builder, name );
  2248. }
  2249. call( builder ) {
  2250. const { shaderNode, inputNodes } = this;
  2251. const properties = builder.getNodeProperties( shaderNode );
  2252. const onceNS = shaderNode.namespace && shaderNode.namespace === builder.namespace ? builder.getNamespace( 'once' ) : 'once';
  2253. if ( properties[ onceNS ] ) {
  2254. return properties[ onceNS ];
  2255. }
  2256. //
  2257. let result = null;
  2258. if ( shaderNode.layout ) {
  2259. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2260. if ( functionNodesCacheMap === undefined ) {
  2261. functionNodesCacheMap = new WeakMap();
  2262. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2263. }
  2264. let functionNode = functionNodesCacheMap.get( shaderNode );
  2265. if ( functionNode === undefined ) {
  2266. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2267. functionNodesCacheMap.set( shaderNode, functionNode );
  2268. }
  2269. builder.addInclude( functionNode );
  2270. result = nodeObject( functionNode.call( inputNodes ) );
  2271. } else {
  2272. const jsFunc = shaderNode.jsFunc;
  2273. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2274. result = nodeObject( outputNode );
  2275. }
  2276. if ( shaderNode.once ) {
  2277. properties[ onceNS ] = result;
  2278. }
  2279. return result;
  2280. }
  2281. setupOutput( builder ) {
  2282. builder.addStack();
  2283. builder.stack.outputNode = this.call( builder );
  2284. return builder.removeStack();
  2285. }
  2286. getOutputNode( builder ) {
  2287. const properties = builder.getNodeProperties( this );
  2288. const outputNamespace = builder.getOutputNamespace();
  2289. properties[ outputNamespace ] = properties[ outputNamespace ] || this.setupOutput( builder );
  2290. return properties[ outputNamespace ];
  2291. }
  2292. build( builder, output = null ) {
  2293. let result = null;
  2294. const buildStage = builder.getBuildStage();
  2295. const properties = builder.getNodeProperties( this );
  2296. const outputNamespace = builder.getOutputNamespace();
  2297. const outputNode = this.getOutputNode( builder );
  2298. if ( buildStage === 'setup' ) {
  2299. const initializedNamespace = builder.getNamespace( 'initialized' );
  2300. if ( properties[ initializedNamespace ] !== true ) {
  2301. properties[ initializedNamespace ] = true;
  2302. properties[ outputNamespace ] = this.getOutputNode( builder );
  2303. properties[ outputNamespace ].build( builder );
  2304. }
  2305. result = properties[ outputNamespace ];
  2306. } else if ( buildStage === 'analyze' ) {
  2307. outputNode.build( builder, output );
  2308. } else if ( buildStage === 'generate' ) {
  2309. result = outputNode.build( builder, output ) || '';
  2310. }
  2311. return result;
  2312. }
  2313. }
  2314. class ShaderNodeInternal extends Node {
  2315. constructor( jsFunc, nodeType ) {
  2316. super( nodeType );
  2317. this.jsFunc = jsFunc;
  2318. this.layout = null;
  2319. this.global = true;
  2320. this.once = false;
  2321. this.namespace = null;
  2322. }
  2323. setLayout( layout ) {
  2324. this.layout = layout;
  2325. return this;
  2326. }
  2327. call( inputs = null ) {
  2328. nodeObjects( inputs );
  2329. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2330. }
  2331. setup() {
  2332. return this.call();
  2333. }
  2334. }
  2335. const bools = [ false, true ];
  2336. const uints = [ 0, 1, 2, 3 ];
  2337. const ints = [ -1, -2 ];
  2338. const floats = [ 0.5, 1.5, 1 / 3, 1e-6, 1e6, Math.PI, Math.PI * 2, 1 / Math.PI, 2 / Math.PI, 1 / ( Math.PI * 2 ), Math.PI / 2 ];
  2339. const boolsCacheMap = new Map();
  2340. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2341. const uintsCacheMap = new Map();
  2342. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2343. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2344. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2345. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2346. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2347. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2348. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2349. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2350. const getConstNode = ( value, type ) => {
  2351. if ( constNodesCacheMap.has( value ) ) {
  2352. return constNodesCacheMap.get( value );
  2353. } else if ( value.isNode === true ) {
  2354. return value;
  2355. } else {
  2356. return new ConstNode( value, type );
  2357. }
  2358. };
  2359. const safeGetNodeType = ( node ) => {
  2360. try {
  2361. return node.getNodeType();
  2362. } catch ( _ ) {
  2363. return undefined;
  2364. }
  2365. };
  2366. const ConvertType = function ( type, cacheMap = null ) {
  2367. return ( ...params ) => {
  2368. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2369. params = [ getValueFromType( type, ...params ) ];
  2370. }
  2371. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2372. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2373. }
  2374. if ( params.length === 1 ) {
  2375. const node = getConstNode( params[ 0 ], type );
  2376. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2377. return nodeObject( new ConvertNode( node, type ) );
  2378. }
  2379. const nodes = params.map( param => getConstNode( param ) );
  2380. return nodeObject( new JoinNode( nodes, type ) );
  2381. };
  2382. };
  2383. // exports
  2384. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2385. // utils
  2386. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2387. // shader node base
  2388. function ShaderNode( jsFunc, nodeType ) {
  2389. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2390. }
  2391. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2392. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2393. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2394. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2395. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2396. let fnId = 0;
  2397. const Fn = ( jsFunc, layout = null ) => {
  2398. let nodeType = null;
  2399. if ( layout !== null ) {
  2400. if ( typeof layout === 'object' ) {
  2401. nodeType = layout.return;
  2402. } else {
  2403. if ( typeof layout === 'string' ) {
  2404. nodeType = layout;
  2405. } else {
  2406. console.error( 'THREE.TSL: Invalid layout type.' );
  2407. }
  2408. layout = null;
  2409. }
  2410. }
  2411. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2412. const fn = ( ...params ) => {
  2413. let inputs;
  2414. nodeObjects( params );
  2415. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2416. if ( isArrayAsParameter ) {
  2417. inputs = [ ...params ];
  2418. } else {
  2419. inputs = params[ 0 ];
  2420. }
  2421. const fnCall = shaderNode.call( inputs );
  2422. if ( nodeType === 'void' ) fnCall.toStack();
  2423. return fnCall;
  2424. };
  2425. fn.shaderNode = shaderNode;
  2426. fn.id = shaderNode.id;
  2427. fn.getNodeType = ( ...params ) => shaderNode.getNodeType( ...params );
  2428. fn.getCacheKey = ( ...params ) => shaderNode.getCacheKey( ...params );
  2429. fn.setLayout = ( layout ) => {
  2430. shaderNode.setLayout( layout );
  2431. return fn;
  2432. };
  2433. fn.once = ( namespace = null ) => {
  2434. shaderNode.once = true;
  2435. shaderNode.namespace = namespace;
  2436. return fn;
  2437. };
  2438. if ( layout !== null ) {
  2439. if ( typeof layout.inputs !== 'object' ) {
  2440. const fullLayout = {
  2441. name: 'fn' + fnId ++,
  2442. type: nodeType,
  2443. inputs: []
  2444. };
  2445. for ( const name in layout ) {
  2446. if ( name === 'return' ) continue;
  2447. fullLayout.inputs.push( {
  2448. name: name,
  2449. type: layout[ name ]
  2450. } );
  2451. }
  2452. layout = fullLayout;
  2453. }
  2454. fn.setLayout( layout );
  2455. }
  2456. return fn;
  2457. };
  2458. //
  2459. const setCurrentStack = ( stack ) => {
  2460. currentStack = stack;
  2461. };
  2462. const getCurrentStack = () => currentStack;
  2463. /**
  2464. * Represent a conditional node using if/else statements.
  2465. *
  2466. * ```js
  2467. * If( condition, function )
  2468. * .ElseIf( condition, function )
  2469. * .Else( function )
  2470. * ```
  2471. * @tsl
  2472. * @function
  2473. * @param {...any} params - The parameters for the conditional node.
  2474. * @returns {StackNode} The conditional node.
  2475. */
  2476. const If = ( ...params ) => currentStack.If( ...params );
  2477. /**
  2478. * Represent a conditional node using switch/case statements.
  2479. *
  2480. * ```js
  2481. * Switch( value )
  2482. * .Case( 1, function )
  2483. * .Case( 2, 3, 4, function )
  2484. * .Default( function )
  2485. * ```
  2486. * @tsl
  2487. * @function
  2488. * @param {...any} params - The parameters for the conditional node.
  2489. * @returns {StackNode} The conditional node.
  2490. */
  2491. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2492. /**
  2493. * Add the given node to the current stack.
  2494. *
  2495. * @param {Node} node - The node to add.
  2496. * @returns {Node} The node that was added to the stack.
  2497. */
  2498. function Stack( node ) {
  2499. if ( currentStack ) currentStack.add( node );
  2500. return node;
  2501. }
  2502. addMethodChaining( 'toStack', Stack );
  2503. // types
  2504. const color = new ConvertType( 'color' );
  2505. const float = new ConvertType( 'float', cacheMaps.float );
  2506. const int = new ConvertType( 'int', cacheMaps.ints );
  2507. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2508. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2509. const vec2 = new ConvertType( 'vec2' );
  2510. const ivec2 = new ConvertType( 'ivec2' );
  2511. const uvec2 = new ConvertType( 'uvec2' );
  2512. const bvec2 = new ConvertType( 'bvec2' );
  2513. const vec3 = new ConvertType( 'vec3' );
  2514. const ivec3 = new ConvertType( 'ivec3' );
  2515. const uvec3 = new ConvertType( 'uvec3' );
  2516. const bvec3 = new ConvertType( 'bvec3' );
  2517. const vec4 = new ConvertType( 'vec4' );
  2518. const ivec4 = new ConvertType( 'ivec4' );
  2519. const uvec4 = new ConvertType( 'uvec4' );
  2520. const bvec4 = new ConvertType( 'bvec4' );
  2521. const mat2 = new ConvertType( 'mat2' );
  2522. const mat3 = new ConvertType( 'mat3' );
  2523. const mat4 = new ConvertType( 'mat4' );
  2524. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2525. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2526. addMethodChaining( 'toColor', color );
  2527. addMethodChaining( 'toFloat', float );
  2528. addMethodChaining( 'toInt', int );
  2529. addMethodChaining( 'toUint', uint );
  2530. addMethodChaining( 'toBool', bool );
  2531. addMethodChaining( 'toVec2', vec2 );
  2532. addMethodChaining( 'toIVec2', ivec2 );
  2533. addMethodChaining( 'toUVec2', uvec2 );
  2534. addMethodChaining( 'toBVec2', bvec2 );
  2535. addMethodChaining( 'toVec3', vec3 );
  2536. addMethodChaining( 'toIVec3', ivec3 );
  2537. addMethodChaining( 'toUVec3', uvec3 );
  2538. addMethodChaining( 'toBVec3', bvec3 );
  2539. addMethodChaining( 'toVec4', vec4 );
  2540. addMethodChaining( 'toIVec4', ivec4 );
  2541. addMethodChaining( 'toUVec4', uvec4 );
  2542. addMethodChaining( 'toBVec4', bvec4 );
  2543. addMethodChaining( 'toMat2', mat2 );
  2544. addMethodChaining( 'toMat3', mat3 );
  2545. addMethodChaining( 'toMat4', mat4 );
  2546. // basic nodes
  2547. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2548. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2549. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2550. addMethodChaining( 'element', element );
  2551. addMethodChaining( 'convert', convert );
  2552. // deprecated
  2553. /**
  2554. * @tsl
  2555. * @function
  2556. * @deprecated since r176. Use {@link Stack} instead.
  2557. *
  2558. * @param {Node} node - The node to add.
  2559. * @returns {Function}
  2560. */
  2561. const append = ( node ) => { // @deprecated, r176
  2562. console.warn( 'THREE.TSL: append() has been renamed to Stack().' );
  2563. return Stack( node );
  2564. };
  2565. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2566. console.warn( 'THREE.TSL: .append() has been renamed to .toStack().' );
  2567. return Stack( node );
  2568. } );
  2569. /**
  2570. * @tsl
  2571. * @function
  2572. * @deprecated since r168. Use {@link Fn} instead.
  2573. *
  2574. * @param {...any} params
  2575. * @returns {Function}
  2576. */
  2577. const tslFn = ( ...params ) => { // @deprecated, r168
  2578. console.warn( 'THREE.TSL: tslFn() has been renamed to Fn().' );
  2579. return Fn( ...params );
  2580. };
  2581. /**
  2582. * This class represents a shader property. It can be used
  2583. * to explicitly define a property and assign a value to it.
  2584. *
  2585. * ```js
  2586. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2587. *```
  2588. * `PropertyNode` is used by the engine to predefined common material properties
  2589. * for TSL code.
  2590. *
  2591. * @augments Node
  2592. */
  2593. class PropertyNode extends Node {
  2594. static get type() {
  2595. return 'PropertyNode';
  2596. }
  2597. /**
  2598. * Constructs a new property node.
  2599. *
  2600. * @param {string} nodeType - The type of the node.
  2601. * @param {?string} [name=null] - The name of the property in the shader.
  2602. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2603. */
  2604. constructor( nodeType, name = null, varying = false ) {
  2605. super( nodeType );
  2606. /**
  2607. * The name of the property in the shader. If no name is defined,
  2608. * the node system auto-generates one.
  2609. *
  2610. * @type {?string}
  2611. * @default null
  2612. */
  2613. this.name = name;
  2614. /**
  2615. * Whether this property is a varying or not.
  2616. *
  2617. * @type {boolean}
  2618. * @default false
  2619. */
  2620. this.varying = varying;
  2621. /**
  2622. * This flag can be used for type testing.
  2623. *
  2624. * @type {boolean}
  2625. * @readonly
  2626. * @default true
  2627. */
  2628. this.isPropertyNode = true;
  2629. /**
  2630. * This flag is used for global cache.
  2631. *
  2632. * @type {boolean}
  2633. * @default true
  2634. */
  2635. this.global = true;
  2636. }
  2637. getHash( builder ) {
  2638. return this.name || super.getHash( builder );
  2639. }
  2640. generate( builder ) {
  2641. let nodeVar;
  2642. if ( this.varying === true ) {
  2643. nodeVar = builder.getVaryingFromNode( this, this.name );
  2644. nodeVar.needsInterpolation = true;
  2645. } else {
  2646. nodeVar = builder.getVarFromNode( this, this.name );
  2647. }
  2648. return builder.getPropertyName( nodeVar );
  2649. }
  2650. }
  2651. /**
  2652. * TSL function for creating a property node.
  2653. *
  2654. * @tsl
  2655. * @function
  2656. * @param {string} type - The type of the node.
  2657. * @param {?string} [name=null] - The name of the property in the shader.
  2658. * @returns {PropertyNode}
  2659. */
  2660. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2661. /**
  2662. * TSL function for creating a varying property node.
  2663. *
  2664. * @tsl
  2665. * @function
  2666. * @param {string} type - The type of the node.
  2667. * @param {?string} [name=null] - The name of the varying in the shader.
  2668. * @returns {PropertyNode}
  2669. */
  2670. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2671. /**
  2672. * TSL object that represents the shader variable `DiffuseColor`.
  2673. *
  2674. * @tsl
  2675. * @type {PropertyNode<vec4>}
  2676. */
  2677. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2678. /**
  2679. * TSL object that represents the shader variable `EmissiveColor`.
  2680. *
  2681. * @tsl
  2682. * @type {PropertyNode<vec3>}
  2683. */
  2684. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2685. /**
  2686. * TSL object that represents the shader variable `Roughness`.
  2687. *
  2688. * @tsl
  2689. * @type {PropertyNode<float>}
  2690. */
  2691. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2692. /**
  2693. * TSL object that represents the shader variable `Metalness`.
  2694. *
  2695. * @tsl
  2696. * @type {PropertyNode<float>}
  2697. */
  2698. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2699. /**
  2700. * TSL object that represents the shader variable `Clearcoat`.
  2701. *
  2702. * @tsl
  2703. * @type {PropertyNode<float>}
  2704. */
  2705. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2706. /**
  2707. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2708. *
  2709. * @tsl
  2710. * @type {PropertyNode<float>}
  2711. */
  2712. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2713. /**
  2714. * TSL object that represents the shader variable `Sheen`.
  2715. *
  2716. * @tsl
  2717. * @type {PropertyNode<vec3>}
  2718. */
  2719. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2720. /**
  2721. * TSL object that represents the shader variable `SheenRoughness`.
  2722. *
  2723. * @tsl
  2724. * @type {PropertyNode<float>}
  2725. */
  2726. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2727. /**
  2728. * TSL object that represents the shader variable `Iridescence`.
  2729. *
  2730. * @tsl
  2731. * @type {PropertyNode<float>}
  2732. */
  2733. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2734. /**
  2735. * TSL object that represents the shader variable `IridescenceIOR`.
  2736. *
  2737. * @tsl
  2738. * @type {PropertyNode<float>}
  2739. */
  2740. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2741. /**
  2742. * TSL object that represents the shader variable `IridescenceThickness`.
  2743. *
  2744. * @tsl
  2745. * @type {PropertyNode<float>}
  2746. */
  2747. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2748. /**
  2749. * TSL object that represents the shader variable `AlphaT`.
  2750. *
  2751. * @tsl
  2752. * @type {PropertyNode<float>}
  2753. */
  2754. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2755. /**
  2756. * TSL object that represents the shader variable `Anisotropy`.
  2757. *
  2758. * @tsl
  2759. * @type {PropertyNode<float>}
  2760. */
  2761. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2762. /**
  2763. * TSL object that represents the shader variable `AnisotropyT`.
  2764. *
  2765. * @tsl
  2766. * @type {PropertyNode<vec3>}
  2767. */
  2768. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2769. /**
  2770. * TSL object that represents the shader variable `AnisotropyB`.
  2771. *
  2772. * @tsl
  2773. * @type {PropertyNode<vec3>}
  2774. */
  2775. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2776. /**
  2777. * TSL object that represents the shader variable `SpecularColor`.
  2778. *
  2779. * @tsl
  2780. * @type {PropertyNode<color>}
  2781. */
  2782. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2783. /**
  2784. * TSL object that represents the shader variable `SpecularF90`.
  2785. *
  2786. * @tsl
  2787. * @type {PropertyNode<float>}
  2788. */
  2789. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2790. /**
  2791. * TSL object that represents the shader variable `Shininess`.
  2792. *
  2793. * @tsl
  2794. * @type {PropertyNode<float>}
  2795. */
  2796. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2797. /**
  2798. * TSL object that represents the shader variable `Output`.
  2799. *
  2800. * @tsl
  2801. * @type {PropertyNode<vec4>}
  2802. */
  2803. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2804. /**
  2805. * TSL object that represents the shader variable `dashSize`.
  2806. *
  2807. * @tsl
  2808. * @type {PropertyNode<float>}
  2809. */
  2810. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2811. /**
  2812. * TSL object that represents the shader variable `gapSize`.
  2813. *
  2814. * @tsl
  2815. * @type {PropertyNode<float>}
  2816. */
  2817. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2818. /**
  2819. * TSL object that represents the shader variable `pointWidth`.
  2820. *
  2821. * @tsl
  2822. * @type {PropertyNode<float>}
  2823. */
  2824. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2825. /**
  2826. * TSL object that represents the shader variable `IOR`.
  2827. *
  2828. * @tsl
  2829. * @type {PropertyNode<float>}
  2830. */
  2831. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2832. /**
  2833. * TSL object that represents the shader variable `Transmission`.
  2834. *
  2835. * @tsl
  2836. * @type {PropertyNode<float>}
  2837. */
  2838. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2839. /**
  2840. * TSL object that represents the shader variable `Thickness`.
  2841. *
  2842. * @tsl
  2843. * @type {PropertyNode<float>}
  2844. */
  2845. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2846. /**
  2847. * TSL object that represents the shader variable `AttenuationDistance`.
  2848. *
  2849. * @tsl
  2850. * @type {PropertyNode<float>}
  2851. */
  2852. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2853. /**
  2854. * TSL object that represents the shader variable `AttenuationColor`.
  2855. *
  2856. * @tsl
  2857. * @type {PropertyNode<color>}
  2858. */
  2859. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2860. /**
  2861. * TSL object that represents the shader variable `Dispersion`.
  2862. *
  2863. * @tsl
  2864. * @type {PropertyNode<float>}
  2865. */
  2866. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2867. /**
  2868. * This node can be used to group single instances of {@link UniformNode}
  2869. * and manage them as a uniform buffer.
  2870. *
  2871. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2872. * will be used when defining the {@link UniformNode#groupNode} property.
  2873. *
  2874. * - `objectGroup`: Uniform buffer per object.
  2875. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2876. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2877. *
  2878. * @augments Node
  2879. */
  2880. class UniformGroupNode extends Node {
  2881. static get type() {
  2882. return 'UniformGroupNode';
  2883. }
  2884. /**
  2885. * Constructs a new uniform group node.
  2886. *
  2887. * @param {string} name - The name of the uniform group node.
  2888. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  2889. * @param {number} [order=1] - Influences the internal sorting.
  2890. */
  2891. constructor( name, shared = false, order = 1 ) {
  2892. super( 'string' );
  2893. /**
  2894. * The name of the uniform group node.
  2895. *
  2896. * @type {string}
  2897. */
  2898. this.name = name;
  2899. /**
  2900. * Whether this uniform group node is shared or not.
  2901. *
  2902. * @type {boolean}
  2903. * @default false
  2904. */
  2905. this.shared = shared;
  2906. /**
  2907. * Influences the internal sorting.
  2908. * TODO: Add details when this property should be changed.
  2909. *
  2910. * @type {number}
  2911. * @default 1
  2912. */
  2913. this.order = order;
  2914. /**
  2915. * This flag can be used for type testing.
  2916. *
  2917. * @type {boolean}
  2918. * @readonly
  2919. * @default true
  2920. */
  2921. this.isUniformGroup = true;
  2922. }
  2923. serialize( data ) {
  2924. super.serialize( data );
  2925. data.name = this.name;
  2926. data.version = this.version;
  2927. data.shared = this.shared;
  2928. }
  2929. deserialize( data ) {
  2930. super.deserialize( data );
  2931. this.name = data.name;
  2932. this.version = data.version;
  2933. this.shared = data.shared;
  2934. }
  2935. }
  2936. /**
  2937. * TSL function for creating a uniform group node with the given name.
  2938. *
  2939. * @tsl
  2940. * @function
  2941. * @param {string} name - The name of the uniform group node.
  2942. * @returns {UniformGroupNode}
  2943. */
  2944. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2945. /**
  2946. * TSL function for creating a shared uniform group node with the given name and order.
  2947. *
  2948. * @tsl
  2949. * @function
  2950. * @param {string} name - The name of the uniform group node.
  2951. * @param {number} [order=0] - Influences the internal sorting.
  2952. * @returns {UniformGroupNode}
  2953. */
  2954. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2955. /**
  2956. * TSL object that represents a shared uniform group node which is updated once per frame.
  2957. *
  2958. * @tsl
  2959. * @type {UniformGroupNode}
  2960. */
  2961. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2962. /**
  2963. * TSL object that represents a shared uniform group node which is updated once per render.
  2964. *
  2965. * @tsl
  2966. * @type {UniformGroupNode}
  2967. */
  2968. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2969. /**
  2970. * TSL object that represents a uniform group node which is updated once per object.
  2971. *
  2972. * @tsl
  2973. * @type {UniformGroupNode}
  2974. */
  2975. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2976. /**
  2977. * Class for representing a uniform.
  2978. *
  2979. * @augments InputNode
  2980. */
  2981. class UniformNode extends InputNode {
  2982. static get type() {
  2983. return 'UniformNode';
  2984. }
  2985. /**
  2986. * Constructs a new uniform node.
  2987. *
  2988. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2989. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2990. */
  2991. constructor( value, nodeType = null ) {
  2992. super( value, nodeType );
  2993. /**
  2994. * This flag can be used for type testing.
  2995. *
  2996. * @type {boolean}
  2997. * @readonly
  2998. * @default true
  2999. */
  3000. this.isUniformNode = true;
  3001. /**
  3002. * The name or label of the uniform.
  3003. *
  3004. * @type {string}
  3005. * @default ''
  3006. */
  3007. this.name = '';
  3008. /**
  3009. * The uniform group of this uniform. By default, uniforms are
  3010. * managed per object but they might belong to a shared group
  3011. * which is updated per frame or render call.
  3012. *
  3013. * @type {UniformGroupNode}
  3014. */
  3015. this.groupNode = objectGroup;
  3016. }
  3017. /**
  3018. * Sets the {@link UniformNode#name} property.
  3019. *
  3020. * @param {string} name - The name of the uniform.
  3021. * @return {UniformNode} A reference to this node.
  3022. */
  3023. label( name ) {
  3024. this.name = name;
  3025. return this;
  3026. }
  3027. /**
  3028. * Sets the {@link UniformNode#groupNode} property.
  3029. *
  3030. * @param {UniformGroupNode} group - The uniform group.
  3031. * @return {UniformNode} A reference to this node.
  3032. */
  3033. setGroup( group ) {
  3034. this.groupNode = group;
  3035. return this;
  3036. }
  3037. /**
  3038. * Returns the {@link UniformNode#groupNode}.
  3039. *
  3040. * @return {UniformGroupNode} The uniform group.
  3041. */
  3042. getGroup() {
  3043. return this.groupNode;
  3044. }
  3045. /**
  3046. * By default, this method returns the result of {@link Node#getHash} but derived
  3047. * classes might overwrite this method with a different implementation.
  3048. *
  3049. * @param {NodeBuilder} builder - The current node builder.
  3050. * @return {string} The uniform hash.
  3051. */
  3052. getUniformHash( builder ) {
  3053. return this.getHash( builder );
  3054. }
  3055. onUpdate( callback, updateType ) {
  3056. const self = this.getSelf();
  3057. callback = callback.bind( self );
  3058. return super.onUpdate( ( frame ) => {
  3059. const value = callback( frame, self );
  3060. if ( value !== undefined ) {
  3061. this.value = value;
  3062. }
  3063. }, updateType );
  3064. }
  3065. generate( builder, output ) {
  3066. const type = this.getNodeType( builder );
  3067. const hash = this.getUniformHash( builder );
  3068. let sharedNode = builder.getNodeFromHash( hash );
  3069. if ( sharedNode === undefined ) {
  3070. builder.setHashNode( this, hash );
  3071. sharedNode = this;
  3072. }
  3073. const sharedNodeType = sharedNode.getInputType( builder );
  3074. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  3075. const propertyName = builder.getPropertyName( nodeUniform );
  3076. if ( builder.context.label !== undefined ) delete builder.context.label;
  3077. return builder.format( propertyName, type, output );
  3078. }
  3079. }
  3080. /**
  3081. * TSL function for creating a uniform node.
  3082. *
  3083. * @tsl
  3084. * @function
  3085. * @param {any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3086. * @param {string} [arg2] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3087. * @returns {UniformNode}
  3088. */
  3089. const uniform = ( arg1, arg2 ) => {
  3090. const nodeType = getConstNodeType( arg2 || arg1 );
  3091. // @TODO: get ConstNode from .traverse() in the future
  3092. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  3093. return nodeObject( new UniformNode( value, nodeType ) );
  3094. };
  3095. /**
  3096. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3097. * ```js
  3098. * const colors = array( [
  3099. * vec3( 1, 0, 0 ),
  3100. * vec3( 0, 1, 0 ),
  3101. * vec3( 0, 0, 1 )
  3102. * ] );
  3103. *
  3104. * const redColor = tintColors.element( 0 );
  3105. *
  3106. * @augments TempNode
  3107. */
  3108. class ArrayNode extends TempNode {
  3109. static get type() {
  3110. return 'ArrayNode';
  3111. }
  3112. /**
  3113. * Constructs a new array node.
  3114. *
  3115. * @param {?string} nodeType - The data type of the elements.
  3116. * @param {number} count - Size of the array.
  3117. * @param {?Array<Node>} [values=null] - Array default values.
  3118. */
  3119. constructor( nodeType, count, values = null ) {
  3120. super( nodeType );
  3121. /**
  3122. * Array size.
  3123. *
  3124. * @type {number}
  3125. */
  3126. this.count = count;
  3127. /**
  3128. * Array default values.
  3129. *
  3130. * @type {?Array<Node>}
  3131. */
  3132. this.values = values;
  3133. /**
  3134. * This flag can be used for type testing.
  3135. *
  3136. * @type {boolean}
  3137. * @readonly
  3138. * @default true
  3139. */
  3140. this.isArrayNode = true;
  3141. }
  3142. /**
  3143. * Returns the node's type.
  3144. *
  3145. * @param {NodeBuilder} builder - The current node builder.
  3146. * @return {string} The type of the node.
  3147. */
  3148. getNodeType( builder ) {
  3149. if ( this.nodeType === null ) {
  3150. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3151. }
  3152. return this.nodeType;
  3153. }
  3154. /**
  3155. * Returns the node's type.
  3156. *
  3157. * @param {NodeBuilder} builder - The current node builder.
  3158. * @return {string} The type of the node.
  3159. */
  3160. getElementType( builder ) {
  3161. return this.getNodeType( builder );
  3162. }
  3163. /**
  3164. * This method builds the output node and returns the resulting array as a shader string.
  3165. *
  3166. * @param {NodeBuilder} builder - The current node builder.
  3167. * @return {string} The generated shader string.
  3168. */
  3169. generate( builder ) {
  3170. const type = this.getNodeType( builder );
  3171. return builder.generateArray( type, this.count, this.values );
  3172. }
  3173. }
  3174. /**
  3175. * TSL function for creating an array node.
  3176. *
  3177. * @tsl
  3178. * @function
  3179. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3180. * or an array containing the default values (e.g., [ vec3() ]).
  3181. * @param {?number} [count] - Size of the array.
  3182. * @returns {ArrayNode}
  3183. */
  3184. const array = ( ...params ) => {
  3185. let node;
  3186. if ( params.length === 1 ) {
  3187. const values = params[ 0 ];
  3188. node = new ArrayNode( null, values.length, values );
  3189. } else {
  3190. const nodeType = params[ 0 ];
  3191. const count = params[ 1 ];
  3192. node = new ArrayNode( nodeType, count );
  3193. }
  3194. return nodeObject( node );
  3195. };
  3196. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3197. /**
  3198. * These node represents an assign operation. Meaning a node is assigned
  3199. * to another node.
  3200. *
  3201. * @augments TempNode
  3202. */
  3203. class AssignNode extends TempNode {
  3204. static get type() {
  3205. return 'AssignNode';
  3206. }
  3207. /**
  3208. * Constructs a new assign node.
  3209. *
  3210. * @param {Node} targetNode - The target node.
  3211. * @param {Node} sourceNode - The source type.
  3212. */
  3213. constructor( targetNode, sourceNode ) {
  3214. super();
  3215. /**
  3216. * The target node.
  3217. *
  3218. * @type {Node}
  3219. */
  3220. this.targetNode = targetNode;
  3221. /**
  3222. * The source node.
  3223. *
  3224. * @type {Node}
  3225. */
  3226. this.sourceNode = sourceNode;
  3227. /**
  3228. * This flag can be used for type testing.
  3229. *
  3230. * @type {boolean}
  3231. * @readonly
  3232. * @default true
  3233. */
  3234. this.isAssignNode = true;
  3235. }
  3236. /**
  3237. * Whether this node is used more than once in context of other nodes. This method
  3238. * is overwritten since it always returns `false` (assigns are unique).
  3239. *
  3240. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3241. */
  3242. hasDependencies() {
  3243. return false;
  3244. }
  3245. getNodeType( builder, output ) {
  3246. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3247. }
  3248. /**
  3249. * Whether a split is required when assigning source to target. This can happen when the component length of
  3250. * target and source data type does not match.
  3251. *
  3252. * @param {NodeBuilder} builder - The current node builder.
  3253. * @return {boolean} Whether a split is required when assigning source to target.
  3254. */
  3255. needsSplitAssign( builder ) {
  3256. const { targetNode } = this;
  3257. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3258. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3259. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3260. return assignDifferentVector;
  3261. }
  3262. return false;
  3263. }
  3264. setup( builder ) {
  3265. const { targetNode, sourceNode } = this;
  3266. const properties = builder.getNodeProperties( this );
  3267. properties.sourceNode = sourceNode;
  3268. properties.targetNode = targetNode.context( { assign: true } );
  3269. }
  3270. generate( builder, output ) {
  3271. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3272. const needsSplitAssign = this.needsSplitAssign( builder );
  3273. const targetType = targetNode.getNodeType( builder );
  3274. const target = targetNode.build( builder );
  3275. const source = sourceNode.build( builder, targetType );
  3276. const sourceType = sourceNode.getNodeType( builder );
  3277. const nodeData = builder.getDataFromNode( this );
  3278. //
  3279. let snippet;
  3280. if ( nodeData.initialized === true ) {
  3281. if ( output !== 'void' ) {
  3282. snippet = target;
  3283. }
  3284. } else if ( needsSplitAssign ) {
  3285. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3286. const sourceProperty = builder.getPropertyName( sourceVar );
  3287. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3288. const splitNode = targetNode.node;
  3289. const splitTargetNode = splitNode.node.context( { assign: true } );
  3290. const targetRoot = splitTargetNode.build( builder );
  3291. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3292. const component = splitNode.components[ i ];
  3293. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3294. }
  3295. if ( output !== 'void' ) {
  3296. snippet = target;
  3297. }
  3298. } else {
  3299. snippet = `${ target } = ${ source }`;
  3300. if ( output === 'void' || sourceType === 'void' ) {
  3301. builder.addLineFlowCode( snippet, this );
  3302. if ( output !== 'void' ) {
  3303. snippet = target;
  3304. }
  3305. }
  3306. }
  3307. nodeData.initialized = true;
  3308. return builder.format( snippet, targetType, output );
  3309. }
  3310. }
  3311. /**
  3312. * TSL function for creating an assign node.
  3313. *
  3314. * @tsl
  3315. * @function
  3316. * @param {Node} targetNode - The target node.
  3317. * @param {Node} sourceNode - The source type.
  3318. * @returns {AssignNode}
  3319. */
  3320. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3321. addMethodChaining( 'assign', assign );
  3322. /**
  3323. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3324. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3325. * this logic.
  3326. *
  3327. * @augments TempNode
  3328. */
  3329. class FunctionCallNode extends TempNode {
  3330. static get type() {
  3331. return 'FunctionCallNode';
  3332. }
  3333. /**
  3334. * Constructs a new function call node.
  3335. *
  3336. * @param {?FunctionNode} functionNode - The function node.
  3337. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3338. */
  3339. constructor( functionNode = null, parameters = {} ) {
  3340. super();
  3341. /**
  3342. * The function node.
  3343. *
  3344. * @type {?FunctionNode}
  3345. * @default null
  3346. */
  3347. this.functionNode = functionNode;
  3348. /**
  3349. * The parameters of the function call.
  3350. *
  3351. * @type {Object<string, Node>}
  3352. * @default {}
  3353. */
  3354. this.parameters = parameters;
  3355. }
  3356. /**
  3357. * Sets the parameters of the function call node.
  3358. *
  3359. * @param {Object<string, Node>} parameters - The parameters to set.
  3360. * @return {FunctionCallNode} A reference to this node.
  3361. */
  3362. setParameters( parameters ) {
  3363. this.parameters = parameters;
  3364. return this;
  3365. }
  3366. /**
  3367. * Returns the parameters of the function call node.
  3368. *
  3369. * @return {Object<string, Node>} The parameters of this node.
  3370. */
  3371. getParameters() {
  3372. return this.parameters;
  3373. }
  3374. getNodeType( builder ) {
  3375. return this.functionNode.getNodeType( builder );
  3376. }
  3377. generate( builder ) {
  3378. const params = [];
  3379. const functionNode = this.functionNode;
  3380. const inputs = functionNode.getInputs( builder );
  3381. const parameters = this.parameters;
  3382. const generateInput = ( node, inputNode ) => {
  3383. const type = inputNode.type;
  3384. const pointer = type === 'pointer';
  3385. let output;
  3386. if ( pointer ) output = '&' + node.build( builder );
  3387. else output = node.build( builder, type );
  3388. return output;
  3389. };
  3390. if ( Array.isArray( parameters ) ) {
  3391. if ( parameters.length > inputs.length ) {
  3392. console.error( 'THREE.TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3393. parameters.length = inputs.length;
  3394. } else if ( parameters.length < inputs.length ) {
  3395. console.error( 'THREE.TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3396. while ( parameters.length < inputs.length ) {
  3397. parameters.push( float( 0 ) );
  3398. }
  3399. }
  3400. for ( let i = 0; i < parameters.length; i ++ ) {
  3401. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3402. }
  3403. } else {
  3404. for ( const inputNode of inputs ) {
  3405. const node = parameters[ inputNode.name ];
  3406. if ( node !== undefined ) {
  3407. params.push( generateInput( node, inputNode ) );
  3408. } else {
  3409. console.error( `THREE.TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3410. params.push( generateInput( float( 0 ), inputNode ) );
  3411. }
  3412. }
  3413. }
  3414. const functionName = functionNode.build( builder, 'property' );
  3415. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3416. }
  3417. }
  3418. const call = ( func, ...params ) => {
  3419. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3420. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3421. };
  3422. addMethodChaining( 'call', call );
  3423. const _vectorOperators = {
  3424. '==': 'equal',
  3425. '!=': 'notEqual',
  3426. '<': 'lessThan',
  3427. '>': 'greaterThan',
  3428. '<=': 'lessThanEqual',
  3429. '>=': 'greaterThanEqual',
  3430. '%': 'mod'
  3431. };
  3432. /**
  3433. * This node represents basic mathematical and logical operations like addition,
  3434. * subtraction or comparisons (e.g. `equal()`).
  3435. *
  3436. * @augments TempNode
  3437. */
  3438. class OperatorNode extends TempNode {
  3439. static get type() {
  3440. return 'OperatorNode';
  3441. }
  3442. /**
  3443. * Constructs a new operator node.
  3444. *
  3445. * @param {string} op - The operator.
  3446. * @param {Node} aNode - The first input.
  3447. * @param {Node} bNode - The second input.
  3448. * @param {...Node} params - Additional input parameters.
  3449. */
  3450. constructor( op, aNode, bNode, ...params ) {
  3451. super();
  3452. if ( params.length > 0 ) {
  3453. let finalOp = new OperatorNode( op, aNode, bNode );
  3454. for ( let i = 0; i < params.length - 1; i ++ ) {
  3455. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3456. }
  3457. aNode = finalOp;
  3458. bNode = params[ params.length - 1 ];
  3459. }
  3460. /**
  3461. * The operator.
  3462. *
  3463. * @type {string}
  3464. */
  3465. this.op = op;
  3466. /**
  3467. * The first input.
  3468. *
  3469. * @type {Node}
  3470. */
  3471. this.aNode = aNode;
  3472. /**
  3473. * The second input.
  3474. *
  3475. * @type {Node}
  3476. */
  3477. this.bNode = bNode;
  3478. /**
  3479. * This flag can be used for type testing.
  3480. *
  3481. * @type {boolean}
  3482. * @readonly
  3483. * @default true
  3484. */
  3485. this.isOperatorNode = true;
  3486. }
  3487. /**
  3488. * Returns the operator method name.
  3489. *
  3490. * @param {NodeBuilder} builder - The current node builder.
  3491. * @param {string} output - The output type.
  3492. * @returns {string} The operator method name.
  3493. */
  3494. getOperatorMethod( builder, output ) {
  3495. return builder.getMethod( _vectorOperators[ this.op ], output );
  3496. }
  3497. /**
  3498. * This method is overwritten since the node type is inferred from the operator
  3499. * and the input node types.
  3500. *
  3501. * @param {NodeBuilder} builder - The current node builder.
  3502. * @return {string} The node type.
  3503. */
  3504. getNodeType( builder ) {
  3505. const op = this.op;
  3506. const aNode = this.aNode;
  3507. const bNode = this.bNode;
  3508. const typeA = aNode.getNodeType( builder );
  3509. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3510. if ( typeA === 'void' || typeB === 'void' ) {
  3511. return 'void';
  3512. } else if ( op === '%' ) {
  3513. return typeA;
  3514. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3515. return builder.getIntegerType( typeA );
  3516. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3517. return 'bool';
  3518. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3519. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3520. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3521. } else {
  3522. // Handle matrix operations
  3523. if ( builder.isMatrix( typeA ) ) {
  3524. if ( typeB === 'float' ) {
  3525. return typeA; // matrix * scalar = matrix
  3526. } else if ( builder.isVector( typeB ) ) {
  3527. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3528. } else if ( builder.isMatrix( typeB ) ) {
  3529. return typeA; // matrix * matrix
  3530. }
  3531. } else if ( builder.isMatrix( typeB ) ) {
  3532. if ( typeA === 'float' ) {
  3533. return typeB; // scalar * matrix = matrix
  3534. } else if ( builder.isVector( typeA ) ) {
  3535. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3536. }
  3537. }
  3538. // Handle non-matrix cases
  3539. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3540. // anytype x anytype: use the greater length vector
  3541. return typeB;
  3542. }
  3543. return typeA;
  3544. }
  3545. }
  3546. generate( builder, output ) {
  3547. const op = this.op;
  3548. const { aNode, bNode } = this;
  3549. const type = this.getNodeType( builder );
  3550. let typeA = null;
  3551. let typeB = null;
  3552. if ( type !== 'void' ) {
  3553. typeA = aNode.getNodeType( builder );
  3554. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3555. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3556. if ( builder.isVector( typeA ) ) {
  3557. typeB = typeA;
  3558. } else if ( builder.isVector( typeB ) ) {
  3559. typeA = typeB;
  3560. } else if ( typeA !== typeB ) {
  3561. typeA = typeB = 'float';
  3562. }
  3563. } else if ( op === '>>' || op === '<<' ) {
  3564. typeA = type;
  3565. typeB = builder.changeComponentType( typeB, 'uint' );
  3566. } else if ( op === '%' ) {
  3567. typeA = type;
  3568. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3569. } else if ( builder.isMatrix( typeA ) ) {
  3570. if ( typeB === 'float' ) {
  3571. // Keep matrix type for typeA, but ensure typeB stays float
  3572. typeB = 'float';
  3573. } else if ( builder.isVector( typeB ) ) {
  3574. // matrix x vector
  3575. typeB = builder.getVectorFromMatrix( typeA );
  3576. } else if ( builder.isMatrix( typeB ) ) ; else {
  3577. typeA = typeB = type;
  3578. }
  3579. } else if ( builder.isMatrix( typeB ) ) {
  3580. if ( typeA === 'float' ) {
  3581. // Keep matrix type for typeB, but ensure typeA stays float
  3582. typeA = 'float';
  3583. } else if ( builder.isVector( typeA ) ) {
  3584. // vector x matrix
  3585. typeA = builder.getVectorFromMatrix( typeB );
  3586. } else {
  3587. typeA = typeB = type;
  3588. }
  3589. } else {
  3590. // anytype x anytype
  3591. typeA = typeB = type;
  3592. }
  3593. } else {
  3594. typeA = typeB = type;
  3595. }
  3596. const a = aNode.build( builder, typeA );
  3597. const b = bNode ? bNode.build( builder, typeB ) : null;
  3598. const fnOpSnippet = builder.getFunctionOperator( op );
  3599. if ( output !== 'void' ) {
  3600. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3601. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3602. if ( isGLSL ) {
  3603. if ( builder.isVector( typeA ) ) {
  3604. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3605. } else {
  3606. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3607. }
  3608. } else {
  3609. // WGSL
  3610. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3611. }
  3612. } else if ( op === '%' ) {
  3613. if ( builder.isInteger( typeB ) ) {
  3614. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3615. } else {
  3616. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3617. }
  3618. } else if ( op === '!' || op === '~' ) {
  3619. return builder.format( `(${op}${a})`, typeA, output );
  3620. } else if ( fnOpSnippet ) {
  3621. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3622. } else {
  3623. // Handle matrix operations
  3624. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3625. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3626. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3627. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3628. } else {
  3629. let snippet = `( ${ a } ${ op } ${ b } )`;
  3630. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  3631. snippet = `all${ snippet }`;
  3632. }
  3633. return builder.format( snippet, type, output );
  3634. }
  3635. }
  3636. } else if ( typeA !== 'void' ) {
  3637. if ( fnOpSnippet ) {
  3638. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3639. } else {
  3640. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3641. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3642. } else {
  3643. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3644. }
  3645. }
  3646. }
  3647. }
  3648. serialize( data ) {
  3649. super.serialize( data );
  3650. data.op = this.op;
  3651. }
  3652. deserialize( data ) {
  3653. super.deserialize( data );
  3654. this.op = data.op;
  3655. }
  3656. }
  3657. /**
  3658. * Returns the addition of two or more value.
  3659. *
  3660. * @tsl
  3661. * @function
  3662. * @param {Node} a - The first input.
  3663. * @param {Node} b - The second input.
  3664. * @param {...Node} params - Additional input parameters.
  3665. * @returns {OperatorNode}
  3666. */
  3667. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  3668. /**
  3669. * Returns the subtraction of two or more value.
  3670. *
  3671. * @tsl
  3672. * @function
  3673. * @param {Node} a - The first input.
  3674. * @param {Node} b - The second input.
  3675. * @param {...Node} params - Additional input parameters.
  3676. * @returns {OperatorNode}
  3677. */
  3678. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  3679. /**
  3680. * Returns the multiplication of two or more value.
  3681. *
  3682. * @tsl
  3683. * @function
  3684. * @param {Node} a - The first input.
  3685. * @param {Node} b - The second input.
  3686. * @param {...Node} params - Additional input parameters.
  3687. * @returns {OperatorNode}
  3688. */
  3689. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  3690. /**
  3691. * Returns the division of two or more value.
  3692. *
  3693. * @tsl
  3694. * @function
  3695. * @param {Node} a - The first input.
  3696. * @param {Node} b - The second input.
  3697. * @param {...Node} params - Additional input parameters.
  3698. * @returns {OperatorNode}
  3699. */
  3700. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  3701. /**
  3702. * Computes the remainder of dividing the first node by the second one.
  3703. *
  3704. * @tsl
  3705. * @function
  3706. * @param {Node} a - The first input.
  3707. * @param {Node} b - The second input.
  3708. * @returns {OperatorNode}
  3709. */
  3710. const mod = /*@__PURE__*/ nodeProxy( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  3711. /**
  3712. * Checks if two nodes are equal.
  3713. *
  3714. * @tsl
  3715. * @function
  3716. * @param {Node} a - The first input.
  3717. * @param {Node} b - The second input.
  3718. * @returns {OperatorNode}
  3719. */
  3720. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  3721. /**
  3722. * Checks if two nodes are not equal.
  3723. *
  3724. * @tsl
  3725. * @function
  3726. * @param {Node} a - The first input.
  3727. * @param {Node} b - The second input.
  3728. * @returns {OperatorNode}
  3729. */
  3730. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  3731. /**
  3732. * Checks if the first node is less than the second.
  3733. *
  3734. * @tsl
  3735. * @function
  3736. * @param {Node} a - The first input.
  3737. * @param {Node} b - The second input.
  3738. * @returns {OperatorNode}
  3739. */
  3740. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  3741. /**
  3742. * Checks if the first node is greater than the second.
  3743. *
  3744. * @tsl
  3745. * @function
  3746. * @param {Node} a - The first input.
  3747. * @param {Node} b - The second input.
  3748. * @returns {OperatorNode}
  3749. */
  3750. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  3751. /**
  3752. * Checks if the first node is less than or equal to the second.
  3753. *
  3754. * @tsl
  3755. * @function
  3756. * @param {Node} a - The first input.
  3757. * @param {Node} b - The second input.
  3758. * @returns {OperatorNode}
  3759. */
  3760. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  3761. /**
  3762. * Checks if the first node is greater than or equal to the second.
  3763. *
  3764. * @tsl
  3765. * @function
  3766. * @param {Node} a - The first input.
  3767. * @param {Node} b - The second input.
  3768. * @returns {OperatorNode}
  3769. */
  3770. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  3771. /**
  3772. * Performs a logical AND operation on multiple nodes.
  3773. *
  3774. * @tsl
  3775. * @function
  3776. * @param {...Node} nodes - The input nodes to be combined using AND.
  3777. * @returns {OperatorNode}
  3778. */
  3779. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  3780. /**
  3781. * Performs a logical OR operation on multiple nodes.
  3782. *
  3783. * @tsl
  3784. * @function
  3785. * @param {...Node} nodes - The input nodes to be combined using OR.
  3786. * @returns {OperatorNode}
  3787. */
  3788. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  3789. /**
  3790. * Performs logical NOT on a node.
  3791. *
  3792. * @tsl
  3793. * @function
  3794. * @param {Node} value - The value.
  3795. * @returns {OperatorNode}
  3796. */
  3797. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  3798. /**
  3799. * Performs logical XOR on two nodes.
  3800. *
  3801. * @tsl
  3802. * @function
  3803. * @param {Node} a - The first input.
  3804. * @param {Node} b - The second input.
  3805. * @returns {OperatorNode}
  3806. */
  3807. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  3808. /**
  3809. * Performs bitwise AND on two nodes.
  3810. *
  3811. * @tsl
  3812. * @function
  3813. * @param {Node} a - The first input.
  3814. * @param {Node} b - The second input.
  3815. * @returns {OperatorNode}
  3816. */
  3817. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  3818. /**
  3819. * Performs bitwise NOT on a node.
  3820. *
  3821. * @tsl
  3822. * @function
  3823. * @param {Node} a - The first input.
  3824. * @param {Node} b - The second input.
  3825. * @returns {OperatorNode}
  3826. */
  3827. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' ).setParameterLength( 2 ).setName( 'bitNot' );
  3828. /**
  3829. * Performs bitwise OR on two nodes.
  3830. *
  3831. * @tsl
  3832. * @function
  3833. * @param {Node} a - The first input.
  3834. * @param {Node} b - The second input.
  3835. * @returns {OperatorNode}
  3836. */
  3837. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  3838. /**
  3839. * Performs bitwise XOR on two nodes.
  3840. *
  3841. * @tsl
  3842. * @function
  3843. * @param {Node} a - The first input.
  3844. * @param {Node} b - The second input.
  3845. * @returns {OperatorNode}
  3846. */
  3847. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  3848. /**
  3849. * Shifts a node to the left.
  3850. *
  3851. * @tsl
  3852. * @function
  3853. * @param {Node} a - The node to shift.
  3854. * @param {Node} b - The value to shift.
  3855. * @returns {OperatorNode}
  3856. */
  3857. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  3858. /**
  3859. * Shifts a node to the right.
  3860. *
  3861. * @tsl
  3862. * @function
  3863. * @param {Node} a - The node to shift.
  3864. * @param {Node} b - The value to shift.
  3865. * @returns {OperatorNode}
  3866. */
  3867. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  3868. /**
  3869. * Increments a node by 1.
  3870. *
  3871. * @tsl
  3872. * @function
  3873. * @param {Node} a - The node to increment.
  3874. * @returns {OperatorNode}
  3875. */
  3876. const incrementBefore = Fn( ( [ a ] ) => {
  3877. a.addAssign( 1 );
  3878. return a;
  3879. } );
  3880. /**
  3881. * Decrements a node by 1.
  3882. *
  3883. * @tsl
  3884. * @function
  3885. * @param {Node} a - The node to decrement.
  3886. * @returns {OperatorNode}
  3887. */
  3888. const decrementBefore = Fn( ( [ a ] ) => {
  3889. a.subAssign( 1 );
  3890. return a;
  3891. } );
  3892. /**
  3893. * Increments a node by 1 and returns the previous value.
  3894. *
  3895. * @tsl
  3896. * @function
  3897. * @param {Node} a - The node to increment.
  3898. * @returns {OperatorNode}
  3899. */
  3900. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  3901. const temp = int( a ).toConst();
  3902. a.addAssign( 1 );
  3903. return temp;
  3904. } );
  3905. /**
  3906. * Decrements a node by 1 and returns the previous value.
  3907. *
  3908. * @tsl
  3909. * @function
  3910. * @param {Node} a - The node to decrement.
  3911. * @returns {OperatorNode}
  3912. */
  3913. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  3914. const temp = int( a ).toConst();
  3915. a.subAssign( 1 );
  3916. return temp;
  3917. } );
  3918. addMethodChaining( 'add', add );
  3919. addMethodChaining( 'sub', sub );
  3920. addMethodChaining( 'mul', mul );
  3921. addMethodChaining( 'div', div );
  3922. addMethodChaining( 'mod', mod );
  3923. addMethodChaining( 'equal', equal );
  3924. addMethodChaining( 'notEqual', notEqual );
  3925. addMethodChaining( 'lessThan', lessThan );
  3926. addMethodChaining( 'greaterThan', greaterThan );
  3927. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3928. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3929. addMethodChaining( 'and', and );
  3930. addMethodChaining( 'or', or );
  3931. addMethodChaining( 'not', not );
  3932. addMethodChaining( 'xor', xor );
  3933. addMethodChaining( 'bitAnd', bitAnd );
  3934. addMethodChaining( 'bitNot', bitNot );
  3935. addMethodChaining( 'bitOr', bitOr );
  3936. addMethodChaining( 'bitXor', bitXor );
  3937. addMethodChaining( 'shiftLeft', shiftLeft );
  3938. addMethodChaining( 'shiftRight', shiftRight );
  3939. addMethodChaining( 'incrementBefore', incrementBefore );
  3940. addMethodChaining( 'decrementBefore', decrementBefore );
  3941. addMethodChaining( 'increment', increment );
  3942. addMethodChaining( 'decrement', decrement );
  3943. /**
  3944. * @tsl
  3945. * @function
  3946. * @deprecated since r168. Use {@link mod} instead.
  3947. *
  3948. * @param {Node} a - The first input.
  3949. * @param {Node} b - The second input.
  3950. * @returns {OperatorNode}
  3951. */
  3952. const remainder = ( a, b ) => { // @deprecated, r168
  3953. console.warn( 'THREE.TSL: "remainder()" is deprecated. Use "mod( int( ... ) )" instead.' );
  3954. return mod( a, b );
  3955. };
  3956. /**
  3957. * @tsl
  3958. * @function
  3959. * @deprecated since r175. Use {@link mod} instead.
  3960. *
  3961. * @param {Node} a - The first input.
  3962. * @param {Node} b - The second input.
  3963. * @returns {OperatorNode}
  3964. */
  3965. const modInt = ( a, b ) => { // @deprecated, r175
  3966. console.warn( 'THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  3967. return mod( int( a ), int( b ) );
  3968. };
  3969. addMethodChaining( 'remainder', remainder );
  3970. addMethodChaining( 'modInt', modInt );
  3971. /**
  3972. * This node represents a variety of mathematical methods available in shaders.
  3973. * They are divided into three categories:
  3974. *
  3975. * - Methods with one input like `sin`, `cos` or `normalize`.
  3976. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3977. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3978. *
  3979. * @augments TempNode
  3980. */
  3981. class MathNode extends TempNode {
  3982. static get type() {
  3983. return 'MathNode';
  3984. }
  3985. /**
  3986. * Constructs a new math node.
  3987. *
  3988. * @param {string} method - The method name.
  3989. * @param {Node} aNode - The first input.
  3990. * @param {?Node} [bNode=null] - The second input.
  3991. * @param {?Node} [cNode=null] - The third input.
  3992. */
  3993. constructor( method, aNode, bNode = null, cNode = null ) {
  3994. super();
  3995. // Allow the max() and min() functions to take an arbitrary number of arguments.
  3996. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  3997. let finalOp = new MathNode( method, aNode, bNode );
  3998. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  3999. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4000. }
  4001. aNode = finalOp;
  4002. bNode = arguments[ arguments.length - 1 ];
  4003. cNode = null;
  4004. }
  4005. /**
  4006. * The method name.
  4007. *
  4008. * @type {string}
  4009. */
  4010. this.method = method;
  4011. /**
  4012. * The first input.
  4013. *
  4014. * @type {Node}
  4015. */
  4016. this.aNode = aNode;
  4017. /**
  4018. * The second input.
  4019. *
  4020. * @type {?Node}
  4021. * @default null
  4022. */
  4023. this.bNode = bNode;
  4024. /**
  4025. * The third input.
  4026. *
  4027. * @type {?Node}
  4028. * @default null
  4029. */
  4030. this.cNode = cNode;
  4031. /**
  4032. * This flag can be used for type testing.
  4033. *
  4034. * @type {boolean}
  4035. * @readonly
  4036. * @default true
  4037. */
  4038. this.isMathNode = true;
  4039. }
  4040. /**
  4041. * The input type is inferred from the node types of the input nodes.
  4042. *
  4043. * @param {NodeBuilder} builder - The current node builder.
  4044. * @return {string} The input type.
  4045. */
  4046. getInputType( builder ) {
  4047. const aType = this.aNode.getNodeType( builder );
  4048. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4049. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4050. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4051. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4052. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4053. if ( aLen > bLen && aLen > cLen ) {
  4054. return aType;
  4055. } else if ( bLen > cLen ) {
  4056. return bType;
  4057. } else if ( cLen > aLen ) {
  4058. return cType;
  4059. }
  4060. return aType;
  4061. }
  4062. /**
  4063. * The selected method as well as the input type determine the node type of this node.
  4064. *
  4065. * @param {NodeBuilder} builder - The current node builder.
  4066. * @return {string} The node type.
  4067. */
  4068. getNodeType( builder ) {
  4069. const method = this.method;
  4070. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4071. return 'float';
  4072. } else if ( method === MathNode.CROSS ) {
  4073. return 'vec3';
  4074. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4075. return 'bool';
  4076. } else if ( method === MathNode.EQUALS ) {
  4077. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4078. } else {
  4079. return this.getInputType( builder );
  4080. }
  4081. }
  4082. setup( builder ) {
  4083. const { aNode, bNode, method } = this;
  4084. let outputNode = null;
  4085. if ( method === MathNode.ONE_MINUS ) {
  4086. outputNode = sub( 1.0, aNode );
  4087. } else if ( method === MathNode.RECIPROCAL ) {
  4088. outputNode = div( 1.0, aNode );
  4089. } else if ( method === MathNode.DIFFERENCE ) {
  4090. outputNode = abs( sub( aNode, bNode ) );
  4091. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4092. // dir can be either a direction vector or a normal vector
  4093. // upper-left 3x3 of matrix is assumed to be orthogonal
  4094. let tA = aNode;
  4095. let tB = bNode;
  4096. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4097. tB = vec4( vec3( tB ), 0.0 );
  4098. } else {
  4099. tA = vec4( vec3( tA ), 0.0 );
  4100. }
  4101. const mulNode = mul( tA, tB ).xyz;
  4102. outputNode = normalize( mulNode );
  4103. }
  4104. if ( outputNode !== null ) {
  4105. return outputNode;
  4106. } else {
  4107. return super.setup( builder );
  4108. }
  4109. }
  4110. generate( builder, output ) {
  4111. const properties = builder.getNodeProperties( this );
  4112. if ( properties.outputNode ) {
  4113. return super.generate( builder, output );
  4114. }
  4115. let method = this.method;
  4116. const type = this.getNodeType( builder );
  4117. const inputType = this.getInputType( builder );
  4118. const a = this.aNode;
  4119. const b = this.bNode;
  4120. const c = this.cNode;
  4121. const coordinateSystem = builder.renderer.coordinateSystem;
  4122. if ( method === MathNode.NEGATE ) {
  4123. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4124. } else {
  4125. const params = [];
  4126. if ( method === MathNode.CROSS ) {
  4127. params.push(
  4128. a.build( builder, type ),
  4129. b.build( builder, type )
  4130. );
  4131. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4132. params.push(
  4133. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4134. b.build( builder, inputType )
  4135. );
  4136. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4137. params.push(
  4138. a.build( builder, inputType ),
  4139. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4140. );
  4141. } else if ( method === MathNode.REFRACT ) {
  4142. params.push(
  4143. a.build( builder, inputType ),
  4144. b.build( builder, inputType ),
  4145. c.build( builder, 'float' )
  4146. );
  4147. } else if ( method === MathNode.MIX ) {
  4148. params.push(
  4149. a.build( builder, inputType ),
  4150. b.build( builder, inputType ),
  4151. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4152. );
  4153. } else {
  4154. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4155. method = 'atan2';
  4156. }
  4157. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4158. console.warn( `THREE.TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4159. method = '/*' + method + '*/';
  4160. }
  4161. params.push( a.build( builder, inputType ) );
  4162. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4163. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4164. }
  4165. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4166. }
  4167. }
  4168. serialize( data ) {
  4169. super.serialize( data );
  4170. data.method = this.method;
  4171. }
  4172. deserialize( data ) {
  4173. super.deserialize( data );
  4174. this.method = data.method;
  4175. }
  4176. }
  4177. // 1 input
  4178. MathNode.ALL = 'all';
  4179. MathNode.ANY = 'any';
  4180. MathNode.RADIANS = 'radians';
  4181. MathNode.DEGREES = 'degrees';
  4182. MathNode.EXP = 'exp';
  4183. MathNode.EXP2 = 'exp2';
  4184. MathNode.LOG = 'log';
  4185. MathNode.LOG2 = 'log2';
  4186. MathNode.SQRT = 'sqrt';
  4187. MathNode.INVERSE_SQRT = 'inversesqrt';
  4188. MathNode.FLOOR = 'floor';
  4189. MathNode.CEIL = 'ceil';
  4190. MathNode.NORMALIZE = 'normalize';
  4191. MathNode.FRACT = 'fract';
  4192. MathNode.SIN = 'sin';
  4193. MathNode.COS = 'cos';
  4194. MathNode.TAN = 'tan';
  4195. MathNode.ASIN = 'asin';
  4196. MathNode.ACOS = 'acos';
  4197. MathNode.ATAN = 'atan';
  4198. MathNode.ABS = 'abs';
  4199. MathNode.SIGN = 'sign';
  4200. MathNode.LENGTH = 'length';
  4201. MathNode.NEGATE = 'negate';
  4202. MathNode.ONE_MINUS = 'oneMinus';
  4203. MathNode.DFDX = 'dFdx';
  4204. MathNode.DFDY = 'dFdy';
  4205. MathNode.ROUND = 'round';
  4206. MathNode.RECIPROCAL = 'reciprocal';
  4207. MathNode.TRUNC = 'trunc';
  4208. MathNode.FWIDTH = 'fwidth';
  4209. MathNode.TRANSPOSE = 'transpose';
  4210. // 2 inputs
  4211. MathNode.BITCAST = 'bitcast';
  4212. MathNode.EQUALS = 'equals';
  4213. MathNode.MIN = 'min';
  4214. MathNode.MAX = 'max';
  4215. MathNode.STEP = 'step';
  4216. MathNode.REFLECT = 'reflect';
  4217. MathNode.DISTANCE = 'distance';
  4218. MathNode.DIFFERENCE = 'difference';
  4219. MathNode.DOT = 'dot';
  4220. MathNode.CROSS = 'cross';
  4221. MathNode.POW = 'pow';
  4222. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4223. // 3 inputs
  4224. MathNode.MIX = 'mix';
  4225. MathNode.CLAMP = 'clamp';
  4226. MathNode.REFRACT = 'refract';
  4227. MathNode.SMOOTHSTEP = 'smoothstep';
  4228. MathNode.FACEFORWARD = 'faceforward';
  4229. // 1 inputs
  4230. /**
  4231. * A small value used to handle floating-point precision errors.
  4232. *
  4233. * @tsl
  4234. * @type {Node<float>}
  4235. */
  4236. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4237. /**
  4238. * Represents infinity.
  4239. *
  4240. * @tsl
  4241. * @type {Node<float>}
  4242. */
  4243. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4244. /**
  4245. * Represents PI.
  4246. *
  4247. * @tsl
  4248. * @type {Node<float>}
  4249. */
  4250. const PI = /*@__PURE__*/ float( Math.PI );
  4251. /**
  4252. * Represents PI * 2.
  4253. *
  4254. * @tsl
  4255. * @type {Node<float>}
  4256. */
  4257. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  4258. /**
  4259. * Returns `true` if all components of `x` are `true`.
  4260. *
  4261. * @tsl
  4262. * @function
  4263. * @param {Node | number} x - The parameter.
  4264. * @returns {Node<bool>}
  4265. */
  4266. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4267. /**
  4268. * Returns `true` if any components of `x` are `true`.
  4269. *
  4270. * @tsl
  4271. * @function
  4272. * @param {Node | number} x - The parameter.
  4273. * @returns {Node<bool>}
  4274. */
  4275. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4276. /**
  4277. * Converts a quantity in degrees to radians.
  4278. *
  4279. * @tsl
  4280. * @function
  4281. * @param {Node | number} x - The input in degrees.
  4282. * @returns {Node}
  4283. */
  4284. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4285. /**
  4286. * Convert a quantity in radians to degrees.
  4287. *
  4288. * @tsl
  4289. * @function
  4290. * @param {Node | number} x - The input in radians.
  4291. * @returns {Node}
  4292. */
  4293. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4294. /**
  4295. * Returns the natural exponentiation of the parameter.
  4296. *
  4297. * @tsl
  4298. * @function
  4299. * @param {Node | number} x - The parameter.
  4300. * @returns {Node}
  4301. */
  4302. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4303. /**
  4304. * Returns 2 raised to the power of the parameter.
  4305. *
  4306. * @tsl
  4307. * @function
  4308. * @param {Node | number} x - The parameter.
  4309. * @returns {Node}
  4310. */
  4311. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4312. /**
  4313. * Returns the natural logarithm of the parameter.
  4314. *
  4315. * @tsl
  4316. * @function
  4317. * @param {Node | number} x - The parameter.
  4318. * @returns {Node}
  4319. */
  4320. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4321. /**
  4322. * Returns the base 2 logarithm of the parameter.
  4323. *
  4324. * @tsl
  4325. * @function
  4326. * @param {Node | number} x - The parameter.
  4327. * @returns {Node}
  4328. */
  4329. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4330. /**
  4331. * Returns the square root of the parameter.
  4332. *
  4333. * @tsl
  4334. * @function
  4335. * @param {Node | number} x - The parameter.
  4336. * @returns {Node}
  4337. */
  4338. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4339. /**
  4340. * Returns the inverse of the square root of the parameter.
  4341. *
  4342. * @tsl
  4343. * @function
  4344. * @param {Node | number} x - The parameter.
  4345. * @returns {Node}
  4346. */
  4347. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4348. /**
  4349. * Finds the nearest integer less than or equal to the parameter.
  4350. *
  4351. * @tsl
  4352. * @function
  4353. * @param {Node | number} x - The parameter.
  4354. * @returns {Node}
  4355. */
  4356. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4357. /**
  4358. * Finds the nearest integer that is greater than or equal to the parameter.
  4359. *
  4360. * @tsl
  4361. * @function
  4362. * @param {Node | number} x - The parameter.
  4363. * @returns {Node}
  4364. */
  4365. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4366. /**
  4367. * Calculates the unit vector in the same direction as the original vector.
  4368. *
  4369. * @tsl
  4370. * @function
  4371. * @param {Node} x - The input vector.
  4372. * @returns {Node}
  4373. */
  4374. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4375. /**
  4376. * Computes the fractional part of the parameter.
  4377. *
  4378. * @tsl
  4379. * @function
  4380. * @param {Node | number} x - The parameter.
  4381. * @returns {Node}
  4382. */
  4383. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4384. /**
  4385. * Returns the sine of the parameter.
  4386. *
  4387. * @tsl
  4388. * @function
  4389. * @param {Node | number} x - The parameter.
  4390. * @returns {Node}
  4391. */
  4392. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4393. /**
  4394. * Returns the cosine of the parameter.
  4395. *
  4396. * @tsl
  4397. * @function
  4398. * @param {Node | number} x - The parameter.
  4399. * @returns {Node}
  4400. */
  4401. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS ).setParameterLength( 1 );
  4402. /**
  4403. * Returns the tangent of the parameter.
  4404. *
  4405. * @tsl
  4406. * @function
  4407. * @param {Node | number} x - The parameter.
  4408. * @returns {Node}
  4409. */
  4410. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4411. /**
  4412. * Returns the arcsine of the parameter.
  4413. *
  4414. * @tsl
  4415. * @function
  4416. * @param {Node | number} x - The parameter.
  4417. * @returns {Node}
  4418. */
  4419. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4420. /**
  4421. * Returns the arccosine of the parameter.
  4422. *
  4423. * @tsl
  4424. * @function
  4425. * @param {Node | number} x - The parameter.
  4426. * @returns {Node}
  4427. */
  4428. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4429. /**
  4430. * Returns the arc-tangent of the parameter.
  4431. * If two parameters are provided, the result is `atan2(y/x)`.
  4432. *
  4433. * @tsl
  4434. * @function
  4435. * @param {Node | number} y - The y parameter.
  4436. * @param {?(Node | number)} x - The x parameter.
  4437. * @returns {Node}
  4438. */
  4439. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4440. /**
  4441. * Returns the absolute value of the parameter.
  4442. *
  4443. * @tsl
  4444. * @function
  4445. * @param {Node | number} x - The parameter.
  4446. * @returns {Node}
  4447. */
  4448. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4449. /**
  4450. * Extracts the sign of the parameter.
  4451. *
  4452. * @tsl
  4453. * @function
  4454. * @param {Node | number} x - The parameter.
  4455. * @returns {Node}
  4456. */
  4457. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4458. /**
  4459. * Calculates the length of a vector.
  4460. *
  4461. * @tsl
  4462. * @function
  4463. * @param {Node} x - The parameter.
  4464. * @returns {Node<float>}
  4465. */
  4466. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4467. /**
  4468. * Negates the value of the parameter (-x).
  4469. *
  4470. * @tsl
  4471. * @function
  4472. * @param {Node | number} x - The parameter.
  4473. * @returns {Node}
  4474. */
  4475. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4476. /**
  4477. * Return `1` minus the parameter.
  4478. *
  4479. * @tsl
  4480. * @function
  4481. * @param {Node | number} x - The parameter.
  4482. * @returns {Node}
  4483. */
  4484. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4485. /**
  4486. * Returns the partial derivative of the parameter with respect to x.
  4487. *
  4488. * @tsl
  4489. * @function
  4490. * @param {Node | number} x - The parameter.
  4491. * @returns {Node}
  4492. */
  4493. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4494. /**
  4495. * Returns the partial derivative of the parameter with respect to y.
  4496. *
  4497. * @tsl
  4498. * @function
  4499. * @param {Node | number} x - The parameter.
  4500. * @returns {Node}
  4501. */
  4502. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4503. /**
  4504. * Rounds the parameter to the nearest integer.
  4505. *
  4506. * @tsl
  4507. * @function
  4508. * @param {Node | number} x - The parameter.
  4509. * @returns {Node}
  4510. */
  4511. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4512. /**
  4513. * Returns the reciprocal of the parameter `(1/x)`.
  4514. *
  4515. * @tsl
  4516. * @function
  4517. * @param {Node | number} x - The parameter.
  4518. * @returns {Node}
  4519. */
  4520. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4521. /**
  4522. * Truncates the parameter, removing the fractional part.
  4523. *
  4524. * @tsl
  4525. * @function
  4526. * @param {Node | number} x - The parameter.
  4527. * @returns {Node}
  4528. */
  4529. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4530. /**
  4531. * Returns the sum of the absolute derivatives in x and y.
  4532. *
  4533. * @tsl
  4534. * @function
  4535. * @param {Node | number} x - The parameter.
  4536. * @returns {Node}
  4537. */
  4538. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4539. /**
  4540. * Returns the transpose of a matrix.
  4541. *
  4542. * @tsl
  4543. * @function
  4544. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4545. * @returns {Node}
  4546. */
  4547. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4548. // 2 inputs
  4549. /**
  4550. * Reinterpret the bit representation of a value in one type as a value in another type.
  4551. *
  4552. * @tsl
  4553. * @function
  4554. * @param {Node | number} x - The parameter.
  4555. * @param {string} y - The new type.
  4556. * @returns {Node}
  4557. */
  4558. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST ).setParameterLength( 2 );
  4559. /**
  4560. * Returns `true` if `x` equals `y`.
  4561. *
  4562. * @tsl
  4563. * @function
  4564. * @param {Node | number} x - The first parameter.
  4565. * @param {Node | number} y - The second parameter.
  4566. * @deprecated since r175. Use {@link equal} instead.
  4567. * @returns {Node<bool>}
  4568. */
  4569. const equals = ( x, y ) => { // @deprecated, r172
  4570. console.warn( 'THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4571. return equal( x, y );
  4572. };
  4573. /**
  4574. * Returns the least of the given values.
  4575. *
  4576. * @tsl
  4577. * @function
  4578. * @param {...(Node | number)} values - The values to compare.
  4579. * @returns {Node}
  4580. */
  4581. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4582. /**
  4583. * Returns the greatest of the given values.
  4584. *
  4585. * @tsl
  4586. * @function
  4587. * @param {...(Node | number)} values - The values to compare.
  4588. * @returns {Node}
  4589. */
  4590. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4591. /**
  4592. * Generate a step function by comparing two values.
  4593. *
  4594. * @tsl
  4595. * @function
  4596. * @param {Node | number} x - The y parameter.
  4597. * @param {Node | number} y - The x parameter.
  4598. * @returns {Node}
  4599. */
  4600. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4601. /**
  4602. * Calculates the reflection direction for an incident vector.
  4603. *
  4604. * @tsl
  4605. * @function
  4606. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4607. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4608. * @returns {Node<vec2|vec3|vec4>}
  4609. */
  4610. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4611. /**
  4612. * Calculates the distance between two points.
  4613. *
  4614. * @tsl
  4615. * @function
  4616. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4617. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4618. * @returns {Node<float>}
  4619. */
  4620. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  4621. /**
  4622. * Calculates the absolute difference between two values.
  4623. *
  4624. * @tsl
  4625. * @function
  4626. * @param {Node | number} x - The first parameter.
  4627. * @param {Node | number} y - The second parameter.
  4628. * @returns {Node}
  4629. */
  4630. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  4631. /**
  4632. * Calculates the dot product of two vectors.
  4633. *
  4634. * @tsl
  4635. * @function
  4636. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4637. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4638. * @returns {Node<float>}
  4639. */
  4640. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT ).setParameterLength( 2 );
  4641. /**
  4642. * Calculates the cross product of two vectors.
  4643. *
  4644. * @tsl
  4645. * @function
  4646. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4647. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4648. * @returns {Node<vec2|vec3|vec4>}
  4649. */
  4650. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  4651. /**
  4652. * Return the value of the first parameter raised to the power of the second one.
  4653. *
  4654. * @tsl
  4655. * @function
  4656. * @param {Node | number} x - The first parameter.
  4657. * @param {Node | number} y - The second parameter.
  4658. * @returns {Node}
  4659. */
  4660. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW ).setParameterLength( 2 );
  4661. /**
  4662. * Returns the square of the parameter.
  4663. *
  4664. * @tsl
  4665. * @function
  4666. * @param {Node | number} x - The first parameter.
  4667. * @returns {Node}
  4668. */
  4669. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 ).setParameterLength( 1 );
  4670. /**
  4671. * Returns the cube of the parameter.
  4672. *
  4673. * @tsl
  4674. * @function
  4675. * @param {Node | number} x - The first parameter.
  4676. * @returns {Node}
  4677. */
  4678. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 ).setParameterLength( 1 );
  4679. /**
  4680. * Returns the fourth power of the parameter.
  4681. *
  4682. * @tsl
  4683. * @function
  4684. * @param {Node | number} x - The first parameter.
  4685. * @returns {Node}
  4686. */
  4687. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 ).setParameterLength( 1 );
  4688. /**
  4689. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4690. *
  4691. * @tsl
  4692. * @function
  4693. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4694. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4695. * @returns {Node}
  4696. */
  4697. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  4698. /**
  4699. * Returns the cube root of a number.
  4700. *
  4701. * @tsl
  4702. * @function
  4703. * @param {Node | number} a - The first parameter.
  4704. * @returns {Node}
  4705. */
  4706. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4707. /**
  4708. * Calculate the squared length of a vector.
  4709. *
  4710. * @tsl
  4711. * @function
  4712. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4713. * @returns {Node<float>}
  4714. */
  4715. const lengthSq = ( a ) => dot( a, a );
  4716. /**
  4717. * Linearly interpolates between two values.
  4718. *
  4719. * @tsl
  4720. * @function
  4721. * @param {Node | number} a - The first parameter.
  4722. * @param {Node | number} b - The second parameter.
  4723. * @param {Node | number} t - The interpolation value.
  4724. * @returns {Node}
  4725. */
  4726. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX ).setParameterLength( 3 );
  4727. /**
  4728. * Constrains a value to lie between two further values.
  4729. *
  4730. * @tsl
  4731. * @function
  4732. * @param {Node | number} value - The value to constrain.
  4733. * @param {Node | number} [low=0] - The lower bound.
  4734. * @param {Node | number} [high=1] - The upper bound.
  4735. * @returns {Node}
  4736. */
  4737. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4738. /**
  4739. * Constrains a value between `0` and `1`.
  4740. *
  4741. * @tsl
  4742. * @function
  4743. * @param {Node | number} value - The value to constrain.
  4744. * @returns {Node}
  4745. */
  4746. const saturate = ( value ) => clamp( value );
  4747. /**
  4748. * Calculates the refraction direction for an incident vector.
  4749. *
  4750. * @tsl
  4751. * @function
  4752. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4753. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4754. * @param {Node<float>} eta - The ratio of indices of refraction.
  4755. * @returns {Node<vec2|vec3|vec4>}
  4756. */
  4757. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  4758. /**
  4759. * Performs a Hermite interpolation between two values.
  4760. *
  4761. * @tsl
  4762. * @function
  4763. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4764. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4765. * @param {Node | number} x - The source value for interpolation.
  4766. * @returns {Node}
  4767. */
  4768. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  4769. /**
  4770. * Returns a vector pointing in the same direction as another.
  4771. *
  4772. * @tsl
  4773. * @function
  4774. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4775. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4776. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4777. * @returns {Node<vec2|vec3|vec4>}
  4778. */
  4779. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  4780. /**
  4781. * Returns a random value for the given uv.
  4782. *
  4783. * @tsl
  4784. * @function
  4785. * @param {Node<vec2>} uv - The uv node.
  4786. * @returns {Node<float>}
  4787. */
  4788. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4789. const a = 12.9898, b = 78.233, c = 43758.5453;
  4790. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4791. return fract( sin( sn ).mul( c ) );
  4792. } );
  4793. /**
  4794. * Alias for `mix()` with a different parameter order.
  4795. *
  4796. * @tsl
  4797. * @function
  4798. * @param {Node | number} t - The interpolation value.
  4799. * @param {Node | number} e1 - The first parameter.
  4800. * @param {Node | number} e2 - The second parameter.
  4801. * @returns {Node}
  4802. */
  4803. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4804. /**
  4805. * Alias for `smoothstep()` with a different parameter order.
  4806. *
  4807. * @tsl
  4808. * @function
  4809. * @param {Node | number} x - The source value for interpolation.
  4810. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4811. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4812. * @returns {Node}
  4813. */
  4814. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4815. /**
  4816. * Returns the arc-tangent of the quotient of its parameters.
  4817. *
  4818. * @tsl
  4819. * @function
  4820. * @deprecated since r172. Use {@link atan} instead.
  4821. *
  4822. * @param {Node | number} y - The y parameter.
  4823. * @param {Node | number} x - The x parameter.
  4824. * @returns {Node}
  4825. */
  4826. const atan2 = ( y, x ) => { // @deprecated, r172
  4827. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4828. return atan( y, x );
  4829. };
  4830. // GLSL alias function
  4831. const faceforward = faceForward;
  4832. const inversesqrt = inverseSqrt;
  4833. // Method chaining
  4834. addMethodChaining( 'all', all );
  4835. addMethodChaining( 'any', any );
  4836. addMethodChaining( 'equals', equals );
  4837. addMethodChaining( 'radians', radians );
  4838. addMethodChaining( 'degrees', degrees );
  4839. addMethodChaining( 'exp', exp );
  4840. addMethodChaining( 'exp2', exp2 );
  4841. addMethodChaining( 'log', log );
  4842. addMethodChaining( 'log2', log2 );
  4843. addMethodChaining( 'sqrt', sqrt );
  4844. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4845. addMethodChaining( 'floor', floor );
  4846. addMethodChaining( 'ceil', ceil );
  4847. addMethodChaining( 'normalize', normalize );
  4848. addMethodChaining( 'fract', fract );
  4849. addMethodChaining( 'sin', sin );
  4850. addMethodChaining( 'cos', cos );
  4851. addMethodChaining( 'tan', tan );
  4852. addMethodChaining( 'asin', asin );
  4853. addMethodChaining( 'acos', acos );
  4854. addMethodChaining( 'atan', atan );
  4855. addMethodChaining( 'abs', abs );
  4856. addMethodChaining( 'sign', sign );
  4857. addMethodChaining( 'length', length );
  4858. addMethodChaining( 'lengthSq', lengthSq );
  4859. addMethodChaining( 'negate', negate );
  4860. addMethodChaining( 'oneMinus', oneMinus );
  4861. addMethodChaining( 'dFdx', dFdx );
  4862. addMethodChaining( 'dFdy', dFdy );
  4863. addMethodChaining( 'round', round );
  4864. addMethodChaining( 'reciprocal', reciprocal );
  4865. addMethodChaining( 'trunc', trunc );
  4866. addMethodChaining( 'fwidth', fwidth );
  4867. addMethodChaining( 'atan2', atan2 );
  4868. addMethodChaining( 'min', min$1 );
  4869. addMethodChaining( 'max', max$1 );
  4870. addMethodChaining( 'step', step );
  4871. addMethodChaining( 'reflect', reflect );
  4872. addMethodChaining( 'distance', distance );
  4873. addMethodChaining( 'dot', dot );
  4874. addMethodChaining( 'cross', cross );
  4875. addMethodChaining( 'pow', pow );
  4876. addMethodChaining( 'pow2', pow2 );
  4877. addMethodChaining( 'pow3', pow3 );
  4878. addMethodChaining( 'pow4', pow4 );
  4879. addMethodChaining( 'transformDirection', transformDirection );
  4880. addMethodChaining( 'mix', mixElement );
  4881. addMethodChaining( 'clamp', clamp );
  4882. addMethodChaining( 'refract', refract );
  4883. addMethodChaining( 'smoothstep', smoothstepElement );
  4884. addMethodChaining( 'faceForward', faceForward );
  4885. addMethodChaining( 'difference', difference );
  4886. addMethodChaining( 'saturate', saturate );
  4887. addMethodChaining( 'cbrt', cbrt );
  4888. addMethodChaining( 'transpose', transpose );
  4889. addMethodChaining( 'rand', rand );
  4890. /**
  4891. * Represents a logical `if/else` statement. Can be used as an alternative
  4892. * to the `If()`/`Else()` syntax.
  4893. *
  4894. * The corresponding TSL `select()` looks like so:
  4895. * ```js
  4896. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4897. * ```
  4898. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4899. * determine the outcome of the entire statement.
  4900. *
  4901. * @augments Node
  4902. */
  4903. class ConditionalNode extends Node {
  4904. static get type() {
  4905. return 'ConditionalNode';
  4906. }
  4907. /**
  4908. * Constructs a new conditional node.
  4909. *
  4910. * @param {Node} condNode - The node that defines the condition.
  4911. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4912. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4913. */
  4914. constructor( condNode, ifNode, elseNode = null ) {
  4915. super();
  4916. /**
  4917. * The node that defines the condition.
  4918. *
  4919. * @type {Node}
  4920. */
  4921. this.condNode = condNode;
  4922. /**
  4923. * The node that is evaluate when the condition ends up `true`.
  4924. *
  4925. * @type {Node}
  4926. */
  4927. this.ifNode = ifNode;
  4928. /**
  4929. * The node that is evaluate when the condition ends up `false`.
  4930. *
  4931. * @type {?Node}
  4932. * @default null
  4933. */
  4934. this.elseNode = elseNode;
  4935. }
  4936. /**
  4937. * This method is overwritten since the node type is inferred from the if/else
  4938. * nodes.
  4939. *
  4940. * @param {NodeBuilder} builder - The current node builder.
  4941. * @return {string} The node type.
  4942. */
  4943. getNodeType( builder ) {
  4944. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4945. if ( ifNode === undefined ) {
  4946. // fallback setup
  4947. this.setup( builder );
  4948. return this.getNodeType( builder );
  4949. }
  4950. const ifType = ifNode.getNodeType( builder );
  4951. if ( elseNode !== null ) {
  4952. const elseType = elseNode.getNodeType( builder );
  4953. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4954. return elseType;
  4955. }
  4956. }
  4957. return ifType;
  4958. }
  4959. setup( builder ) {
  4960. const condNode = this.condNode.cache();
  4961. const ifNode = this.ifNode.cache();
  4962. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4963. //
  4964. const currentNodeBlock = builder.context.nodeBlock;
  4965. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4966. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4967. //
  4968. const properties = builder.getNodeProperties( this );
  4969. properties.condNode = condNode;
  4970. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4971. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4972. }
  4973. generate( builder, output ) {
  4974. const type = this.getNodeType( builder );
  4975. const nodeData = builder.getDataFromNode( this );
  4976. if ( nodeData.nodeProperty !== undefined ) {
  4977. return nodeData.nodeProperty;
  4978. }
  4979. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4980. const functionNode = builder.currentFunctionNode;
  4981. const needsOutput = output !== 'void';
  4982. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4983. nodeData.nodeProperty = nodeProperty;
  4984. const nodeSnippet = condNode.build( builder, 'bool' );
  4985. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4986. let ifSnippet = ifNode.build( builder, type );
  4987. if ( ifSnippet ) {
  4988. if ( needsOutput ) {
  4989. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4990. } else {
  4991. ifSnippet = 'return ' + ifSnippet + ';';
  4992. if ( functionNode === null ) {
  4993. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  4994. ifSnippet = '// ' + ifSnippet;
  4995. }
  4996. }
  4997. }
  4998. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4999. if ( elseNode !== null ) {
  5000. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5001. let elseSnippet = elseNode.build( builder, type );
  5002. if ( elseSnippet ) {
  5003. if ( needsOutput ) {
  5004. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5005. } else {
  5006. elseSnippet = 'return ' + elseSnippet + ';';
  5007. if ( functionNode === null ) {
  5008. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5009. elseSnippet = '// ' + elseSnippet;
  5010. }
  5011. }
  5012. }
  5013. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5014. } else {
  5015. builder.addFlowCode( '\n\n' );
  5016. }
  5017. return builder.format( nodeProperty, type, output );
  5018. }
  5019. }
  5020. /**
  5021. * TSL function for creating a conditional node.
  5022. *
  5023. * @tsl
  5024. * @function
  5025. * @param {Node} condNode - The node that defines the condition.
  5026. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5027. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5028. * @returns {ConditionalNode}
  5029. */
  5030. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5031. addMethodChaining( 'select', select );
  5032. // Deprecated
  5033. /**
  5034. * @tsl
  5035. * @function
  5036. * @deprecated since r168. Use {@link select} instead.
  5037. *
  5038. * @param {...any} params
  5039. * @returns {ConditionalNode}
  5040. */
  5041. const cond = ( ...params ) => { // @deprecated, r168
  5042. console.warn( 'THREE.TSL: cond() has been renamed to select().' );
  5043. return select( ...params );
  5044. };
  5045. addMethodChaining( 'cond', cond );
  5046. /**
  5047. * This node can be used as a context management component for another node.
  5048. * {@link NodeBuilder} performs its node building process in a specific context and
  5049. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5050. *
  5051. * ```js
  5052. *node.context( { getUV: () => customCoord } );
  5053. *```
  5054. * @augments Node
  5055. */
  5056. class ContextNode extends Node {
  5057. static get type() {
  5058. return 'ContextNode';
  5059. }
  5060. /**
  5061. * Constructs a new context node.
  5062. *
  5063. * @param {Node} node - The node whose context should be modified.
  5064. * @param {Object} [value={}] - The modified context data.
  5065. */
  5066. constructor( node, value = {} ) {
  5067. super();
  5068. /**
  5069. * This flag can be used for type testing.
  5070. *
  5071. * @type {boolean}
  5072. * @readonly
  5073. * @default true
  5074. */
  5075. this.isContextNode = true;
  5076. /**
  5077. * The node whose context should be modified.
  5078. *
  5079. * @type {Node}
  5080. */
  5081. this.node = node;
  5082. /**
  5083. * The modified context data.
  5084. *
  5085. * @type {Object}
  5086. * @default {}
  5087. */
  5088. this.value = value;
  5089. }
  5090. /**
  5091. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5092. *
  5093. * @return {Node} A reference to {@link ContextNode#node}.
  5094. */
  5095. getScope() {
  5096. return this.node.getScope();
  5097. }
  5098. /**
  5099. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5100. *
  5101. * @param {NodeBuilder} builder - The current node builder.
  5102. * @return {string} The node type.
  5103. */
  5104. getNodeType( builder ) {
  5105. return this.node.getNodeType( builder );
  5106. }
  5107. analyze( builder ) {
  5108. const previousContext = builder.getContext();
  5109. builder.setContext( { ...builder.context, ...this.value } );
  5110. this.node.build( builder );
  5111. builder.setContext( previousContext );
  5112. }
  5113. setup( builder ) {
  5114. const previousContext = builder.getContext();
  5115. builder.setContext( { ...builder.context, ...this.value } );
  5116. this.node.build( builder );
  5117. builder.setContext( previousContext );
  5118. }
  5119. generate( builder, output ) {
  5120. const previousContext = builder.getContext();
  5121. builder.setContext( { ...builder.context, ...this.value } );
  5122. const snippet = this.node.build( builder, output );
  5123. builder.setContext( previousContext );
  5124. return snippet;
  5125. }
  5126. }
  5127. /**
  5128. * TSL function for creating a context node.
  5129. *
  5130. * @tsl
  5131. * @function
  5132. * @param {Node} node - The node whose context should be modified.
  5133. * @param {Object} [value={}] - The modified context data.
  5134. * @returns {ContextNode}
  5135. */
  5136. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5137. /**
  5138. * TSL function for defining a label context value for a given node.
  5139. *
  5140. * @tsl
  5141. * @function
  5142. * @param {Node} node - The node whose context should be modified.
  5143. * @param {string} name - The name/label to set.
  5144. * @returns {ContextNode}
  5145. */
  5146. const label = ( node, name ) => context( node, { label: name } );
  5147. addMethodChaining( 'context', context );
  5148. addMethodChaining( 'label', label );
  5149. /**
  5150. * Class for representing shader variables as nodes. Variables are created from
  5151. * existing nodes like the following:
  5152. *
  5153. * ```js
  5154. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5155. * ```
  5156. *
  5157. * @augments Node
  5158. */
  5159. class VarNode extends Node {
  5160. static get type() {
  5161. return 'VarNode';
  5162. }
  5163. /**
  5164. * Constructs a new variable node.
  5165. *
  5166. * @param {Node} node - The node for which a variable should be created.
  5167. * @param {?string} [name=null] - The name of the variable in the shader.
  5168. * @param {boolean} [readOnly=false] - The read-only flag.
  5169. */
  5170. constructor( node, name = null, readOnly = false ) {
  5171. super();
  5172. /**
  5173. * The node for which a variable should be created.
  5174. *
  5175. * @type {Node}
  5176. */
  5177. this.node = node;
  5178. /**
  5179. * The name of the variable in the shader. If no name is defined,
  5180. * the node system auto-generates one.
  5181. *
  5182. * @type {?string}
  5183. * @default null
  5184. */
  5185. this.name = name;
  5186. /**
  5187. * `VarNode` sets this property to `true` by default.
  5188. *
  5189. * @type {boolean}
  5190. * @default true
  5191. */
  5192. this.global = true;
  5193. /**
  5194. * This flag can be used for type testing.
  5195. *
  5196. * @type {boolean}
  5197. * @readonly
  5198. * @default true
  5199. */
  5200. this.isVarNode = true;
  5201. /**
  5202. *
  5203. * The read-only flag.
  5204. *
  5205. * @type {boolean}
  5206. * @default false
  5207. */
  5208. this.readOnly = readOnly;
  5209. /**
  5210. *
  5211. * Add this flag to the node system to indicate that this node require parents.
  5212. *
  5213. * @type {boolean}
  5214. * @default true
  5215. */
  5216. this.parents = true;
  5217. }
  5218. getMemberType( builder, name ) {
  5219. return this.node.getMemberType( builder, name );
  5220. }
  5221. getElementType( builder ) {
  5222. return this.node.getElementType( builder );
  5223. }
  5224. getNodeType( builder ) {
  5225. return this.node.getNodeType( builder );
  5226. }
  5227. generate( builder ) {
  5228. const { node, name, readOnly } = this;
  5229. const { renderer } = builder;
  5230. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5231. let isDeterministic = false;
  5232. let shouldTreatAsReadOnly = false;
  5233. if ( readOnly ) {
  5234. isDeterministic = builder.isDeterministic( node );
  5235. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5236. }
  5237. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  5238. const snippet = node.build( builder, vectorType );
  5239. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5240. const propertyName = builder.getPropertyName( nodeVar );
  5241. let declarationPrefix = propertyName;
  5242. if ( shouldTreatAsReadOnly ) {
  5243. if ( isWebGPUBackend ) {
  5244. declarationPrefix = isDeterministic
  5245. ? `const ${ propertyName }`
  5246. : `let ${ propertyName }`;
  5247. } else {
  5248. const count = builder.getArrayCount( node );
  5249. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5250. }
  5251. }
  5252. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5253. return propertyName;
  5254. }
  5255. }
  5256. /**
  5257. * TSL function for creating a var node.
  5258. *
  5259. * @tsl
  5260. * @function
  5261. * @param {Node} node - The node for which a variable should be created.
  5262. * @param {?string} name - The name of the variable in the shader.
  5263. * @returns {VarNode}
  5264. */
  5265. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5266. /**
  5267. * TSL function for creating a var node.
  5268. *
  5269. * @tsl
  5270. * @function
  5271. * @param {Node} node - The node for which a variable should be created.
  5272. * @param {?string} name - The name of the variable in the shader.
  5273. * @returns {VarNode}
  5274. */
  5275. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5276. /**
  5277. * TSL function for creating a const node.
  5278. *
  5279. * @tsl
  5280. * @function
  5281. * @param {Node} node - The node for which a constant should be created.
  5282. * @param {?string} name - The name of the constant in the shader.
  5283. * @returns {VarNode}
  5284. */
  5285. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5286. // Method chaining
  5287. addMethodChaining( 'toVar', Var );
  5288. addMethodChaining( 'toConst', Const );
  5289. // Deprecated
  5290. /**
  5291. * @tsl
  5292. * @function
  5293. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  5294. *
  5295. * @param {any} node
  5296. * @returns {VarNode}
  5297. */
  5298. const temp = ( node ) => { // @deprecated, r170
  5299. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  5300. return createVar( node );
  5301. };
  5302. addMethodChaining( 'temp', temp );
  5303. /**
  5304. * Class for representing shader varyings as nodes. Varyings are create from
  5305. * existing nodes like the following:
  5306. *
  5307. * ```js
  5308. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5309. * ```
  5310. *
  5311. * @augments Node
  5312. */
  5313. class VaryingNode extends Node {
  5314. static get type() {
  5315. return 'VaryingNode';
  5316. }
  5317. /**
  5318. * Constructs a new varying node.
  5319. *
  5320. * @param {Node} node - The node for which a varying should be created.
  5321. * @param {?string} name - The name of the varying in the shader.
  5322. */
  5323. constructor( node, name = null ) {
  5324. super();
  5325. /**
  5326. * The node for which a varying should be created.
  5327. *
  5328. * @type {Node}
  5329. */
  5330. this.node = node;
  5331. /**
  5332. * The name of the varying in the shader. If no name is defined,
  5333. * the node system auto-generates one.
  5334. *
  5335. * @type {?string}
  5336. * @default null
  5337. */
  5338. this.name = name;
  5339. /**
  5340. * This flag can be used for type testing.
  5341. *
  5342. * @type {boolean}
  5343. * @readonly
  5344. * @default true
  5345. */
  5346. this.isVaryingNode = true;
  5347. /**
  5348. * The interpolation type of the varying data.
  5349. *
  5350. * @type {?string}
  5351. * @default null
  5352. */
  5353. this.interpolationType = null;
  5354. /**
  5355. * The interpolation sampling type of varying data.
  5356. *
  5357. * @type {?string}
  5358. * @default null
  5359. */
  5360. this.interpolationSampling = null;
  5361. /**
  5362. * This flag is used for global cache.
  5363. *
  5364. * @type {boolean}
  5365. * @default true
  5366. */
  5367. this.global = true;
  5368. }
  5369. /**
  5370. * Defines the interpolation type of the varying.
  5371. *
  5372. * @param {string} type - The interpolation type.
  5373. * @param {?string} sampling - The interpolation sampling type
  5374. * @return {VaryingNode} A reference to this node.
  5375. */
  5376. setInterpolation( type, sampling = null ) {
  5377. this.interpolationType = type;
  5378. this.interpolationSampling = sampling;
  5379. return this;
  5380. }
  5381. getHash( builder ) {
  5382. return this.name || super.getHash( builder );
  5383. }
  5384. getNodeType( builder ) {
  5385. // VaryingNode is auto type
  5386. return this.node.getNodeType( builder );
  5387. }
  5388. /**
  5389. * This method performs the setup of a varying node with the current node builder.
  5390. *
  5391. * @param {NodeBuilder} builder - The current node builder.
  5392. * @return {NodeVarying} The node varying from the node builder.
  5393. */
  5394. setupVarying( builder ) {
  5395. const properties = builder.getNodeProperties( this );
  5396. let varying = properties.varying;
  5397. if ( varying === undefined ) {
  5398. const name = this.name;
  5399. const type = this.getNodeType( builder );
  5400. const interpolationType = this.interpolationType;
  5401. const interpolationSampling = this.interpolationSampling;
  5402. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5403. properties.node = this.node;
  5404. }
  5405. // this property can be used to check if the varying can be optimized for a variable
  5406. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5407. return varying;
  5408. }
  5409. setup( builder ) {
  5410. this.setupVarying( builder );
  5411. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5412. }
  5413. analyze( builder ) {
  5414. this.setupVarying( builder );
  5415. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5416. }
  5417. generate( builder ) {
  5418. const properties = builder.getNodeProperties( this );
  5419. const varying = this.setupVarying( builder );
  5420. if ( properties.propertyName === undefined ) {
  5421. const type = this.getNodeType( builder );
  5422. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5423. // force node run in vertex stage
  5424. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  5425. properties.propertyName = propertyName;
  5426. }
  5427. return builder.getPropertyName( varying );
  5428. }
  5429. }
  5430. /**
  5431. * TSL function for creating a varying node.
  5432. *
  5433. * @tsl
  5434. * @function
  5435. * @param {Node} node - The node for which a varying should be created.
  5436. * @param {?string} name - The name of the varying in the shader.
  5437. * @returns {VaryingNode}
  5438. */
  5439. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5440. /**
  5441. * Computes a node in the vertex stage.
  5442. *
  5443. * @tsl
  5444. * @function
  5445. * @param {Node} node - The node which should be executed in the vertex stage.
  5446. * @returns {VaryingNode}
  5447. */
  5448. const vertexStage = ( node ) => varying( node );
  5449. addMethodChaining( 'toVarying', varying );
  5450. addMethodChaining( 'toVertexStage', vertexStage );
  5451. // Deprecated
  5452. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5453. console.warn( 'THREE.TSL: .varying() has been renamed to .toVarying().' );
  5454. return varying( ...params );
  5455. } );
  5456. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5457. console.warn( 'THREE.TSL: .vertexStage() has been renamed to .toVertexStage().' );
  5458. return varying( ...params );
  5459. } );
  5460. /**
  5461. * Converts the given color value from sRGB to linear-sRGB color space.
  5462. *
  5463. * @tsl
  5464. * @function
  5465. * @param {Node<vec3>} color - The sRGB color.
  5466. * @return {Node<vec3>} The linear-sRGB color.
  5467. */
  5468. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5469. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5470. const b = color.mul( 0.0773993808 );
  5471. const factor = color.lessThanEqual( 0.04045 );
  5472. const rgbResult = mix( a, b, factor );
  5473. return rgbResult;
  5474. } ).setLayout( {
  5475. name: 'sRGBTransferEOTF',
  5476. type: 'vec3',
  5477. inputs: [
  5478. { name: 'color', type: 'vec3' }
  5479. ]
  5480. } );
  5481. /**
  5482. * Converts the given color value from linear-sRGB to sRGB color space.
  5483. *
  5484. * @tsl
  5485. * @function
  5486. * @param {Node<vec3>} color - The linear-sRGB color.
  5487. * @return {Node<vec3>} The sRGB color.
  5488. */
  5489. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5490. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5491. const b = color.mul( 12.92 );
  5492. const factor = color.lessThanEqual( 0.0031308 );
  5493. const rgbResult = mix( a, b, factor );
  5494. return rgbResult;
  5495. } ).setLayout( {
  5496. name: 'sRGBTransferOETF',
  5497. type: 'vec3',
  5498. inputs: [
  5499. { name: 'color', type: 'vec3' }
  5500. ]
  5501. } );
  5502. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5503. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5504. /**
  5505. * This node represents a color space conversion. Meaning it converts
  5506. * a color value from a source to a target color space.
  5507. *
  5508. * @augments TempNode
  5509. */
  5510. class ColorSpaceNode extends TempNode {
  5511. static get type() {
  5512. return 'ColorSpaceNode';
  5513. }
  5514. /**
  5515. * Constructs a new color space node.
  5516. *
  5517. * @param {Node} colorNode - Represents the color to convert.
  5518. * @param {string} source - The source color space.
  5519. * @param {string} target - The target color space.
  5520. */
  5521. constructor( colorNode, source, target ) {
  5522. super( 'vec4' );
  5523. /**
  5524. * Represents the color to convert.
  5525. *
  5526. * @type {Node}
  5527. */
  5528. this.colorNode = colorNode;
  5529. /**
  5530. * The source color space.
  5531. *
  5532. * @type {string}
  5533. */
  5534. this.source = source;
  5535. /**
  5536. * The target color space.
  5537. *
  5538. * @type {string}
  5539. */
  5540. this.target = target;
  5541. }
  5542. /**
  5543. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5544. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5545. * color management and renderer.
  5546. *
  5547. * @param {NodeBuilder} builder - The current node builder.
  5548. * @param {string} colorSpace - The color space to resolve.
  5549. * @return {string} The resolved color space.
  5550. */
  5551. resolveColorSpace( builder, colorSpace ) {
  5552. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5553. return ColorManagement.workingColorSpace;
  5554. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5555. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5556. }
  5557. return colorSpace;
  5558. }
  5559. setup( builder ) {
  5560. const { colorNode } = this;
  5561. const source = this.resolveColorSpace( builder, this.source );
  5562. const target = this.resolveColorSpace( builder, this.target );
  5563. let outputNode = colorNode;
  5564. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5565. return outputNode;
  5566. }
  5567. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5568. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5569. }
  5570. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5571. outputNode = vec4(
  5572. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5573. outputNode.a
  5574. );
  5575. }
  5576. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5577. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5578. }
  5579. return outputNode;
  5580. }
  5581. }
  5582. /**
  5583. * TSL function for converting a given color node from the current working color space to the given color space.
  5584. *
  5585. * @tsl
  5586. * @function
  5587. * @param {Node} node - Represents the node to convert.
  5588. * @param {string} targetColorSpace - The target color space.
  5589. * @returns {ColorSpaceNode}
  5590. */
  5591. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  5592. /**
  5593. * TSL function for converting a given color node from the given color space to the current working color space.
  5594. *
  5595. * @tsl
  5596. * @function
  5597. * @param {Node} node - Represents the node to convert.
  5598. * @param {string} sourceColorSpace - The source color space.
  5599. * @returns {ColorSpaceNode}
  5600. */
  5601. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  5602. /**
  5603. * TSL function for converting a given color node from one color space to another one.
  5604. *
  5605. * @tsl
  5606. * @function
  5607. * @param {Node} node - Represents the node to convert.
  5608. * @param {string} sourceColorSpace - The source color space.
  5609. * @param {string} targetColorSpace - The target color space.
  5610. * @returns {ColorSpaceNode}
  5611. */
  5612. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5613. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5614. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5615. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5616. /**
  5617. * This class is only relevant if the referenced property is array-like.
  5618. * In this case, `ReferenceElementNode` allows to refer to a specific
  5619. * element inside the data structure via an index.
  5620. *
  5621. * @augments ArrayElementNode
  5622. */
  5623. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5624. static get type() {
  5625. return 'ReferenceElementNode';
  5626. }
  5627. /**
  5628. * Constructs a new reference element node.
  5629. *
  5630. * @param {ReferenceBaseNode} referenceNode - The reference node.
  5631. * @param {Node} indexNode - The index node that defines the element access.
  5632. */
  5633. constructor( referenceNode, indexNode ) {
  5634. super( referenceNode, indexNode );
  5635. /**
  5636. * Similar to {@link ReferenceBaseNode#reference}, an additional
  5637. * property references to the current node.
  5638. *
  5639. * @type {?ReferenceBaseNode}
  5640. * @default null
  5641. */
  5642. this.referenceNode = referenceNode;
  5643. /**
  5644. * This flag can be used for type testing.
  5645. *
  5646. * @type {boolean}
  5647. * @readonly
  5648. * @default true
  5649. */
  5650. this.isReferenceElementNode = true;
  5651. }
  5652. /**
  5653. * This method is overwritten since the node type is inferred from
  5654. * the uniform type of the reference node.
  5655. *
  5656. * @return {string} The node type.
  5657. */
  5658. getNodeType() {
  5659. return this.referenceNode.uniformType;
  5660. }
  5661. generate( builder ) {
  5662. const snippet = super.generate( builder );
  5663. const arrayType = this.referenceNode.getNodeType();
  5664. const elementType = this.getNodeType();
  5665. return builder.format( snippet, arrayType, elementType );
  5666. }
  5667. };
  5668. /**
  5669. * Base class for nodes which establishes a reference to a property of another object.
  5670. * In this way, the value of the node is automatically linked to the value of
  5671. * referenced object. Reference nodes internally represent the linked value
  5672. * as a uniform.
  5673. *
  5674. * @augments Node
  5675. */
  5676. class ReferenceBaseNode extends Node {
  5677. static get type() {
  5678. return 'ReferenceBaseNode';
  5679. }
  5680. /**
  5681. * Constructs a new reference base node.
  5682. *
  5683. * @param {string} property - The name of the property the node refers to.
  5684. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  5685. * @param {?Object} [object=null] - The object the property belongs to.
  5686. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5687. */
  5688. constructor( property, uniformType, object = null, count = null ) {
  5689. super();
  5690. /**
  5691. * The name of the property the node refers to.
  5692. *
  5693. * @type {string}
  5694. */
  5695. this.property = property;
  5696. /**
  5697. * The uniform type that should be used to represent the property value.
  5698. *
  5699. * @type {string}
  5700. */
  5701. this.uniformType = uniformType;
  5702. /**
  5703. * The object the property belongs to.
  5704. *
  5705. * @type {?Object}
  5706. * @default null
  5707. */
  5708. this.object = object;
  5709. /**
  5710. * When the linked property is an array, this parameter defines its length.
  5711. *
  5712. * @type {?number}
  5713. * @default null
  5714. */
  5715. this.count = count;
  5716. /**
  5717. * The property name might have dots so nested properties can be referred.
  5718. * The hierarchy of the names is stored inside this array.
  5719. *
  5720. * @type {Array<string>}
  5721. */
  5722. this.properties = property.split( '.' );
  5723. /**
  5724. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  5725. * since the final reference might be updated from calling code.
  5726. *
  5727. * @type {?Object}
  5728. * @default null
  5729. */
  5730. this.reference = object;
  5731. /**
  5732. * The uniform node that holds the value of the reference node.
  5733. *
  5734. * @type {UniformNode}
  5735. * @default null
  5736. */
  5737. this.node = null;
  5738. /**
  5739. * The uniform group of the internal uniform.
  5740. *
  5741. * @type {UniformGroupNode}
  5742. * @default null
  5743. */
  5744. this.group = null;
  5745. /**
  5746. * Overwritten since reference nodes are updated per object.
  5747. *
  5748. * @type {string}
  5749. * @default 'object'
  5750. */
  5751. this.updateType = NodeUpdateType.OBJECT;
  5752. }
  5753. /**
  5754. * Sets the uniform group for this reference node.
  5755. *
  5756. * @param {UniformGroupNode} group - The uniform group to set.
  5757. * @return {ReferenceBaseNode} A reference to this node.
  5758. */
  5759. setGroup( group ) {
  5760. this.group = group;
  5761. return this;
  5762. }
  5763. /**
  5764. * When the referred property is array-like, this method can be used
  5765. * to access elements via an index node.
  5766. *
  5767. * @param {IndexNode} indexNode - indexNode.
  5768. * @return {ReferenceElementNode} A reference to an element.
  5769. */
  5770. element( indexNode ) {
  5771. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5772. }
  5773. /**
  5774. * Sets the node type which automatically defines the internal
  5775. * uniform type.
  5776. *
  5777. * @param {string} uniformType - The type to set.
  5778. */
  5779. setNodeType( uniformType ) {
  5780. const node = uniform( null, uniformType ).getSelf();
  5781. if ( this.group !== null ) {
  5782. node.setGroup( this.group );
  5783. }
  5784. this.node = node;
  5785. }
  5786. /**
  5787. * This method is overwritten since the node type is inferred from
  5788. * the type of the reference node.
  5789. *
  5790. * @param {NodeBuilder} builder - The current node builder.
  5791. * @return {string} The node type.
  5792. */
  5793. getNodeType( builder ) {
  5794. if ( this.node === null ) {
  5795. this.updateReference( builder );
  5796. this.updateValue();
  5797. }
  5798. return this.node.getNodeType( builder );
  5799. }
  5800. /**
  5801. * Returns the property value from the given referred object.
  5802. *
  5803. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5804. * @return {any} The value.
  5805. */
  5806. getValueFromReference( object = this.reference ) {
  5807. const { properties } = this;
  5808. let value = object[ properties[ 0 ] ];
  5809. for ( let i = 1; i < properties.length; i ++ ) {
  5810. value = value[ properties[ i ] ];
  5811. }
  5812. return value;
  5813. }
  5814. /**
  5815. * Allows to update the reference based on the given state. The state is only
  5816. * evaluated {@link ReferenceBaseNode#object} is not set.
  5817. *
  5818. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5819. * @return {Object} The updated reference.
  5820. */
  5821. updateReference( state ) {
  5822. this.reference = this.object !== null ? this.object : state.object;
  5823. return this.reference;
  5824. }
  5825. /**
  5826. * The output of the reference node is the internal uniform node.
  5827. *
  5828. * @return {UniformNode} The output node.
  5829. */
  5830. setup() {
  5831. this.updateValue();
  5832. return this.node;
  5833. }
  5834. /**
  5835. * Overwritten to update the internal uniform value.
  5836. *
  5837. * @param {NodeFrame} frame - A reference to the current node frame.
  5838. */
  5839. update( /*frame*/ ) {
  5840. this.updateValue();
  5841. }
  5842. /**
  5843. * Retrieves the value from the referred object property and uses it
  5844. * to updated the internal uniform.
  5845. */
  5846. updateValue() {
  5847. if ( this.node === null ) this.setNodeType( this.uniformType );
  5848. const value = this.getValueFromReference();
  5849. if ( Array.isArray( value ) ) {
  5850. this.node.array = value;
  5851. } else {
  5852. this.node.value = value;
  5853. }
  5854. }
  5855. }
  5856. /**
  5857. * TSL function for creating a reference base node.
  5858. *
  5859. * @tsl
  5860. * @function
  5861. * @param {string} name - The name of the property the node refers to.
  5862. * @param {string} type - The uniform type that should be used to represent the property value.
  5863. * @param {Object} object - The object the property belongs to.
  5864. * @returns {ReferenceBaseNode}
  5865. */
  5866. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5867. /**
  5868. * This node is a special type of reference node which is intended
  5869. * for linking renderer properties with node values.
  5870. * ```js
  5871. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5872. * ```
  5873. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5874. * automatically be updated.
  5875. *
  5876. * @augments ReferenceBaseNode
  5877. */
  5878. class RendererReferenceNode extends ReferenceBaseNode {
  5879. static get type() {
  5880. return 'RendererReferenceNode';
  5881. }
  5882. /**
  5883. * Constructs a new renderer reference node.
  5884. *
  5885. * @param {string} property - The name of the property the node refers to.
  5886. * @param {string} inputType - The uniform type that should be used to represent the property value.
  5887. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5888. * the node refers to the renderer of the current state.
  5889. */
  5890. constructor( property, inputType, renderer = null ) {
  5891. super( property, inputType, renderer );
  5892. /**
  5893. * The renderer the property belongs to. When no renderer is set,
  5894. * the node refers to the renderer of the current state.
  5895. *
  5896. * @type {?Renderer}
  5897. * @default null
  5898. */
  5899. this.renderer = renderer;
  5900. this.setGroup( renderGroup );
  5901. }
  5902. /**
  5903. * Updates the reference based on the given state. The state is only evaluated
  5904. * {@link RendererReferenceNode#renderer} is not set.
  5905. *
  5906. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5907. * @return {Object} The updated reference.
  5908. */
  5909. updateReference( state ) {
  5910. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5911. return this.reference;
  5912. }
  5913. }
  5914. /**
  5915. * TSL function for creating a renderer reference node.
  5916. *
  5917. * @tsl
  5918. * @function
  5919. * @param {string} name - The name of the property the node refers to.
  5920. * @param {string} type - The uniform type that should be used to represent the property value.
  5921. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5922. * the node refers to the renderer of the current state.
  5923. * @returns {RendererReferenceNode}
  5924. */
  5925. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5926. /**
  5927. * This node represents a tone mapping operation.
  5928. *
  5929. * @augments TempNode
  5930. */
  5931. class ToneMappingNode extends TempNode {
  5932. static get type() {
  5933. return 'ToneMappingNode';
  5934. }
  5935. /**
  5936. * Constructs a new tone mapping node.
  5937. *
  5938. * @param {number} toneMapping - The tone mapping type.
  5939. * @param {Node} exposureNode - The tone mapping exposure.
  5940. * @param {Node} [colorNode=null] - The color node to process.
  5941. */
  5942. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5943. super( 'vec3' );
  5944. /**
  5945. * The tone mapping type.
  5946. *
  5947. * @type {number}
  5948. */
  5949. this.toneMapping = toneMapping;
  5950. /**
  5951. * The tone mapping exposure.
  5952. *
  5953. * @type {Node}
  5954. * @default null
  5955. */
  5956. this.exposureNode = exposureNode;
  5957. /**
  5958. * Represents the color to process.
  5959. *
  5960. * @type {?Node}
  5961. * @default null
  5962. */
  5963. this.colorNode = colorNode;
  5964. }
  5965. /**
  5966. * Overwrites the default `customCacheKey()` implementation by including the tone
  5967. * mapping type into the cache key.
  5968. *
  5969. * @return {number} The hash.
  5970. */
  5971. customCacheKey() {
  5972. return hash$1( this.toneMapping );
  5973. }
  5974. setup( builder ) {
  5975. const colorNode = this.colorNode || builder.context.color;
  5976. const toneMapping = this.toneMapping;
  5977. if ( toneMapping === NoToneMapping ) return colorNode;
  5978. let outputNode = null;
  5979. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5980. if ( toneMappingFn !== null ) {
  5981. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5982. } else {
  5983. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5984. outputNode = colorNode;
  5985. }
  5986. return outputNode;
  5987. }
  5988. }
  5989. /**
  5990. * TSL function for creating a tone mapping node.
  5991. *
  5992. * @tsl
  5993. * @function
  5994. * @param {number} mapping - The tone mapping type.
  5995. * @param {Node<float> | number} exposure - The tone mapping exposure.
  5996. * @param {Node<vec3> | Color} color - The color node to process.
  5997. * @returns {ToneMappingNode<vec3>}
  5998. */
  5999. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6000. /**
  6001. * TSL object that represents the global tone mapping exposure of the renderer.
  6002. *
  6003. * @tsl
  6004. * @type {RendererReferenceNode<vec3>}
  6005. */
  6006. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6007. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6008. /**
  6009. * In earlier `three.js` versions it was only possible to define attribute data
  6010. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6011. * on the node level.
  6012. * ```js
  6013. * const geometry = new THREE.PlaneGeometry();
  6014. * const positionAttribute = geometry.getAttribute( 'position' );
  6015. *
  6016. * const colors = [];
  6017. * for ( let i = 0; i < position.count; i ++ ) {
  6018. * colors.push( 1, 0, 0 );
  6019. * }
  6020. *
  6021. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6022. * ```
  6023. * This new approach is especially interesting when geometry data are generated via
  6024. * compute shaders. The below line converts a storage buffer into an attribute node.
  6025. * ```js
  6026. * material.positionNode = positionBuffer.toAttribute();
  6027. * ```
  6028. * @augments InputNode
  6029. */
  6030. class BufferAttributeNode extends InputNode {
  6031. static get type() {
  6032. return 'BufferAttributeNode';
  6033. }
  6034. /**
  6035. * Constructs a new buffer attribute node.
  6036. *
  6037. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6038. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6039. * @param {number} [bufferStride=0] - The buffer stride.
  6040. * @param {number} [bufferOffset=0] - The buffer offset.
  6041. */
  6042. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6043. super( value, bufferType );
  6044. /**
  6045. * This flag can be used for type testing.
  6046. *
  6047. * @type {boolean}
  6048. * @readonly
  6049. * @default true
  6050. */
  6051. this.isBufferNode = true;
  6052. /**
  6053. * The buffer type (e.g. `'vec3'`).
  6054. *
  6055. * @type {?string}
  6056. * @default null
  6057. */
  6058. this.bufferType = bufferType;
  6059. /**
  6060. * The buffer stride.
  6061. *
  6062. * @type {number}
  6063. * @default 0
  6064. */
  6065. this.bufferStride = bufferStride;
  6066. /**
  6067. * The buffer offset.
  6068. *
  6069. * @type {number}
  6070. * @default 0
  6071. */
  6072. this.bufferOffset = bufferOffset;
  6073. /**
  6074. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6075. * if you are planning to update the attribute data per frame.
  6076. *
  6077. * @type {number}
  6078. * @default StaticDrawUsage
  6079. */
  6080. this.usage = StaticDrawUsage;
  6081. /**
  6082. * Whether the attribute is instanced or not.
  6083. *
  6084. * @type {boolean}
  6085. * @default false
  6086. */
  6087. this.instanced = false;
  6088. /**
  6089. * A reference to the buffer attribute.
  6090. *
  6091. * @type {?BufferAttribute}
  6092. * @default null
  6093. */
  6094. this.attribute = null;
  6095. /**
  6096. * `BufferAttributeNode` sets this property to `true` by default.
  6097. *
  6098. * @type {boolean}
  6099. * @default true
  6100. */
  6101. this.global = true;
  6102. if ( value && value.isBufferAttribute === true ) {
  6103. this.attribute = value;
  6104. this.usage = value.usage;
  6105. this.instanced = value.isInstancedBufferAttribute;
  6106. }
  6107. }
  6108. /**
  6109. * This method is overwritten since the attribute data might be shared
  6110. * and thus the hash should be shared as well.
  6111. *
  6112. * @param {NodeBuilder} builder - The current node builder.
  6113. * @return {string} The hash.
  6114. */
  6115. getHash( builder ) {
  6116. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6117. let bufferData = builder.globalCache.getData( this.value );
  6118. if ( bufferData === undefined ) {
  6119. bufferData = {
  6120. node: this
  6121. };
  6122. builder.globalCache.setData( this.value, bufferData );
  6123. }
  6124. return bufferData.node.uuid;
  6125. }
  6126. return this.uuid;
  6127. }
  6128. /**
  6129. * This method is overwritten since the node type is inferred from
  6130. * the buffer attribute.
  6131. *
  6132. * @param {NodeBuilder} builder - The current node builder.
  6133. * @return {string} The node type.
  6134. */
  6135. getNodeType( builder ) {
  6136. if ( this.bufferType === null ) {
  6137. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6138. }
  6139. return this.bufferType;
  6140. }
  6141. /**
  6142. * Depending on which value was passed to the node, `setup()` behaves
  6143. * differently. If no instance of `BufferAttribute` was passed, the method
  6144. * creates an internal attribute and configures it respectively.
  6145. *
  6146. * @param {NodeBuilder} builder - The current node builder.
  6147. */
  6148. setup( builder ) {
  6149. if ( this.attribute !== null ) return;
  6150. const type = this.getNodeType( builder );
  6151. const array = this.value;
  6152. const itemSize = builder.getTypeLength( type );
  6153. const stride = this.bufferStride || itemSize;
  6154. const offset = this.bufferOffset;
  6155. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6156. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6157. buffer.setUsage( this.usage );
  6158. this.attribute = bufferAttribute;
  6159. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6160. }
  6161. /**
  6162. * Generates the code snippet of the buffer attribute node.
  6163. *
  6164. * @param {NodeBuilder} builder - The current node builder.
  6165. * @return {string} The generated code snippet.
  6166. */
  6167. generate( builder ) {
  6168. const nodeType = this.getNodeType( builder );
  6169. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6170. const propertyName = builder.getPropertyName( nodeAttribute );
  6171. let output = null;
  6172. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6173. this.name = propertyName;
  6174. output = propertyName;
  6175. } else {
  6176. const nodeVarying = varying( this );
  6177. output = nodeVarying.build( builder, nodeType );
  6178. }
  6179. return output;
  6180. }
  6181. /**
  6182. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6183. *
  6184. * @param {NodeBuilder} builder - The current node builder.
  6185. * @return {string} The input type.
  6186. */
  6187. getInputType( /*builder*/ ) {
  6188. return 'bufferAttribute';
  6189. }
  6190. /**
  6191. * Sets the `usage` property to the given value.
  6192. *
  6193. * @param {number} value - The usage to set.
  6194. * @return {BufferAttributeNode} A reference to this node.
  6195. */
  6196. setUsage( value ) {
  6197. this.usage = value;
  6198. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6199. this.attribute.usage = value;
  6200. }
  6201. return this;
  6202. }
  6203. /**
  6204. * Sets the `instanced` property to the given value.
  6205. *
  6206. * @param {boolean} value - The value to set.
  6207. * @return {BufferAttributeNode} A reference to this node.
  6208. */
  6209. setInstanced( value ) {
  6210. this.instanced = value;
  6211. return this;
  6212. }
  6213. }
  6214. /**
  6215. * TSL function for creating a buffer attribute node.
  6216. *
  6217. * @tsl
  6218. * @function
  6219. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6220. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6221. * @param {number} [stride=0] - The buffer stride.
  6222. * @param {number} [offset=0] - The buffer offset.
  6223. * @returns {BufferAttributeNode}
  6224. */
  6225. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6226. /**
  6227. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6228. * Use this function if attribute data are updated per frame.
  6229. *
  6230. * @tsl
  6231. * @function
  6232. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6233. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6234. * @param {number} [stride=0] - The buffer stride.
  6235. * @param {number} [offset=0] - The buffer offset.
  6236. * @returns {BufferAttributeNode}
  6237. */
  6238. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6239. /**
  6240. * TSL function for creating a buffer attribute node but with enabled instancing
  6241. *
  6242. * @tsl
  6243. * @function
  6244. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6245. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6246. * @param {number} [stride=0] - The buffer stride.
  6247. * @param {number} [offset=0] - The buffer offset.
  6248. * @returns {BufferAttributeNode}
  6249. */
  6250. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6251. /**
  6252. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6253. *
  6254. * @tsl
  6255. * @function
  6256. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6257. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6258. * @param {number} [stride=0] - The buffer stride.
  6259. * @param {number} [offset=0] - The buffer offset.
  6260. * @returns {BufferAttributeNode}
  6261. */
  6262. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6263. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6264. /**
  6265. * TODO
  6266. *
  6267. * @augments Node
  6268. */
  6269. class ComputeNode extends Node {
  6270. static get type() {
  6271. return 'ComputeNode';
  6272. }
  6273. /**
  6274. * Constructs a new compute node.
  6275. *
  6276. * @param {Node} computeNode - TODO
  6277. * @param {number} count - TODO.
  6278. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6279. */
  6280. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  6281. super( 'void' );
  6282. /**
  6283. * This flag can be used for type testing.
  6284. *
  6285. * @type {boolean}
  6286. * @readonly
  6287. * @default true
  6288. */
  6289. this.isComputeNode = true;
  6290. /**
  6291. * TODO
  6292. *
  6293. * @type {Node}
  6294. */
  6295. this.computeNode = computeNode;
  6296. /**
  6297. * TODO
  6298. *
  6299. * @type {number}
  6300. */
  6301. this.count = count;
  6302. /**
  6303. * TODO
  6304. *
  6305. * @type {Array<number>}
  6306. * @default [64]
  6307. */
  6308. this.workgroupSize = workgroupSize;
  6309. /**
  6310. * TODO
  6311. *
  6312. * @type {number}
  6313. */
  6314. this.dispatchCount = 0;
  6315. /**
  6316. * TODO
  6317. *
  6318. * @type {number}
  6319. */
  6320. this.version = 1;
  6321. /**
  6322. * The name or label of the uniform.
  6323. *
  6324. * @type {string}
  6325. * @default ''
  6326. */
  6327. this.name = '';
  6328. /**
  6329. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6330. * is executed once per object by default.
  6331. *
  6332. * @type {string}
  6333. * @default 'object'
  6334. */
  6335. this.updateBeforeType = NodeUpdateType.OBJECT;
  6336. /**
  6337. * TODO
  6338. *
  6339. * @type {?Function}
  6340. */
  6341. this.onInitFunction = null;
  6342. this.updateDispatchCount();
  6343. }
  6344. /**
  6345. * Executes the `dispose` event for this node.
  6346. */
  6347. dispose() {
  6348. this.dispatchEvent( { type: 'dispose' } );
  6349. }
  6350. /**
  6351. * Sets the {@link ComputeNode#name} property.
  6352. *
  6353. * @param {string} name - The name of the uniform.
  6354. * @return {ComputeNode} A reference to this node.
  6355. */
  6356. label( name ) {
  6357. this.name = name;
  6358. return this;
  6359. }
  6360. /**
  6361. * TODO
  6362. */
  6363. updateDispatchCount() {
  6364. const { count, workgroupSize } = this;
  6365. let size = workgroupSize[ 0 ];
  6366. for ( let i = 1; i < workgroupSize.length; i ++ )
  6367. size *= workgroupSize[ i ];
  6368. this.dispatchCount = Math.ceil( count / size );
  6369. }
  6370. /**
  6371. * TODO
  6372. *
  6373. * @param {Function} callback - TODO.
  6374. * @return {ComputeNode} A reference to this node.
  6375. */
  6376. onInit( callback ) {
  6377. this.onInitFunction = callback;
  6378. return this;
  6379. }
  6380. /**
  6381. * The method execute the compute for this node.
  6382. *
  6383. * @param {NodeFrame} frame - A reference to the current node frame.
  6384. */
  6385. updateBefore( { renderer } ) {
  6386. renderer.compute( this );
  6387. }
  6388. setup( builder ) {
  6389. const result = this.computeNode.build( builder );
  6390. if ( result ) {
  6391. const properties = builder.getNodeProperties( this );
  6392. properties.outputComputeNode = result.outputNode;
  6393. result.outputNode = null;
  6394. }
  6395. return result;
  6396. }
  6397. generate( builder, output ) {
  6398. const { shaderStage } = builder;
  6399. if ( shaderStage === 'compute' ) {
  6400. const snippet = this.computeNode.build( builder, 'void' );
  6401. if ( snippet !== '' ) {
  6402. builder.addLineFlowCode( snippet, this );
  6403. }
  6404. } else {
  6405. const properties = builder.getNodeProperties( this );
  6406. const outputComputeNode = properties.outputComputeNode;
  6407. if ( outputComputeNode ) {
  6408. return outputComputeNode.build( builder, output );
  6409. }
  6410. }
  6411. }
  6412. }
  6413. /**
  6414. * TSL function for creating a compute node.
  6415. *
  6416. * @tsl
  6417. * @function
  6418. * @param {Node} node - TODO
  6419. * @param {number} count - TODO.
  6420. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6421. * @returns {AtomicFunctionNode}
  6422. */
  6423. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  6424. addMethodChaining( 'compute', compute );
  6425. /**
  6426. * This node can be used as a cache management component for another node.
  6427. * Caching is in general used by default in {@link NodeBuilder} but this node
  6428. * allows the usage of a shared parent cache during the build process.
  6429. *
  6430. * @augments Node
  6431. */
  6432. class CacheNode extends Node {
  6433. static get type() {
  6434. return 'CacheNode';
  6435. }
  6436. /**
  6437. * Constructs a new cache node.
  6438. *
  6439. * @param {Node} node - The node that should be cached.
  6440. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6441. */
  6442. constructor( node, parent = true ) {
  6443. super();
  6444. /**
  6445. * The node that should be cached.
  6446. *
  6447. * @type {Node}
  6448. */
  6449. this.node = node;
  6450. /**
  6451. * Whether this node refers to a shared parent cache or not.
  6452. *
  6453. * @type {boolean}
  6454. * @default true
  6455. */
  6456. this.parent = parent;
  6457. /**
  6458. * This flag can be used for type testing.
  6459. *
  6460. * @type {boolean}
  6461. * @readonly
  6462. * @default true
  6463. */
  6464. this.isCacheNode = true;
  6465. }
  6466. getNodeType( builder ) {
  6467. const previousCache = builder.getCache();
  6468. const cache = builder.getCacheFromNode( this, this.parent );
  6469. builder.setCache( cache );
  6470. const nodeType = this.node.getNodeType( builder );
  6471. builder.setCache( previousCache );
  6472. return nodeType;
  6473. }
  6474. build( builder, ...params ) {
  6475. const previousCache = builder.getCache();
  6476. const cache = builder.getCacheFromNode( this, this.parent );
  6477. builder.setCache( cache );
  6478. const data = this.node.build( builder, ...params );
  6479. builder.setCache( previousCache );
  6480. return data;
  6481. }
  6482. }
  6483. /**
  6484. * TSL function for creating a cache node.
  6485. *
  6486. * @tsl
  6487. * @function
  6488. * @param {Node} node - The node that should be cached.
  6489. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  6490. * @returns {CacheNode}
  6491. */
  6492. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6493. /**
  6494. * Assigns a namespace to the given node by updating its context.
  6495. *
  6496. * Important for TSL functions that use `.once( namespace )` to ensure that the namespace will run twice,
  6497. * once when the node is build in the specific namespace and once when the node is built in the others namespace.
  6498. *
  6499. * This is useful for nodes like `positionWorld` that need to be re-updated if used in `material.positionNode` and outside of it in the same material.
  6500. *
  6501. * @param {Object} node - The node to which the namespace will be assigned.
  6502. * @param {string} namespace - The namespace to be assigned to the node.
  6503. * @returns {Object} The updated node with the new namespace in its context.
  6504. */
  6505. const namespace = ( node, namespace ) => node.context( { namespace } );
  6506. addMethodChaining( 'cache', cache );
  6507. /**
  6508. * The class generates the code of a given node but returns another node in the output.
  6509. * This can be used to call a method or node that does not return a value, i.e.
  6510. * type `void` on an input where returning a value is required. Example:
  6511. *
  6512. * ```js
  6513. * material.colorNode = myColor.bypass( runVoidFn() )
  6514. *```
  6515. *
  6516. * @augments Node
  6517. */
  6518. class BypassNode extends Node {
  6519. static get type() {
  6520. return 'BypassNode';
  6521. }
  6522. /**
  6523. * Constructs a new bypass node.
  6524. *
  6525. * @param {Node} outputNode - The output node.
  6526. * @param {Node} callNode - The call node.
  6527. */
  6528. constructor( outputNode, callNode ) {
  6529. super();
  6530. /**
  6531. * This flag can be used for type testing.
  6532. *
  6533. * @type {boolean}
  6534. * @readonly
  6535. * @default true
  6536. */
  6537. this.isBypassNode = true;
  6538. /**
  6539. * The output node.
  6540. *
  6541. * @type {Node}
  6542. */
  6543. this.outputNode = outputNode;
  6544. /**
  6545. * The call node.
  6546. *
  6547. * @type {Node}
  6548. */
  6549. this.callNode = callNode;
  6550. }
  6551. getNodeType( builder ) {
  6552. return this.outputNode.getNodeType( builder );
  6553. }
  6554. generate( builder ) {
  6555. const snippet = this.callNode.build( builder, 'void' );
  6556. if ( snippet !== '' ) {
  6557. builder.addLineFlowCode( snippet, this );
  6558. }
  6559. return this.outputNode.build( builder );
  6560. }
  6561. }
  6562. /**
  6563. * TSL function for creating a bypass node.
  6564. *
  6565. * @tsl
  6566. * @function
  6567. * @param {Node} outputNode - The output node.
  6568. * @param {Node} callNode - The call node.
  6569. * @returns {BypassNode}
  6570. */
  6571. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  6572. addMethodChaining( 'bypass', bypass );
  6573. /**
  6574. * This node allows to remap a node value from one range into another. E.g a value of
  6575. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6576. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6577. *
  6578. * @augments Node
  6579. */
  6580. class RemapNode extends Node {
  6581. static get type() {
  6582. return 'RemapNode';
  6583. }
  6584. /**
  6585. * Constructs a new remap node.
  6586. *
  6587. * @param {Node} node - The node that should be remapped.
  6588. * @param {Node} inLowNode - The source or current lower bound of the range.
  6589. * @param {Node} inHighNode - The source or current upper bound of the range.
  6590. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6591. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6592. */
  6593. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  6594. super();
  6595. /**
  6596. * The node that should be remapped.
  6597. *
  6598. * @type {Node}
  6599. */
  6600. this.node = node;
  6601. /**
  6602. * The source or current lower bound of the range.
  6603. *
  6604. * @type {Node}
  6605. */
  6606. this.inLowNode = inLowNode;
  6607. /**
  6608. * The source or current upper bound of the range.
  6609. *
  6610. * @type {Node}
  6611. */
  6612. this.inHighNode = inHighNode;
  6613. /**
  6614. * The target lower bound of the range.
  6615. *
  6616. * @type {Node}
  6617. * @default float(0)
  6618. */
  6619. this.outLowNode = outLowNode;
  6620. /**
  6621. * The target upper bound of the range.
  6622. *
  6623. * @type {Node}
  6624. * @default float(1)
  6625. */
  6626. this.outHighNode = outHighNode;
  6627. /**
  6628. * Whether the node value should be clamped before
  6629. * remapping it to the target range.
  6630. *
  6631. * @type {boolean}
  6632. * @default true
  6633. */
  6634. this.doClamp = true;
  6635. }
  6636. setup() {
  6637. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6638. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6639. if ( doClamp === true ) t = t.clamp();
  6640. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6641. }
  6642. }
  6643. /**
  6644. * TSL function for creating a remap node.
  6645. *
  6646. * @tsl
  6647. * @function
  6648. * @param {Node} node - The node that should be remapped.
  6649. * @param {Node} inLowNode - The source or current lower bound of the range.
  6650. * @param {Node} inHighNode - The source or current upper bound of the range.
  6651. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6652. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6653. * @returns {RemapNode}
  6654. */
  6655. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  6656. /**
  6657. * TSL function for creating a remap node, but with enabled clamping.
  6658. *
  6659. * @tsl
  6660. * @function
  6661. * @param {Node} node - The node that should be remapped.
  6662. * @param {Node} inLowNode - The source or current lower bound of the range.
  6663. * @param {Node} inHighNode - The source or current upper bound of the range.
  6664. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6665. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6666. * @returns {RemapNode}
  6667. */
  6668. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  6669. addMethodChaining( 'remap', remap );
  6670. addMethodChaining( 'remapClamp', remapClamp );
  6671. /**
  6672. * This class can be used to implement basic expressions in shader code.
  6673. * Basic examples for that are `return`, `continue` or `discard` statements.
  6674. *
  6675. * @augments Node
  6676. */
  6677. class ExpressionNode extends Node {
  6678. static get type() {
  6679. return 'ExpressionNode';
  6680. }
  6681. /**
  6682. * Constructs a new expression node.
  6683. *
  6684. * @param {string} [snippet=''] - The native code snippet.
  6685. * @param {string} [nodeType='void'] - The node type.
  6686. */
  6687. constructor( snippet = '', nodeType = 'void' ) {
  6688. super( nodeType );
  6689. /**
  6690. * The native code snippet.
  6691. *
  6692. * @type {string}
  6693. * @default ''
  6694. */
  6695. this.snippet = snippet;
  6696. }
  6697. generate( builder, output ) {
  6698. const type = this.getNodeType( builder );
  6699. const snippet = this.snippet;
  6700. if ( type === 'void' ) {
  6701. builder.addLineFlowCode( snippet, this );
  6702. } else {
  6703. return builder.format( snippet, type, output );
  6704. }
  6705. }
  6706. }
  6707. /**
  6708. * TSL function for creating an expression node.
  6709. *
  6710. * @tsl
  6711. * @function
  6712. * @param {string} [snippet] - The native code snippet.
  6713. * @param {?string} [nodeType='void'] - The node type.
  6714. * @returns {ExpressionNode}
  6715. */
  6716. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  6717. /**
  6718. * Represents a `discard` shader operation in TSL.
  6719. *
  6720. * @tsl
  6721. * @function
  6722. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6723. * @return {Node} The `discard` expression.
  6724. */
  6725. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  6726. /**
  6727. * Represents a `return` shader operation in TSL.
  6728. *
  6729. * @tsl
  6730. * @function
  6731. * @return {ExpressionNode} The `return` expression.
  6732. */
  6733. const Return = () => expression( 'return' ).toStack();
  6734. addMethodChaining( 'discard', Discard );
  6735. /**
  6736. * Normally, tone mapping and color conversion happens automatically
  6737. * before outputting pixel too the default (screen) framebuffer. In certain
  6738. * post processing setups this happens to late because certain effects
  6739. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  6740. * to apply tone mapping and color space conversion at an arbitrary point
  6741. * in the effect chain.
  6742. *
  6743. * When applying tone mapping and color space conversion manually with this node,
  6744. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  6745. *
  6746. * ```js
  6747. * const postProcessing = new PostProcessing( renderer );
  6748. * postProcessing.outputColorTransform = false;
  6749. *
  6750. * const scenePass = pass( scene, camera );
  6751. * const outputPass = renderOutput( scenePass );
  6752. *
  6753. * postProcessing.outputNode = outputPass;
  6754. * ```
  6755. *
  6756. * @augments TempNode
  6757. */
  6758. class RenderOutputNode extends TempNode {
  6759. static get type() {
  6760. return 'RenderOutputNode';
  6761. }
  6762. /**
  6763. * Constructs a new render output node.
  6764. *
  6765. * @param {Node} colorNode - The color node to process.
  6766. * @param {?number} toneMapping - The tone mapping type.
  6767. * @param {?string} outputColorSpace - The output color space.
  6768. */
  6769. constructor( colorNode, toneMapping, outputColorSpace ) {
  6770. super( 'vec4' );
  6771. /**
  6772. * The color node to process.
  6773. *
  6774. * @type {Node}
  6775. */
  6776. this.colorNode = colorNode;
  6777. /**
  6778. * The tone mapping type.
  6779. *
  6780. * @type {?number}
  6781. */
  6782. this.toneMapping = toneMapping;
  6783. /**
  6784. * The output color space.
  6785. *
  6786. * @type {?string}
  6787. */
  6788. this.outputColorSpace = outputColorSpace;
  6789. /**
  6790. * This flag can be used for type testing.
  6791. *
  6792. * @type {boolean}
  6793. * @readonly
  6794. * @default true
  6795. */
  6796. this.isRenderOutputNode = true;
  6797. }
  6798. setup( { context } ) {
  6799. let outputNode = this.colorNode || context.color;
  6800. // tone mapping
  6801. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6802. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6803. if ( toneMapping !== NoToneMapping ) {
  6804. outputNode = outputNode.toneMapping( toneMapping );
  6805. }
  6806. // working to output color space
  6807. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6808. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6809. }
  6810. return outputNode;
  6811. }
  6812. }
  6813. /**
  6814. * TSL function for creating a posterize node.
  6815. *
  6816. * @tsl
  6817. * @function
  6818. * @param {Node} color - The color node to process.
  6819. * @param {?number} [toneMapping=null] - The tone mapping type.
  6820. * @param {?string} [outputColorSpace=null] - The output color space.
  6821. * @returns {RenderOutputNode}
  6822. */
  6823. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6824. addMethodChaining( 'renderOutput', renderOutput );
  6825. class DebugNode extends TempNode {
  6826. static get type() {
  6827. return 'DebugNode';
  6828. }
  6829. constructor( node, callback = null ) {
  6830. super();
  6831. this.node = node;
  6832. this.callback = callback;
  6833. }
  6834. getNodeType( builder ) {
  6835. return this.node.getNodeType( builder );
  6836. }
  6837. setup( builder ) {
  6838. return this.node.build( builder );
  6839. }
  6840. analyze( builder ) {
  6841. return this.node.build( builder );
  6842. }
  6843. generate( builder ) {
  6844. const callback = this.callback;
  6845. const snippet = this.node.build( builder );
  6846. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  6847. const border = '-'.repeat( title.length );
  6848. let code = '';
  6849. code += '// #' + title + '#\n';
  6850. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  6851. code += '/* ... */ ' + snippet + ' /* ... */\n';
  6852. code += '// #' + border + '#\n';
  6853. if ( callback !== null ) {
  6854. callback( builder, code );
  6855. } else {
  6856. console.log( code );
  6857. }
  6858. return snippet;
  6859. }
  6860. }
  6861. /**
  6862. * TSL function for creating a debug node.
  6863. *
  6864. * @tsl
  6865. * @function
  6866. * @param {Node} node - The node to debug.
  6867. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  6868. * @returns {DebugNode}
  6869. */
  6870. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) );
  6871. addMethodChaining( 'debug', debug );
  6872. // Non-PURE exports list, side-effects are required here.
  6873. // TSL Base Syntax
  6874. function addNodeElement( name/*, nodeElement*/ ) {
  6875. console.warn( 'THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6876. }
  6877. /**
  6878. * Base class for representing shader attributes as nodes.
  6879. *
  6880. * @augments Node
  6881. */
  6882. class AttributeNode extends Node {
  6883. static get type() {
  6884. return 'AttributeNode';
  6885. }
  6886. /**
  6887. * Constructs a new attribute node.
  6888. *
  6889. * @param {string} attributeName - The name of the attribute.
  6890. * @param {?string} nodeType - The node type.
  6891. */
  6892. constructor( attributeName, nodeType = null ) {
  6893. super( nodeType );
  6894. /**
  6895. * `AttributeNode` sets this property to `true` by default.
  6896. *
  6897. * @type {boolean}
  6898. * @default true
  6899. */
  6900. this.global = true;
  6901. this._attributeName = attributeName;
  6902. }
  6903. getHash( builder ) {
  6904. return this.getAttributeName( builder );
  6905. }
  6906. getNodeType( builder ) {
  6907. let nodeType = this.nodeType;
  6908. if ( nodeType === null ) {
  6909. const attributeName = this.getAttributeName( builder );
  6910. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6911. const attribute = builder.geometry.getAttribute( attributeName );
  6912. nodeType = builder.getTypeFromAttribute( attribute );
  6913. } else {
  6914. nodeType = 'float';
  6915. }
  6916. }
  6917. return nodeType;
  6918. }
  6919. /**
  6920. * Sets the attribute name to the given value. The method can be
  6921. * overwritten in derived classes if the final name must be computed
  6922. * analytically.
  6923. *
  6924. * @param {string} attributeName - The name of the attribute.
  6925. * @return {AttributeNode} A reference to this node.
  6926. */
  6927. setAttributeName( attributeName ) {
  6928. this._attributeName = attributeName;
  6929. return this;
  6930. }
  6931. /**
  6932. * Returns the attribute name of this node. The method can be
  6933. * overwritten in derived classes if the final name must be computed
  6934. * analytically.
  6935. *
  6936. * @param {NodeBuilder} builder - The current node builder.
  6937. * @return {string} The attribute name.
  6938. */
  6939. getAttributeName( /*builder*/ ) {
  6940. return this._attributeName;
  6941. }
  6942. generate( builder ) {
  6943. const attributeName = this.getAttributeName( builder );
  6944. const nodeType = this.getNodeType( builder );
  6945. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6946. if ( geometryAttribute === true ) {
  6947. const attribute = builder.geometry.getAttribute( attributeName );
  6948. const attributeType = builder.getTypeFromAttribute( attribute );
  6949. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6950. if ( builder.shaderStage === 'vertex' ) {
  6951. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6952. } else {
  6953. const nodeVarying = varying( this );
  6954. return nodeVarying.build( builder, nodeType );
  6955. }
  6956. } else {
  6957. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6958. return builder.generateConst( nodeType );
  6959. }
  6960. }
  6961. serialize( data ) {
  6962. super.serialize( data );
  6963. data.global = this.global;
  6964. data._attributeName = this._attributeName;
  6965. }
  6966. deserialize( data ) {
  6967. super.deserialize( data );
  6968. this.global = data.global;
  6969. this._attributeName = data._attributeName;
  6970. }
  6971. }
  6972. /**
  6973. * TSL function for creating an attribute node.
  6974. *
  6975. * @tsl
  6976. * @function
  6977. * @param {string} name - The name of the attribute.
  6978. * @param {?string} [nodeType=null] - The node type.
  6979. * @returns {AttributeNode}
  6980. */
  6981. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  6982. /**
  6983. * TSL function for creating an uv attribute node with the given index.
  6984. *
  6985. * @tsl
  6986. * @function
  6987. * @param {number} [index=0] - The uv index.
  6988. * @return {AttributeNode<vec2>} The uv attribute node.
  6989. */
  6990. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6991. /**
  6992. * A node that represents the dimensions of a texture. The texture size is
  6993. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6994. * or `textureSize()`.
  6995. *
  6996. * @augments Node
  6997. */
  6998. class TextureSizeNode extends Node {
  6999. static get type() {
  7000. return 'TextureSizeNode';
  7001. }
  7002. /**
  7003. * Constructs a new texture size node.
  7004. *
  7005. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7006. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7007. */
  7008. constructor( textureNode, levelNode = null ) {
  7009. super( 'uvec2' );
  7010. /**
  7011. * This flag can be used for type testing.
  7012. *
  7013. * @type {boolean}
  7014. * @readonly
  7015. * @default true
  7016. */
  7017. this.isTextureSizeNode = true;
  7018. /**
  7019. * A texture node which size should be retrieved.
  7020. *
  7021. * @type {TextureNode}
  7022. */
  7023. this.textureNode = textureNode;
  7024. /**
  7025. * A level node which defines the requested mip.
  7026. *
  7027. * @type {Node<int>}
  7028. * @default null
  7029. */
  7030. this.levelNode = levelNode;
  7031. }
  7032. generate( builder, output ) {
  7033. const textureProperty = this.textureNode.build( builder, 'property' );
  7034. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7035. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7036. }
  7037. }
  7038. /**
  7039. * TSL function for creating a texture size node.
  7040. *
  7041. * @tsl
  7042. * @function
  7043. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7044. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7045. * @returns {TextureSizeNode}
  7046. */
  7047. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7048. /**
  7049. * A special type of uniform node that computes the
  7050. * maximum mipmap level for a given texture node.
  7051. *
  7052. * ```js
  7053. * const level = maxMipLevel( textureNode );
  7054. * ```
  7055. *
  7056. * @augments UniformNode
  7057. */
  7058. class MaxMipLevelNode extends UniformNode {
  7059. static get type() {
  7060. return 'MaxMipLevelNode';
  7061. }
  7062. /**
  7063. * Constructs a new max mip level node.
  7064. *
  7065. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7066. */
  7067. constructor( textureNode ) {
  7068. super( 0 );
  7069. /**
  7070. * The texture node to compute the max mip level for.
  7071. *
  7072. * @private
  7073. * @type {TextureNode}
  7074. */
  7075. this._textureNode = textureNode;
  7076. /**
  7077. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7078. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7079. *
  7080. * @type {string}
  7081. * @default 'frame'
  7082. */
  7083. this.updateType = NodeUpdateType.FRAME;
  7084. }
  7085. /**
  7086. * The texture node to compute the max mip level for.
  7087. *
  7088. * @readonly
  7089. * @type {TextureNode}
  7090. */
  7091. get textureNode() {
  7092. return this._textureNode;
  7093. }
  7094. /**
  7095. * The texture.
  7096. *
  7097. * @readonly
  7098. * @type {Texture}
  7099. */
  7100. get texture() {
  7101. return this._textureNode.value;
  7102. }
  7103. update() {
  7104. const texture = this.texture;
  7105. const images = texture.images;
  7106. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7107. if ( image && image.width !== undefined ) {
  7108. const { width, height } = image;
  7109. this.value = Math.log2( Math.max( width, height ) );
  7110. }
  7111. }
  7112. }
  7113. /**
  7114. * TSL function for creating a max mip level node.
  7115. *
  7116. * @tsl
  7117. * @function
  7118. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7119. * @returns {MaxMipLevelNode}
  7120. */
  7121. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7122. /**
  7123. * This type of uniform node represents a 2D texture.
  7124. *
  7125. * @augments UniformNode
  7126. */
  7127. class TextureNode extends UniformNode {
  7128. static get type() {
  7129. return 'TextureNode';
  7130. }
  7131. /**
  7132. * Constructs a new texture node.
  7133. *
  7134. * @param {Texture} value - The texture.
  7135. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7136. * @param {?Node<int>} [levelNode=null] - The level node.
  7137. * @param {?Node<float>} [biasNode=null] - The bias node.
  7138. */
  7139. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7140. super( value );
  7141. /**
  7142. * This flag can be used for type testing.
  7143. *
  7144. * @type {boolean}
  7145. * @readonly
  7146. * @default true
  7147. */
  7148. this.isTextureNode = true;
  7149. /**
  7150. * Represents the texture coordinates.
  7151. *
  7152. * @type {?Node<vec2|vec3>}
  7153. * @default null
  7154. */
  7155. this.uvNode = uvNode;
  7156. /**
  7157. * Represents the mip level that should be selected.
  7158. *
  7159. * @type {?Node<int>}
  7160. * @default null
  7161. */
  7162. this.levelNode = levelNode;
  7163. /**
  7164. * Represents the bias to be applied during level-of-detail computation.
  7165. *
  7166. * @type {?Node<float>}
  7167. * @default null
  7168. */
  7169. this.biasNode = biasNode;
  7170. /**
  7171. * Represents a reference value a texture sample is compared to.
  7172. *
  7173. * @type {?Node<float>}
  7174. * @default null
  7175. */
  7176. this.compareNode = null;
  7177. /**
  7178. * When using texture arrays, the depth node defines the layer to select.
  7179. *
  7180. * @type {?Node<int>}
  7181. * @default null
  7182. */
  7183. this.depthNode = null;
  7184. /**
  7185. * When defined, a texture is sampled using explicit gradients.
  7186. *
  7187. * @type {?Array<Node<vec2>>}
  7188. * @default null
  7189. */
  7190. this.gradNode = null;
  7191. /**
  7192. * Whether texture values should be sampled or fetched.
  7193. *
  7194. * @type {boolean}
  7195. * @default true
  7196. */
  7197. this.sampler = true;
  7198. /**
  7199. * Whether the uv transformation matrix should be
  7200. * automatically updated or not. Use `setUpdateMatrix()`
  7201. * if you want to change the value of the property.
  7202. *
  7203. * @type {boolean}
  7204. * @default false
  7205. */
  7206. this.updateMatrix = false;
  7207. /**
  7208. * By default the `update()` method is not executed. `setUpdateMatrix()`
  7209. * sets the value to `frame` when the uv transformation matrix should
  7210. * automatically be updated.
  7211. *
  7212. * @type {string}
  7213. * @default 'none'
  7214. */
  7215. this.updateType = NodeUpdateType.NONE;
  7216. /**
  7217. * The reference node.
  7218. *
  7219. * @type {?Node}
  7220. * @default null
  7221. */
  7222. this.referenceNode = null;
  7223. /**
  7224. * The texture value is stored in a private property.
  7225. *
  7226. * @private
  7227. * @type {Texture}
  7228. */
  7229. this._value = value;
  7230. /**
  7231. * The uniform node that represents the uv transformation matrix.
  7232. *
  7233. * @private
  7234. * @type {?UniformNode<mat3>}
  7235. */
  7236. this._matrixUniform = null;
  7237. this.setUpdateMatrix( uvNode === null );
  7238. }
  7239. set value( value ) {
  7240. if ( this.referenceNode ) {
  7241. this.referenceNode.value = value;
  7242. } else {
  7243. this._value = value;
  7244. }
  7245. }
  7246. /**
  7247. * The texture value.
  7248. *
  7249. * @type {Texture}
  7250. */
  7251. get value() {
  7252. return this.referenceNode ? this.referenceNode.value : this._value;
  7253. }
  7254. /**
  7255. * Overwritten since the uniform hash is defined by the texture's UUID.
  7256. *
  7257. * @param {NodeBuilder} builder - The current node builder.
  7258. * @return {string} The uniform hash.
  7259. */
  7260. getUniformHash( /*builder*/ ) {
  7261. return this.value.uuid;
  7262. }
  7263. /**
  7264. * Overwritten since the node type is inferred from the texture type.
  7265. *
  7266. * @param {NodeBuilder} builder - The current node builder.
  7267. * @return {string} The node type.
  7268. */
  7269. getNodeType( /*builder*/ ) {
  7270. if ( this.value.isDepthTexture === true ) return 'float';
  7271. if ( this.value.type === UnsignedIntType ) {
  7272. return 'uvec4';
  7273. } else if ( this.value.type === IntType ) {
  7274. return 'ivec4';
  7275. }
  7276. return 'vec4';
  7277. }
  7278. /**
  7279. * Overwrites the default implementation to return a fixed value `'texture'`.
  7280. *
  7281. * @param {NodeBuilder} builder - The current node builder.
  7282. * @return {string} The input type.
  7283. */
  7284. getInputType( /*builder*/ ) {
  7285. return 'texture';
  7286. }
  7287. /**
  7288. * Returns a default uvs based on the current texture's channel.
  7289. *
  7290. * @return {AttributeNode<vec2>} The default uvs.
  7291. */
  7292. getDefaultUV() {
  7293. return uv( this.value.channel );
  7294. }
  7295. /**
  7296. * Overwritten to always return the texture reference of the node.
  7297. *
  7298. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  7299. * @return {Texture} The texture reference.
  7300. */
  7301. updateReference( /*state*/ ) {
  7302. return this.value;
  7303. }
  7304. /**
  7305. * Transforms the given uv node with the texture transformation matrix.
  7306. *
  7307. * @param {Node} uvNode - The uv node to transform.
  7308. * @return {Node} The transformed uv node.
  7309. */
  7310. getTransformedUV( uvNode ) {
  7311. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  7312. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  7313. }
  7314. /**
  7315. * Defines whether the uv transformation matrix should automatically be updated or not.
  7316. *
  7317. * @param {boolean} value - The update toggle.
  7318. * @return {TextureNode} A reference to this node.
  7319. */
  7320. setUpdateMatrix( value ) {
  7321. this.updateMatrix = value;
  7322. this.updateType = value ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  7323. return this;
  7324. }
  7325. /**
  7326. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  7327. * to modify the uv node for correct sampling.
  7328. *
  7329. * @param {NodeBuilder} builder - The current node builder.
  7330. * @param {Node} uvNode - The uv node to setup.
  7331. * @return {Node} The updated uv node.
  7332. */
  7333. setupUV( builder, uvNode ) {
  7334. const texture = this.value;
  7335. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  7336. if ( this.sampler ) {
  7337. uvNode = uvNode.flipY();
  7338. } else {
  7339. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  7340. }
  7341. }
  7342. return uvNode;
  7343. }
  7344. /**
  7345. * Setups texture node by preparing the internal nodes for code generation.
  7346. *
  7347. * @param {NodeBuilder} builder - The current node builder.
  7348. */
  7349. setup( builder ) {
  7350. const properties = builder.getNodeProperties( this );
  7351. properties.referenceNode = this.referenceNode;
  7352. //
  7353. const texture = this.value;
  7354. if ( ! texture || texture.isTexture !== true ) {
  7355. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  7356. }
  7357. //
  7358. let uvNode = this.uvNode;
  7359. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  7360. uvNode = builder.context.getUV( this, builder );
  7361. }
  7362. if ( ! uvNode ) uvNode = this.getDefaultUV();
  7363. if ( this.updateMatrix === true ) {
  7364. uvNode = this.getTransformedUV( uvNode );
  7365. }
  7366. uvNode = this.setupUV( builder, uvNode );
  7367. //
  7368. let levelNode = this.levelNode;
  7369. if ( levelNode === null && builder.context.getTextureLevel ) {
  7370. levelNode = builder.context.getTextureLevel( this );
  7371. }
  7372. //
  7373. properties.uvNode = uvNode;
  7374. properties.levelNode = levelNode;
  7375. properties.biasNode = this.biasNode;
  7376. properties.compareNode = this.compareNode;
  7377. properties.gradNode = this.gradNode;
  7378. properties.depthNode = this.depthNode;
  7379. }
  7380. /**
  7381. * Generates the uv code snippet.
  7382. *
  7383. * @param {NodeBuilder} builder - The current node builder.
  7384. * @param {Node} uvNode - The uv node to generate code for.
  7385. * @return {string} The generated code snippet.
  7386. */
  7387. generateUV( builder, uvNode ) {
  7388. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  7389. }
  7390. /**
  7391. * Generates the snippet for the texture sampling.
  7392. *
  7393. * @param {NodeBuilder} builder - The current node builder.
  7394. * @param {string} textureProperty - The texture property.
  7395. * @param {string} uvSnippet - The uv snippet.
  7396. * @param {?string} levelSnippet - The level snippet.
  7397. * @param {?string} biasSnippet - The bias snippet.
  7398. * @param {?string} depthSnippet - The depth snippet.
  7399. * @param {?string} compareSnippet - The compare snippet.
  7400. * @param {?Array<string>} gradSnippet - The grad snippet.
  7401. * @return {string} The generated code snippet.
  7402. */
  7403. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  7404. const texture = this.value;
  7405. let snippet;
  7406. if ( levelSnippet ) {
  7407. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  7408. } else if ( biasSnippet ) {
  7409. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  7410. } else if ( gradSnippet ) {
  7411. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  7412. } else if ( compareSnippet ) {
  7413. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  7414. } else if ( this.sampler === false ) {
  7415. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  7416. } else {
  7417. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  7418. }
  7419. return snippet;
  7420. }
  7421. /**
  7422. * Generates the code snippet of the texture node.
  7423. *
  7424. * @param {NodeBuilder} builder - The current node builder.
  7425. * @param {string} output - The current output.
  7426. * @return {string} The generated code snippet.
  7427. */
  7428. generate( builder, output ) {
  7429. const texture = this.value;
  7430. const properties = builder.getNodeProperties( this );
  7431. const textureProperty = super.generate( builder, 'property' );
  7432. if ( /^sampler/.test( output ) ) {
  7433. return textureProperty + '_sampler';
  7434. } else if ( builder.isReference( output ) ) {
  7435. return textureProperty;
  7436. } else {
  7437. const nodeData = builder.getDataFromNode( this );
  7438. let propertyName = nodeData.propertyName;
  7439. if ( propertyName === undefined ) {
  7440. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  7441. const uvSnippet = this.generateUV( builder, uvNode );
  7442. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  7443. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  7444. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  7445. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  7446. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  7447. const nodeVar = builder.getVarFromNode( this );
  7448. propertyName = builder.getPropertyName( nodeVar );
  7449. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  7450. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7451. nodeData.snippet = snippet;
  7452. nodeData.propertyName = propertyName;
  7453. }
  7454. let snippet = propertyName;
  7455. const nodeType = this.getNodeType( builder );
  7456. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7457. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7458. }
  7459. return builder.format( snippet, nodeType, output );
  7460. }
  7461. }
  7462. /**
  7463. * Sets the sampler value.
  7464. *
  7465. * @param {boolean} value - The sampler value to set.
  7466. * @return {TextureNode} A reference to this texture node.
  7467. */
  7468. setSampler( value ) {
  7469. this.sampler = value;
  7470. return this;
  7471. }
  7472. /**
  7473. * Returns the sampler value.
  7474. *
  7475. * @return {boolean} The sampler value.
  7476. */
  7477. getSampler() {
  7478. return this.sampler;
  7479. }
  7480. // @TODO: Move to TSL
  7481. /**
  7482. * @function
  7483. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7484. *
  7485. * @param {Node} uvNode - The uv node.
  7486. * @return {TextureNode} A texture node representing the texture sample.
  7487. */
  7488. uv( uvNode ) { // @deprecated, r172
  7489. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7490. return this.sample( uvNode );
  7491. }
  7492. /**
  7493. * Samples the texture with the given uv node.
  7494. *
  7495. * @param {Node} uvNode - The uv node.
  7496. * @return {TextureNode} A texture node representing the texture sample.
  7497. */
  7498. sample( uvNode ) {
  7499. const textureNode = this.clone();
  7500. textureNode.uvNode = nodeObject( uvNode );
  7501. textureNode.referenceNode = this.getSelf();
  7502. return nodeObject( textureNode );
  7503. }
  7504. /**
  7505. * Samples a blurred version of the texture by defining an internal bias.
  7506. *
  7507. * @param {Node<float>} amountNode - How blurred the texture should be.
  7508. * @return {TextureNode} A texture node representing the texture sample.
  7509. */
  7510. blur( amountNode ) {
  7511. const textureNode = this.clone();
  7512. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7513. textureNode.referenceNode = this.getSelf();
  7514. const map = textureNode.value;
  7515. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  7516. console.warn( 'THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  7517. textureNode.biasNode = null;
  7518. }
  7519. return nodeObject( textureNode );
  7520. }
  7521. /**
  7522. * Samples a specific mip of the texture.
  7523. *
  7524. * @param {Node<int>} levelNode - The mip level to sample.
  7525. * @return {TextureNode} A texture node representing the texture sample.
  7526. */
  7527. level( levelNode ) {
  7528. const textureNode = this.clone();
  7529. textureNode.levelNode = nodeObject( levelNode );
  7530. textureNode.referenceNode = this.getSelf();
  7531. return nodeObject( textureNode );
  7532. }
  7533. /**
  7534. * Returns the texture size of the requested level.
  7535. *
  7536. * @param {Node<int>} levelNode - The level to compute the size for.
  7537. * @return {TextureSizeNode} The texture size.
  7538. */
  7539. size( levelNode ) {
  7540. return textureSize( this, levelNode );
  7541. }
  7542. /**
  7543. * Samples the texture with the given bias.
  7544. *
  7545. * @param {Node<float>} biasNode - The bias node.
  7546. * @return {TextureNode} A texture node representing the texture sample.
  7547. */
  7548. bias( biasNode ) {
  7549. const textureNode = this.clone();
  7550. textureNode.biasNode = nodeObject( biasNode );
  7551. textureNode.referenceNode = this.getSelf();
  7552. return nodeObject( textureNode );
  7553. }
  7554. /**
  7555. * Samples the texture by executing a compare operation.
  7556. *
  7557. * @param {Node<float>} compareNode - The node that defines the compare value.
  7558. * @return {TextureNode} A texture node representing the texture sample.
  7559. */
  7560. compare( compareNode ) {
  7561. const textureNode = this.clone();
  7562. textureNode.compareNode = nodeObject( compareNode );
  7563. textureNode.referenceNode = this.getSelf();
  7564. return nodeObject( textureNode );
  7565. }
  7566. /**
  7567. * Samples the texture using an explicit gradient.
  7568. *
  7569. * @param {Node<vec2>} gradNodeX - The gradX node.
  7570. * @param {Node<vec2>} gradNodeY - The gradY node.
  7571. * @return {TextureNode} A texture node representing the texture sample.
  7572. */
  7573. grad( gradNodeX, gradNodeY ) {
  7574. const textureNode = this.clone();
  7575. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  7576. textureNode.referenceNode = this.getSelf();
  7577. return nodeObject( textureNode );
  7578. }
  7579. /**
  7580. * Samples the texture by defining a depth node.
  7581. *
  7582. * @param {Node<int>} depthNode - The depth node.
  7583. * @return {TextureNode} A texture node representing the texture sample.
  7584. */
  7585. depth( depthNode ) {
  7586. const textureNode = this.clone();
  7587. textureNode.depthNode = nodeObject( depthNode );
  7588. textureNode.referenceNode = this.getSelf();
  7589. return nodeObject( textureNode );
  7590. }
  7591. // --
  7592. serialize( data ) {
  7593. super.serialize( data );
  7594. data.value = this.value.toJSON( data.meta ).uuid;
  7595. data.sampler = this.sampler;
  7596. data.updateMatrix = this.updateMatrix;
  7597. data.updateType = this.updateType;
  7598. }
  7599. deserialize( data ) {
  7600. super.deserialize( data );
  7601. this.value = data.meta.textures[ data.value ];
  7602. this.sampler = data.sampler;
  7603. this.updateMatrix = data.updateMatrix;
  7604. this.updateType = data.updateType;
  7605. }
  7606. /**
  7607. * The update is used to implement the update of the uv transformation matrix.
  7608. */
  7609. update() {
  7610. const texture = this.value;
  7611. const matrixUniform = this._matrixUniform;
  7612. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  7613. if ( texture.matrixAutoUpdate === true ) {
  7614. texture.updateMatrix();
  7615. }
  7616. }
  7617. /**
  7618. * Clones the texture node.
  7619. *
  7620. * @return {TextureNode} The cloned texture node.
  7621. */
  7622. clone() {
  7623. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  7624. newNode.sampler = this.sampler;
  7625. newNode.depthNode = this.depthNode;
  7626. newNode.compareNode = this.compareNode;
  7627. newNode.gradNode = this.gradNode;
  7628. return newNode;
  7629. }
  7630. }
  7631. /**
  7632. * TSL function for creating a texture node.
  7633. *
  7634. * @tsl
  7635. * @function
  7636. * @param {Texture} value - The texture.
  7637. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7638. * @param {?Node<int>} [levelNode=null] - The level node.
  7639. * @param {?Node<float>} [biasNode=null] - The bias node.
  7640. * @returns {TextureNode}
  7641. */
  7642. const texture = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 );
  7643. /**
  7644. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7645. *
  7646. * @tsl
  7647. * @function
  7648. * @param {Texture} value - The texture.
  7649. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7650. * @param {?Node<int>} [levelNode=null] - The level node.
  7651. * @param {?Node<float>} [biasNode=null] - The bias node.
  7652. * @returns {TextureNode}
  7653. */
  7654. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  7655. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  7656. /**
  7657. * Converts a texture or texture node to a sampler.
  7658. *
  7659. * @tsl
  7660. * @function
  7661. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7662. * @returns {Node}
  7663. */
  7664. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  7665. /**
  7666. * Converts a texture or texture node to a sampler comparison.
  7667. *
  7668. * @tsl
  7669. * @function
  7670. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7671. * @returns {Node}
  7672. */
  7673. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  7674. /**
  7675. * A special type of uniform node which represents array-like data
  7676. * as uniform buffers. The access usually happens via `element()`
  7677. * which returns an instance of {@link ArrayElementNode}. For example:
  7678. *
  7679. * ```js
  7680. * const bufferNode = buffer( array, 'mat4', count );
  7681. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7682. * ```
  7683. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7684. * since it handles more input types and automatically cares about buffer paddings.
  7685. *
  7686. * @augments UniformNode
  7687. */
  7688. class BufferNode extends UniformNode {
  7689. static get type() {
  7690. return 'BufferNode';
  7691. }
  7692. /**
  7693. * Constructs a new buffer node.
  7694. *
  7695. * @param {Array<number>} value - Array-like buffer data.
  7696. * @param {string} bufferType - The data type of the buffer.
  7697. * @param {number} [bufferCount=0] - The count of buffer elements.
  7698. */
  7699. constructor( value, bufferType, bufferCount = 0 ) {
  7700. super( value, bufferType );
  7701. /**
  7702. * This flag can be used for type testing.
  7703. *
  7704. * @type {boolean}
  7705. * @readonly
  7706. * @default true
  7707. */
  7708. this.isBufferNode = true;
  7709. /**
  7710. * The data type of the buffer.
  7711. *
  7712. * @type {string}
  7713. */
  7714. this.bufferType = bufferType;
  7715. /**
  7716. * The uniform node that holds the value of the reference node.
  7717. *
  7718. * @type {number}
  7719. * @default 0
  7720. */
  7721. this.bufferCount = bufferCount;
  7722. }
  7723. /**
  7724. * The data type of the buffer elements.
  7725. *
  7726. * @param {NodeBuilder} builder - The current node builder.
  7727. * @return {string} The element type.
  7728. */
  7729. getElementType( builder ) {
  7730. return this.getNodeType( builder );
  7731. }
  7732. /**
  7733. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7734. *
  7735. * @param {NodeBuilder} builder - The current node builder.
  7736. * @return {string} The input type.
  7737. */
  7738. getInputType( /*builder*/ ) {
  7739. return 'buffer';
  7740. }
  7741. }
  7742. /**
  7743. * TSL function for creating a buffer node.
  7744. *
  7745. * @tsl
  7746. * @function
  7747. * @param {Array} value - Array-like buffer data.
  7748. * @param {string} type - The data type of a buffer element.
  7749. * @param {number} count - The count of buffer elements.
  7750. * @returns {BufferNode}
  7751. */
  7752. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7753. /**
  7754. * Represents the element access on uniform array nodes.
  7755. *
  7756. * @augments ArrayElementNode
  7757. */
  7758. class UniformArrayElementNode extends ArrayElementNode {
  7759. static get type() {
  7760. return 'UniformArrayElementNode';
  7761. }
  7762. /**
  7763. * Constructs a new buffer node.
  7764. *
  7765. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7766. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7767. */
  7768. constructor( uniformArrayNode, indexNode ) {
  7769. super( uniformArrayNode, indexNode );
  7770. /**
  7771. * This flag can be used for type testing.
  7772. *
  7773. * @type {boolean}
  7774. * @readonly
  7775. * @default true
  7776. */
  7777. this.isArrayBufferElementNode = true;
  7778. }
  7779. generate( builder ) {
  7780. const snippet = super.generate( builder );
  7781. const type = this.getNodeType();
  7782. const paddedType = this.node.getPaddedType();
  7783. return builder.format( snippet, paddedType, type );
  7784. }
  7785. }
  7786. /**
  7787. * Similar to {@link BufferNode} this module represents array-like data as
  7788. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  7789. * data types in the array (e.g `three.js` primitives) and automatically
  7790. * manage buffer padding. It should be the first choice when working with
  7791. * uniforms buffers.
  7792. * ```js
  7793. * const tintColors = uniformArray( [
  7794. * new Color( 1, 0, 0 ),
  7795. * new Color( 0, 1, 0 ),
  7796. * new Color( 0, 0, 1 )
  7797. * ], 'color' );
  7798. *
  7799. * const redColor = tintColors.element( 0 );
  7800. *
  7801. * @augments BufferNode
  7802. */
  7803. class UniformArrayNode extends BufferNode {
  7804. static get type() {
  7805. return 'UniformArrayNode';
  7806. }
  7807. /**
  7808. * Constructs a new uniform array node.
  7809. *
  7810. * @param {Array<any>} value - Array holding the buffer data.
  7811. * @param {?string} [elementType=null] - The data type of a buffer element.
  7812. */
  7813. constructor( value, elementType = null ) {
  7814. super( null );
  7815. /**
  7816. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  7817. * hold number primitives as well as three.js objects like vectors, matrices
  7818. * or colors.
  7819. *
  7820. * @type {Array<any>}
  7821. */
  7822. this.array = value;
  7823. /**
  7824. * The data type of an array element.
  7825. *
  7826. * @type {string}
  7827. */
  7828. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7829. /**
  7830. * The padded type. Uniform buffers must conform to a certain buffer layout
  7831. * so a separate type is computed to ensure correct buffer size.
  7832. *
  7833. * @type {string}
  7834. */
  7835. this.paddedType = this.getPaddedType();
  7836. /**
  7837. * Overwritten since uniform array nodes are updated per render.
  7838. *
  7839. * @type {string}
  7840. * @default 'render'
  7841. */
  7842. this.updateType = NodeUpdateType.RENDER;
  7843. /**
  7844. * This flag can be used for type testing.
  7845. *
  7846. * @type {boolean}
  7847. * @readonly
  7848. * @default true
  7849. */
  7850. this.isArrayBufferNode = true;
  7851. }
  7852. /**
  7853. * This method is overwritten since the node type is inferred from the
  7854. * {@link UniformArrayNode#paddedType}.
  7855. *
  7856. * @param {NodeBuilder} builder - The current node builder.
  7857. * @return {string} The node type.
  7858. */
  7859. getNodeType( /*builder*/ ) {
  7860. return this.paddedType;
  7861. }
  7862. /**
  7863. * The data type of the array elements.
  7864. *
  7865. * @param {NodeBuilder} builder - The current node builder.
  7866. * @return {string} The element type.
  7867. */
  7868. getElementType() {
  7869. return this.elementType;
  7870. }
  7871. /**
  7872. * Returns the padded type based on the element type.
  7873. *
  7874. * @return {string} The padded type.
  7875. */
  7876. getPaddedType() {
  7877. const elementType = this.elementType;
  7878. let paddedType = 'vec4';
  7879. if ( elementType === 'mat2' ) {
  7880. paddedType = 'mat2';
  7881. } else if ( /mat/.test( elementType ) === true ) {
  7882. paddedType = 'mat4';
  7883. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7884. paddedType = 'ivec4';
  7885. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7886. paddedType = 'uvec4';
  7887. }
  7888. return paddedType;
  7889. }
  7890. /**
  7891. * The update makes sure to correctly transfer the data from the (complex) objects
  7892. * in the array to the internal, correctly padded value buffer.
  7893. *
  7894. * @param {NodeFrame} frame - A reference to the current node frame.
  7895. */
  7896. update( /*frame*/ ) {
  7897. const { array, value } = this;
  7898. const elementType = this.elementType;
  7899. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7900. for ( let i = 0; i < array.length; i ++ ) {
  7901. const index = i * 4;
  7902. value[ index ] = array[ i ];
  7903. }
  7904. } else if ( elementType === 'color' ) {
  7905. for ( let i = 0; i < array.length; i ++ ) {
  7906. const index = i * 4;
  7907. const vector = array[ i ];
  7908. value[ index ] = vector.r;
  7909. value[ index + 1 ] = vector.g;
  7910. value[ index + 2 ] = vector.b || 0;
  7911. //value[ index + 3 ] = vector.a || 0;
  7912. }
  7913. } else if ( elementType === 'mat2' ) {
  7914. for ( let i = 0; i < array.length; i ++ ) {
  7915. const index = i * 4;
  7916. const matrix = array[ i ];
  7917. value[ index ] = matrix.elements[ 0 ];
  7918. value[ index + 1 ] = matrix.elements[ 1 ];
  7919. value[ index + 2 ] = matrix.elements[ 2 ];
  7920. value[ index + 3 ] = matrix.elements[ 3 ];
  7921. }
  7922. } else if ( elementType === 'mat3' ) {
  7923. for ( let i = 0; i < array.length; i ++ ) {
  7924. const index = i * 16;
  7925. const matrix = array[ i ];
  7926. value[ index ] = matrix.elements[ 0 ];
  7927. value[ index + 1 ] = matrix.elements[ 1 ];
  7928. value[ index + 2 ] = matrix.elements[ 2 ];
  7929. value[ index + 4 ] = matrix.elements[ 3 ];
  7930. value[ index + 5 ] = matrix.elements[ 4 ];
  7931. value[ index + 6 ] = matrix.elements[ 5 ];
  7932. value[ index + 8 ] = matrix.elements[ 6 ];
  7933. value[ index + 9 ] = matrix.elements[ 7 ];
  7934. value[ index + 10 ] = matrix.elements[ 8 ];
  7935. value[ index + 15 ] = 1;
  7936. }
  7937. } else if ( elementType === 'mat4' ) {
  7938. for ( let i = 0; i < array.length; i ++ ) {
  7939. const index = i * 16;
  7940. const matrix = array[ i ];
  7941. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7942. value[ index + i ] = matrix.elements[ i ];
  7943. }
  7944. }
  7945. } else {
  7946. for ( let i = 0; i < array.length; i ++ ) {
  7947. const index = i * 4;
  7948. const vector = array[ i ];
  7949. value[ index ] = vector.x;
  7950. value[ index + 1 ] = vector.y;
  7951. value[ index + 2 ] = vector.z || 0;
  7952. value[ index + 3 ] = vector.w || 0;
  7953. }
  7954. }
  7955. }
  7956. /**
  7957. * Implement the value buffer creation based on the array data.
  7958. *
  7959. * @param {NodeBuilder} builder - A reference to the current node builder.
  7960. * @return {null}
  7961. */
  7962. setup( builder ) {
  7963. const length = this.array.length;
  7964. const elementType = this.elementType;
  7965. let arrayType = Float32Array;
  7966. const paddedType = this.paddedType;
  7967. const paddedElementLength = builder.getTypeLength( paddedType );
  7968. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7969. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7970. this.value = new arrayType( length * paddedElementLength );
  7971. this.bufferCount = length;
  7972. this.bufferType = paddedType;
  7973. return super.setup( builder );
  7974. }
  7975. /**
  7976. * Overwrites the default `element()` method to provide element access
  7977. * based on {@link UniformArrayNode}.
  7978. *
  7979. * @param {IndexNode} indexNode - The index node.
  7980. * @return {UniformArrayElementNode}
  7981. */
  7982. element( indexNode ) {
  7983. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7984. }
  7985. }
  7986. /**
  7987. * TSL function for creating an uniform array node.
  7988. *
  7989. * @tsl
  7990. * @function
  7991. * @param {Array<any>} values - Array-like data.
  7992. * @param {?string} [nodeType] - The data type of the array elements.
  7993. * @returns {UniformArrayNode}
  7994. */
  7995. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7996. /**
  7997. * @tsl
  7998. * @function
  7999. * @deprecated since r168. Use {@link uniformArray} instead.
  8000. *
  8001. * @param {Array<any>} values - Array-like data.
  8002. * @param {string} nodeType - The data type of the array elements.
  8003. * @returns {UniformArrayNode}
  8004. */
  8005. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  8006. console.warn( 'THREE.TSL: uniforms() has been renamed to uniformArray().' );
  8007. return nodeObject( new UniformArrayNode( values, nodeType ) );
  8008. };
  8009. /**
  8010. * The node allows to set values for built-in shader variables. That is
  8011. * required for features like hardware-accelerated vertex clipping.
  8012. *
  8013. * @augments Node
  8014. */
  8015. class BuiltinNode extends Node {
  8016. /**
  8017. * Constructs a new builtin node.
  8018. *
  8019. * @param {string} name - The name of the built-in shader variable.
  8020. */
  8021. constructor( name ) {
  8022. super( 'float' );
  8023. /**
  8024. * The name of the built-in shader variable.
  8025. *
  8026. * @type {string}
  8027. */
  8028. this.name = name;
  8029. /**
  8030. * This flag can be used for type testing.
  8031. *
  8032. * @type {boolean}
  8033. * @readonly
  8034. * @default true
  8035. */
  8036. this.isBuiltinNode = true;
  8037. }
  8038. /**
  8039. * Generates the code snippet of the builtin node.
  8040. *
  8041. * @param {NodeBuilder} builder - The current node builder.
  8042. * @return {string} The generated code snippet.
  8043. */
  8044. generate( /* builder */ ) {
  8045. return this.name;
  8046. }
  8047. }
  8048. /**
  8049. * TSL function for creating a builtin node.
  8050. *
  8051. * @tsl
  8052. * @function
  8053. * @param {string} name - The name of the built-in shader variable.
  8054. * @returns {BuiltinNode}
  8055. */
  8056. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8057. /**
  8058. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  8059. *
  8060. * @tsl
  8061. * @type {UniformNode<uint>}
  8062. */
  8063. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).label( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  8064. /**
  8065. * TSL object that represents the `near` value of the camera used for the current render.
  8066. *
  8067. * @tsl
  8068. * @type {UniformNode<float>}
  8069. */
  8070. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  8071. /**
  8072. * TSL object that represents the `far` value of the camera used for the current render.
  8073. *
  8074. * @tsl
  8075. * @type {UniformNode<float>}
  8076. */
  8077. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  8078. /**
  8079. * TSL object that represents the projection matrix of the camera used for the current render.
  8080. *
  8081. * @tsl
  8082. * @type {UniformNode<mat4>}
  8083. */
  8084. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8085. let cameraProjectionMatrix;
  8086. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8087. const matrices = [];
  8088. for ( const subCamera of camera.cameras ) {
  8089. matrices.push( subCamera.projectionMatrix );
  8090. }
  8091. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  8092. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrix' );
  8093. } else {
  8094. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  8095. }
  8096. return cameraProjectionMatrix;
  8097. } ).once() )();
  8098. /**
  8099. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  8100. *
  8101. * @tsl
  8102. * @type {UniformNode<mat4>}
  8103. */
  8104. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8105. let cameraProjectionMatrixInverse;
  8106. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8107. const matrices = [];
  8108. for ( const subCamera of camera.cameras ) {
  8109. matrices.push( subCamera.projectionMatrixInverse );
  8110. }
  8111. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatricesInverse' );
  8112. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrixInverse' );
  8113. } else {
  8114. cameraProjectionMatrixInverse = uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  8115. }
  8116. return cameraProjectionMatrixInverse;
  8117. } ).once() )();
  8118. /**
  8119. * TSL object that represents the view matrix of the camera used for the current render.
  8120. *
  8121. * @tsl
  8122. * @type {UniformNode<mat4>}
  8123. */
  8124. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8125. let cameraViewMatrix;
  8126. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8127. const matrices = [];
  8128. for ( const subCamera of camera.cameras ) {
  8129. matrices.push( subCamera.matrixWorldInverse );
  8130. }
  8131. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  8132. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraViewMatrix' );
  8133. } else {
  8134. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  8135. }
  8136. return cameraViewMatrix;
  8137. } ).once() )();
  8138. /**
  8139. * TSL object that represents the world matrix of the camera used for the current render.
  8140. *
  8141. * @tsl
  8142. * @type {UniformNode<mat4>}
  8143. */
  8144. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  8145. /**
  8146. * TSL object that represents the normal matrix of the camera used for the current render.
  8147. *
  8148. * @tsl
  8149. * @type {UniformNode<mat3>}
  8150. */
  8151. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  8152. /**
  8153. * TSL object that represents the position in world space of the camera used for the current render.
  8154. *
  8155. * @tsl
  8156. * @type {UniformNode<vec3>}
  8157. */
  8158. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  8159. const _sphere = /*@__PURE__*/ new Sphere();
  8160. /**
  8161. * This node can be used to access transformation related metrics of 3D objects.
  8162. * Depending on the selected scope, a different metric is represented as a uniform
  8163. * in the shader. The following scopes are supported:
  8164. *
  8165. * - `POSITION`: The object's position in world space.
  8166. * - `VIEW_POSITION`: The object's position in view/camera space.
  8167. * - `DIRECTION`: The object's direction in world space.
  8168. * - `SCALE`: The object's scale in world space.
  8169. * - `WORLD_MATRIX`: The object's matrix in world space.
  8170. *
  8171. * @augments Node
  8172. */
  8173. class Object3DNode extends Node {
  8174. static get type() {
  8175. return 'Object3DNode';
  8176. }
  8177. /**
  8178. * Constructs a new object 3D node.
  8179. *
  8180. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8181. * @param {?Object3D} [object3d=null] - The 3D object.
  8182. */
  8183. constructor( scope, object3d = null ) {
  8184. super();
  8185. /**
  8186. * The node reports a different type of transformation depending on the scope.
  8187. *
  8188. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  8189. */
  8190. this.scope = scope;
  8191. /**
  8192. * The 3D object.
  8193. *
  8194. * @type {?Object3D}
  8195. * @default null
  8196. */
  8197. this.object3d = object3d;
  8198. /**
  8199. * Overwritten since this type of node is updated per object.
  8200. *
  8201. * @type {string}
  8202. * @default 'object'
  8203. */
  8204. this.updateType = NodeUpdateType.OBJECT;
  8205. /**
  8206. * Holds the value of the node as a uniform.
  8207. *
  8208. * @type {UniformNode}
  8209. */
  8210. this.uniformNode = new UniformNode( null );
  8211. }
  8212. /**
  8213. * Overwritten since the node type is inferred from the scope.
  8214. *
  8215. * @return {string} The node type.
  8216. */
  8217. getNodeType() {
  8218. const scope = this.scope;
  8219. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8220. return 'mat4';
  8221. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8222. return 'vec3';
  8223. } else if ( scope === Object3DNode.RADIUS ) {
  8224. return 'float';
  8225. }
  8226. }
  8227. /**
  8228. * Updates the uniform value depending on the scope.
  8229. *
  8230. * @param {NodeFrame} frame - The current node frame.
  8231. */
  8232. update( frame ) {
  8233. const object = this.object3d;
  8234. const uniformNode = this.uniformNode;
  8235. const scope = this.scope;
  8236. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8237. uniformNode.value = object.matrixWorld;
  8238. } else if ( scope === Object3DNode.POSITION ) {
  8239. uniformNode.value = uniformNode.value || new Vector3();
  8240. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8241. } else if ( scope === Object3DNode.SCALE ) {
  8242. uniformNode.value = uniformNode.value || new Vector3();
  8243. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  8244. } else if ( scope === Object3DNode.DIRECTION ) {
  8245. uniformNode.value = uniformNode.value || new Vector3();
  8246. object.getWorldDirection( uniformNode.value );
  8247. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  8248. const camera = frame.camera;
  8249. uniformNode.value = uniformNode.value || new Vector3();
  8250. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8251. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  8252. } else if ( scope === Object3DNode.RADIUS ) {
  8253. const geometry = frame.object.geometry;
  8254. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8255. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8256. uniformNode.value = _sphere.radius;
  8257. }
  8258. }
  8259. /**
  8260. * Generates the code snippet of the uniform node. The node type of the uniform
  8261. * node also depends on the selected scope.
  8262. *
  8263. * @param {NodeBuilder} builder - The current node builder.
  8264. * @return {string} The generated code snippet.
  8265. */
  8266. generate( builder ) {
  8267. const scope = this.scope;
  8268. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8269. this.uniformNode.nodeType = 'mat4';
  8270. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8271. this.uniformNode.nodeType = 'vec3';
  8272. } else if ( scope === Object3DNode.RADIUS ) {
  8273. this.uniformNode.nodeType = 'float';
  8274. }
  8275. return this.uniformNode.build( builder );
  8276. }
  8277. serialize( data ) {
  8278. super.serialize( data );
  8279. data.scope = this.scope;
  8280. }
  8281. deserialize( data ) {
  8282. super.deserialize( data );
  8283. this.scope = data.scope;
  8284. }
  8285. }
  8286. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  8287. Object3DNode.POSITION = 'position';
  8288. Object3DNode.SCALE = 'scale';
  8289. Object3DNode.VIEW_POSITION = 'viewPosition';
  8290. Object3DNode.DIRECTION = 'direction';
  8291. Object3DNode.RADIUS = 'radius';
  8292. /**
  8293. * TSL function for creating an object 3D node that represents the object's direction in world space.
  8294. *
  8295. * @tsl
  8296. * @function
  8297. * @param {?Object3D} [object3d] - The 3D object.
  8298. * @returns {Object3DNode<vec3>}
  8299. */
  8300. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  8301. /**
  8302. * TSL function for creating an object 3D node that represents the object's world matrix.
  8303. *
  8304. * @tsl
  8305. * @function
  8306. * @param {?Object3D} [object3d] - The 3D object.
  8307. * @returns {Object3DNode<mat4>}
  8308. */
  8309. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  8310. /**
  8311. * TSL function for creating an object 3D node that represents the object's position in world space.
  8312. *
  8313. * @tsl
  8314. * @function
  8315. * @param {?Object3D} [object3d] - The 3D object.
  8316. * @returns {Object3DNode<vec3>}
  8317. */
  8318. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  8319. /**
  8320. * TSL function for creating an object 3D node that represents the object's scale in world space.
  8321. *
  8322. * @tsl
  8323. * @function
  8324. * @param {?Object3D} [object3d] - The 3D object.
  8325. * @returns {Object3DNode<vec3>}
  8326. */
  8327. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  8328. /**
  8329. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  8330. *
  8331. * @tsl
  8332. * @function
  8333. * @param {?Object3D} [object3d] - The 3D object.
  8334. * @returns {Object3DNode<vec3>}
  8335. */
  8336. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  8337. /**
  8338. * TSL function for creating an object 3D node that represents the object's radius.
  8339. *
  8340. * @tsl
  8341. * @function
  8342. * @param {?Object3D} [object3d] - The 3D object.
  8343. * @returns {Object3DNode<vec3>}
  8344. */
  8345. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  8346. /**
  8347. * This type of node is a specialized version of `Object3DNode`
  8348. * with larger set of model related metrics. Unlike `Object3DNode`,
  8349. * `ModelNode` extracts the reference to the 3D object from the
  8350. * current node frame state.
  8351. *
  8352. * @augments Object3DNode
  8353. */
  8354. class ModelNode extends Object3DNode {
  8355. static get type() {
  8356. return 'ModelNode';
  8357. }
  8358. /**
  8359. * Constructs a new object model node.
  8360. *
  8361. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8362. */
  8363. constructor( scope ) {
  8364. super( scope );
  8365. }
  8366. /**
  8367. * Extracts the model reference from the frame state and then
  8368. * updates the uniform value depending on the scope.
  8369. *
  8370. * @param {NodeFrame} frame - The current node frame.
  8371. */
  8372. update( frame ) {
  8373. this.object3d = frame.object;
  8374. super.update( frame );
  8375. }
  8376. }
  8377. /**
  8378. * TSL object that represents the object's direction in world space.
  8379. *
  8380. * @tsl
  8381. * @type {ModelNode<vec3>}
  8382. */
  8383. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  8384. /**
  8385. * TSL object that represents the object's world matrix.
  8386. *
  8387. * @tsl
  8388. * @type {ModelNode<mat4>}
  8389. */
  8390. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  8391. /**
  8392. * TSL object that represents the object's position in world space.
  8393. *
  8394. * @tsl
  8395. * @type {ModelNode<vec3>}
  8396. */
  8397. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  8398. /**
  8399. * TSL object that represents the object's scale in world space.
  8400. *
  8401. * @tsl
  8402. * @type {ModelNode<vec3>}
  8403. */
  8404. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  8405. /**
  8406. * TSL object that represents the object's position in view/camera space.
  8407. *
  8408. * @tsl
  8409. * @type {ModelNode<vec3>}
  8410. */
  8411. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  8412. /**
  8413. * TSL object that represents the object's radius.
  8414. *
  8415. * @tsl
  8416. * @type {ModelNode<float>}
  8417. */
  8418. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  8419. /**
  8420. * TSL object that represents the object's normal matrix.
  8421. *
  8422. * @tsl
  8423. * @type {UniformNode<mat3>}
  8424. */
  8425. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  8426. /**
  8427. * TSL object that represents the object's inverse world matrix.
  8428. *
  8429. * @tsl
  8430. * @type {UniformNode<mat4>}
  8431. */
  8432. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  8433. /**
  8434. * TSL object that represents the object's model view matrix.
  8435. *
  8436. * @tsl
  8437. * @type {Node<mat4>}
  8438. */
  8439. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8440. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  8441. } ).once() )().toVar( 'modelViewMatrix' );
  8442. // GPU Precision
  8443. /**
  8444. * TSL object that represents the object's model view in `mediump` precision.
  8445. *
  8446. * @tsl
  8447. * @type {Node<mat4>}
  8448. */
  8449. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  8450. // CPU Precision
  8451. /**
  8452. * TSL object that represents the object's model view in `highp` precision
  8453. * which is achieved by computing the matrix in JS and not in the shader.
  8454. *
  8455. * @tsl
  8456. * @type {Node<mat4>}
  8457. */
  8458. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8459. builder.context.isHighPrecisionModelViewMatrix = true;
  8460. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  8461. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8462. } );
  8463. } ).once() )().toVar( 'highpModelViewMatrix' );
  8464. /**
  8465. * TSL object that represents the object's model normal view in `highp` precision
  8466. * which is achieved by computing the matrix in JS and not in the shader.
  8467. *
  8468. * @tsl
  8469. * @type {Node<mat3>}
  8470. */
  8471. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8472. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  8473. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  8474. if ( isHighPrecisionModelViewMatrix !== true ) {
  8475. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8476. }
  8477. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  8478. } );
  8479. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  8480. /**
  8481. * TSL object that represents the position attribute of the current rendered object.
  8482. *
  8483. * @tsl
  8484. * @type {AttributeNode<vec3>}
  8485. */
  8486. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  8487. /**
  8488. * TSL object that represents the vertex position in local space of the current rendered object.
  8489. *
  8490. * @tsl
  8491. * @type {AttributeNode<vec3>}
  8492. */
  8493. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  8494. /**
  8495. * TSL object that represents the previous vertex position in local space of the current rendered object.
  8496. * Used in context of {@link VelocityNode} for rendering motion vectors.
  8497. *
  8498. * @tsl
  8499. * @type {AttributeNode<vec3>}
  8500. */
  8501. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  8502. /**
  8503. * TSL object that represents the vertex position in world space of the current rendered object.
  8504. *
  8505. * @tsl
  8506. * @type {VaryingNode<vec3>}
  8507. */
  8508. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  8509. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getNamespace( 'v_positionWorld' ) );
  8510. }, 'vec3' ).once( 'POSITION' ) )();
  8511. /**
  8512. * TSL object that represents the position world direction of the current rendered object.
  8513. *
  8514. * @tsl
  8515. * @type {Node<vec3>}
  8516. */
  8517. const positionWorldDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  8518. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( builder.getNamespace( 'v_positionWorldDirection' ) );
  8519. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  8520. }, 'vec3' ).once( 'POSITION' ) )();
  8521. /**
  8522. * TSL object that represents the vertex position in view space of the current rendered object.
  8523. *
  8524. * @tsl
  8525. * @type {VaryingNode<vec3>}
  8526. */
  8527. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8528. return builder.context.setupPositionView().toVarying( builder.getNamespace( 'v_positionView' ) );
  8529. }, 'vec3' ).once( 'POSITION' ) )();
  8530. /**
  8531. * TSL object that represents the position view direction of the current rendered object.
  8532. *
  8533. * @tsl
  8534. * @type {VaryingNode<vec3>}
  8535. */
  8536. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  8537. /**
  8538. * This node can be used to evaluate whether a primitive is front or back facing.
  8539. *
  8540. * @augments Node
  8541. */
  8542. class FrontFacingNode extends Node {
  8543. static get type() {
  8544. return 'FrontFacingNode';
  8545. }
  8546. /**
  8547. * Constructs a new front facing node.
  8548. */
  8549. constructor() {
  8550. super( 'bool' );
  8551. /**
  8552. * This flag can be used for type testing.
  8553. *
  8554. * @type {boolean}
  8555. * @readonly
  8556. * @default true
  8557. */
  8558. this.isFrontFacingNode = true;
  8559. }
  8560. generate( builder ) {
  8561. const { renderer, material } = builder;
  8562. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  8563. if ( material.side === BackSide ) {
  8564. return 'false';
  8565. }
  8566. }
  8567. return builder.getFrontFacing();
  8568. }
  8569. }
  8570. /**
  8571. * TSL object that represents whether a primitive is front or back facing
  8572. *
  8573. * @tsl
  8574. * @type {FrontFacingNode<bool>}
  8575. */
  8576. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  8577. /**
  8578. * TSL object that represents the front facing status as a number instead of a bool.
  8579. * `1` means front facing, `-1` means back facing.
  8580. *
  8581. * @tsl
  8582. * @type {Node<float>}
  8583. */
  8584. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  8585. /**
  8586. * TSL object that represents the normal attribute of the current rendered object.
  8587. *
  8588. * @tsl
  8589. * @type {Node<vec3>}
  8590. */
  8591. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  8592. /**
  8593. * TSL object that represents the vertex normal in local space of the current rendered object.
  8594. *
  8595. * @tsl
  8596. * @type {Node<vec3>}
  8597. */
  8598. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  8599. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8600. console.warn( 'THREE.TSL: Vertex attribute "normal" not found on geometry.' );
  8601. return vec3( 0, 1, 0 );
  8602. }
  8603. return normalGeometry;
  8604. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  8605. /**
  8606. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  8607. *
  8608. * @tsl
  8609. * @type {Node<vec3>}
  8610. */
  8611. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  8612. /**
  8613. * TSL object that represents the vertex normal in view space of the current rendered object.
  8614. *
  8615. * @tsl
  8616. * @type {Node<vec3>}
  8617. */
  8618. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8619. let node;
  8620. if ( builder.material.flatShading === true ) {
  8621. node = normalFlat;
  8622. } else {
  8623. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  8624. }
  8625. return node;
  8626. }, 'vec3' ).once() )().toVar( 'normalView' );
  8627. /**
  8628. * TSL object that represents the vertex normal in world space of the current rendered object.
  8629. *
  8630. * @tsl
  8631. * @type {Node<vec3>}
  8632. */
  8633. const normalWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  8634. let normal = normalView.transformDirection( cameraViewMatrix );
  8635. if ( builder.material.flatShading !== true ) {
  8636. normal = varying( normal, 'v_normalWorld' );
  8637. }
  8638. return normal;
  8639. }, 'vec3' ).once() )().normalize().toVar( 'normalWorld' );
  8640. /**
  8641. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  8642. *
  8643. * @tsl
  8644. * @type {Node<vec3>}
  8645. */
  8646. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8647. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8648. let node = builder.context.setupNormal().context( { getUV: null } );
  8649. if ( builder.material.flatShading !== true ) node = node.mul( faceDirection );
  8650. return node;
  8651. }, 'vec3' ).once() )().toVar( 'transformedNormalView' );
  8652. /**
  8653. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  8654. *
  8655. * @tsl
  8656. * @type {Node<vec3>}
  8657. */
  8658. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  8659. /**
  8660. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  8661. *
  8662. * @tsl
  8663. * @type {Node<vec3>}
  8664. */
  8665. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8666. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8667. let node = builder.context.setupClearcoatNormal().context( { getUV: null } );
  8668. if ( builder.material.flatShading !== true ) node = node.mul( faceDirection );
  8669. return node;
  8670. }, 'vec3' ).once() )().toVar( 'transformedClearcoatNormalView' );
  8671. /**
  8672. * Transforms the normal with the given matrix.
  8673. *
  8674. * @tsl
  8675. * @function
  8676. * @param {Node<vec3>} normal - The normal.
  8677. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  8678. * @return {Node<vec3>} The transformed normal.
  8679. */
  8680. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  8681. const m = mat3( matrix );
  8682. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  8683. return m.mul( transformedNormal ).xyz;
  8684. } );
  8685. /**
  8686. * Transforms the given normal from local to view space.
  8687. *
  8688. * @tsl
  8689. * @function
  8690. * @param {Node<vec3>} normal - The normal.
  8691. * @param {NodeBuilder} builder - The current node builder.
  8692. * @return {Node<vec3>} The transformed normal.
  8693. */
  8694. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  8695. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  8696. if ( modelNormalViewMatrix !== null ) {
  8697. return modelNormalViewMatrix.transformDirection( normal );
  8698. }
  8699. //
  8700. const transformedNormal = modelNormalMatrix.mul( normal );
  8701. return cameraViewMatrix.transformDirection( transformedNormal );
  8702. } );
  8703. const _e1$1 = /*@__PURE__*/ new Euler();
  8704. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8705. /**
  8706. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  8707. *
  8708. * @tsl
  8709. * @type {UniformNode<float>}
  8710. */
  8711. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  8712. /**
  8713. * TSL object that represents the intensity of environment maps of PBR materials.
  8714. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  8715. *
  8716. * @tsl
  8717. * @type {Node<float>}
  8718. */
  8719. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  8720. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  8721. } );
  8722. /**
  8723. * TSL object that represents the rotation of environment maps.
  8724. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  8725. * rotation of `scene.environment` instead.
  8726. *
  8727. * @tsl
  8728. * @type {Node<mat4>}
  8729. */
  8730. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  8731. return frame.material;
  8732. } ).onObjectUpdate( function ( { material, scene } ) {
  8733. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  8734. if ( rotation ) {
  8735. _e1$1.copy( rotation );
  8736. _m1$1.makeRotationFromEuler( _e1$1 );
  8737. } else {
  8738. _m1$1.identity();
  8739. }
  8740. return _m1$1;
  8741. } );
  8742. /**
  8743. * The reflect vector in view space.
  8744. *
  8745. * @tsl
  8746. * @type {Node<vec3>}
  8747. */
  8748. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  8749. /**
  8750. * The refract vector in view space.
  8751. *
  8752. * @tsl
  8753. * @type {Node<vec3>}
  8754. */
  8755. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  8756. /**
  8757. * Used for sampling cube maps when using cube reflection mapping.
  8758. *
  8759. * @tsl
  8760. * @type {Node<vec3>}
  8761. */
  8762. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8763. /**
  8764. * Used for sampling cube maps when using cube refraction mapping.
  8765. *
  8766. * @tsl
  8767. * @type {Node<vec3>}
  8768. */
  8769. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8770. /**
  8771. * This type of uniform node represents a cube texture.
  8772. *
  8773. * @augments TextureNode
  8774. */
  8775. class CubeTextureNode extends TextureNode {
  8776. static get type() {
  8777. return 'CubeTextureNode';
  8778. }
  8779. /**
  8780. * Constructs a new cube texture node.
  8781. *
  8782. * @param {CubeTexture} value - The cube texture.
  8783. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8784. * @param {?Node<int>} [levelNode=null] - The level node.
  8785. * @param {?Node<float>} [biasNode=null] - The bias node.
  8786. */
  8787. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  8788. super( value, uvNode, levelNode, biasNode );
  8789. /**
  8790. * This flag can be used for type testing.
  8791. *
  8792. * @type {boolean}
  8793. * @readonly
  8794. * @default true
  8795. */
  8796. this.isCubeTextureNode = true;
  8797. }
  8798. /**
  8799. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  8800. *
  8801. * @param {NodeBuilder} builder - The current node builder.
  8802. * @return {string} The input type.
  8803. */
  8804. getInputType( /*builder*/ ) {
  8805. return 'cubeTexture';
  8806. }
  8807. /**
  8808. * Returns a default uvs based on the mapping type of the cube texture.
  8809. *
  8810. * @return {Node<vec3>} The default uv attribute.
  8811. */
  8812. getDefaultUV() {
  8813. const texture = this.value;
  8814. if ( texture.mapping === CubeReflectionMapping ) {
  8815. return reflectVector;
  8816. } else if ( texture.mapping === CubeRefractionMapping ) {
  8817. return refractVector;
  8818. } else {
  8819. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  8820. return vec3( 0, 0, 0 );
  8821. }
  8822. }
  8823. /**
  8824. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  8825. * for cube textures. The uv transformation matrix is not applied to cube textures.
  8826. *
  8827. * @param {boolean} value - The update toggle.
  8828. */
  8829. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  8830. /**
  8831. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  8832. * to modify the uv node for correct sampling.
  8833. *
  8834. * @param {NodeBuilder} builder - The current node builder.
  8835. * @param {Node} uvNode - The uv node to setup.
  8836. * @return {Node} The updated uv node.
  8837. */
  8838. setupUV( builder, uvNode ) {
  8839. const texture = this.value;
  8840. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  8841. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  8842. }
  8843. return materialEnvRotation.mul( uvNode );
  8844. }
  8845. /**
  8846. * Generates the uv code snippet.
  8847. *
  8848. * @param {NodeBuilder} builder - The current node builder.
  8849. * @param {Node} cubeUV - The uv node to generate code for.
  8850. * @return {string} The generated code snippet.
  8851. */
  8852. generateUV( builder, cubeUV ) {
  8853. return cubeUV.build( builder, 'vec3' );
  8854. }
  8855. }
  8856. /**
  8857. * TSL function for creating a cube texture node.
  8858. *
  8859. * @tsl
  8860. * @function
  8861. * @param {CubeTexture} value - The cube texture.
  8862. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8863. * @param {?Node<int>} [levelNode=null] - The level node.
  8864. * @param {?Node<float>} [biasNode=null] - The bias node.
  8865. * @returns {CubeTextureNode}
  8866. */
  8867. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  8868. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  8869. /**
  8870. * This class is only relevant if the referenced property is array-like.
  8871. * In this case, `ReferenceElementNode` allows to refer to a specific
  8872. * element inside the data structure via an index.
  8873. *
  8874. * @augments ArrayElementNode
  8875. */
  8876. class ReferenceElementNode extends ArrayElementNode {
  8877. static get type() {
  8878. return 'ReferenceElementNode';
  8879. }
  8880. /**
  8881. * Constructs a new reference element node.
  8882. *
  8883. * @param {?ReferenceNode} referenceNode - The reference node.
  8884. * @param {Node} indexNode - The index node that defines the element access.
  8885. */
  8886. constructor( referenceNode, indexNode ) {
  8887. super( referenceNode, indexNode );
  8888. /**
  8889. * Similar to {@link ReferenceNode#reference}, an additional
  8890. * property references to the current node.
  8891. *
  8892. * @type {?ReferenceNode}
  8893. * @default null
  8894. */
  8895. this.referenceNode = referenceNode;
  8896. /**
  8897. * This flag can be used for type testing.
  8898. *
  8899. * @type {boolean}
  8900. * @readonly
  8901. * @default true
  8902. */
  8903. this.isReferenceElementNode = true;
  8904. }
  8905. /**
  8906. * This method is overwritten since the node type is inferred from
  8907. * the uniform type of the reference node.
  8908. *
  8909. * @return {string} The node type.
  8910. */
  8911. getNodeType() {
  8912. return this.referenceNode.uniformType;
  8913. }
  8914. generate( builder ) {
  8915. const snippet = super.generate( builder );
  8916. const arrayType = this.referenceNode.getNodeType();
  8917. const elementType = this.getNodeType();
  8918. return builder.format( snippet, arrayType, elementType );
  8919. }
  8920. }
  8921. /**
  8922. * This type of node establishes a reference to a property of another object.
  8923. * In this way, the value of the node is automatically linked to the value of
  8924. * referenced object. Reference nodes internally represent the linked value
  8925. * as a uniform.
  8926. *
  8927. * @augments Node
  8928. */
  8929. class ReferenceNode extends Node {
  8930. static get type() {
  8931. return 'ReferenceNode';
  8932. }
  8933. /**
  8934. * Constructs a new reference node.
  8935. *
  8936. * @param {string} property - The name of the property the node refers to.
  8937. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  8938. * @param {?Object} [object=null] - The object the property belongs to.
  8939. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  8940. */
  8941. constructor( property, uniformType, object = null, count = null ) {
  8942. super();
  8943. /**
  8944. * The name of the property the node refers to.
  8945. *
  8946. * @type {string}
  8947. */
  8948. this.property = property;
  8949. /**
  8950. * The uniform type that should be used to represent the property value.
  8951. *
  8952. * @type {string}
  8953. */
  8954. this.uniformType = uniformType;
  8955. /**
  8956. * The object the property belongs to.
  8957. *
  8958. * @type {?Object}
  8959. * @default null
  8960. */
  8961. this.object = object;
  8962. /**
  8963. * When the linked property is an array, this parameter defines its length.
  8964. *
  8965. * @type {?number}
  8966. * @default null
  8967. */
  8968. this.count = count;
  8969. /**
  8970. * The property name might have dots so nested properties can be referred.
  8971. * The hierarchy of the names is stored inside this array.
  8972. *
  8973. * @type {Array<string>}
  8974. */
  8975. this.properties = property.split( '.' );
  8976. /**
  8977. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  8978. * since the final reference might be updated from calling code.
  8979. *
  8980. * @type {?Object}
  8981. * @default null
  8982. */
  8983. this.reference = object;
  8984. /**
  8985. * The uniform node that holds the value of the reference node.
  8986. *
  8987. * @type {UniformNode}
  8988. * @default null
  8989. */
  8990. this.node = null;
  8991. /**
  8992. * The uniform group of the internal uniform.
  8993. *
  8994. * @type {UniformGroupNode}
  8995. * @default null
  8996. */
  8997. this.group = null;
  8998. /**
  8999. * An optional label of the internal uniform node.
  9000. *
  9001. * @type {?string}
  9002. * @default null
  9003. */
  9004. this.name = null;
  9005. /**
  9006. * Overwritten since reference nodes are updated per object.
  9007. *
  9008. * @type {string}
  9009. * @default 'object'
  9010. */
  9011. this.updateType = NodeUpdateType.OBJECT;
  9012. }
  9013. /**
  9014. * When the referred property is array-like, this method can be used
  9015. * to access elements via an index node.
  9016. *
  9017. * @param {IndexNode} indexNode - indexNode.
  9018. * @return {ReferenceElementNode} A reference to an element.
  9019. */
  9020. element( indexNode ) {
  9021. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  9022. }
  9023. /**
  9024. * Sets the uniform group for this reference node.
  9025. *
  9026. * @param {UniformGroupNode} group - The uniform group to set.
  9027. * @return {ReferenceNode} A reference to this node.
  9028. */
  9029. setGroup( group ) {
  9030. this.group = group;
  9031. return this;
  9032. }
  9033. /**
  9034. * Sets the label for the internal uniform.
  9035. *
  9036. * @param {string} name - The label to set.
  9037. * @return {ReferenceNode} A reference to this node.
  9038. */
  9039. label( name ) {
  9040. this.name = name;
  9041. return this;
  9042. }
  9043. /**
  9044. * Sets the node type which automatically defines the internal
  9045. * uniform type.
  9046. *
  9047. * @param {string} uniformType - The type to set.
  9048. */
  9049. setNodeType( uniformType ) {
  9050. let node = null;
  9051. if ( this.count !== null ) {
  9052. node = buffer( null, uniformType, this.count );
  9053. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  9054. node = uniformArray( null, uniformType );
  9055. } else if ( uniformType === 'texture' ) {
  9056. node = texture( null );
  9057. } else if ( uniformType === 'cubeTexture' ) {
  9058. node = cubeTexture( null );
  9059. } else {
  9060. node = uniform( null, uniformType );
  9061. }
  9062. if ( this.group !== null ) {
  9063. node.setGroup( this.group );
  9064. }
  9065. if ( this.name !== null ) node.label( this.name );
  9066. this.node = node.getSelf();
  9067. }
  9068. /**
  9069. * This method is overwritten since the node type is inferred from
  9070. * the type of the reference node.
  9071. *
  9072. * @param {NodeBuilder} builder - The current node builder.
  9073. * @return {string} The node type.
  9074. */
  9075. getNodeType( builder ) {
  9076. if ( this.node === null ) {
  9077. this.updateReference( builder );
  9078. this.updateValue();
  9079. }
  9080. return this.node.getNodeType( builder );
  9081. }
  9082. /**
  9083. * Returns the property value from the given referred object.
  9084. *
  9085. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  9086. * @return {any} The value.
  9087. */
  9088. getValueFromReference( object = this.reference ) {
  9089. const { properties } = this;
  9090. let value = object[ properties[ 0 ] ];
  9091. for ( let i = 1; i < properties.length; i ++ ) {
  9092. value = value[ properties[ i ] ];
  9093. }
  9094. return value;
  9095. }
  9096. /**
  9097. * Allows to update the reference based on the given state. The state is only
  9098. * evaluated {@link ReferenceNode#object} is not set.
  9099. *
  9100. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9101. * @return {Object} The updated reference.
  9102. */
  9103. updateReference( state ) {
  9104. this.reference = this.object !== null ? this.object : state.object;
  9105. return this.reference;
  9106. }
  9107. /**
  9108. * The output of the reference node is the internal uniform node.
  9109. *
  9110. * @param {NodeBuilder} builder - The current node builder.
  9111. * @return {UniformNode} The output node.
  9112. */
  9113. setup( /* builder */ ) {
  9114. this.updateValue();
  9115. return this.node;
  9116. }
  9117. /**
  9118. * Overwritten to update the internal uniform value.
  9119. *
  9120. * @param {NodeFrame} frame - A reference to the current node frame.
  9121. */
  9122. update( /*frame*/ ) {
  9123. this.updateValue();
  9124. }
  9125. /**
  9126. * Retrieves the value from the referred object property and uses it
  9127. * to updated the internal uniform.
  9128. */
  9129. updateValue() {
  9130. if ( this.node === null ) this.setNodeType( this.uniformType );
  9131. const value = this.getValueFromReference();
  9132. if ( Array.isArray( value ) ) {
  9133. this.node.array = value;
  9134. } else {
  9135. this.node.value = value;
  9136. }
  9137. }
  9138. }
  9139. /**
  9140. * TSL function for creating a reference node.
  9141. *
  9142. * @tsl
  9143. * @function
  9144. * @param {string} name - The name of the property the node refers to.
  9145. * @param {string} type - The uniform type that should be used to represent the property value.
  9146. * @param {?Object} [object] - The object the property belongs to.
  9147. * @returns {ReferenceNode}
  9148. */
  9149. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  9150. /**
  9151. * TSL function for creating a reference node. Use this function if you want need a reference
  9152. * to an array-like property that should be represented as a uniform buffer.
  9153. *
  9154. * @tsl
  9155. * @function
  9156. * @param {string} name - The name of the property the node refers to.
  9157. * @param {string} type - The uniform type that should be used to represent the property value.
  9158. * @param {number} count - The number of value inside the array-like object.
  9159. * @param {Object} object - An array-like object the property belongs to.
  9160. * @returns {ReferenceNode}
  9161. */
  9162. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  9163. /**
  9164. * This node is a special type of reference node which is intended
  9165. * for linking material properties with node values.
  9166. * ```js
  9167. * const opacityNode = materialReference( 'opacity', 'float', material );
  9168. * ```
  9169. * When changing `material.opacity`, the node value of `opacityNode` will
  9170. * automatically be updated.
  9171. *
  9172. * @augments ReferenceNode
  9173. */
  9174. class MaterialReferenceNode extends ReferenceNode {
  9175. static get type() {
  9176. return 'MaterialReferenceNode';
  9177. }
  9178. /**
  9179. * Constructs a new material reference node.
  9180. *
  9181. * @param {string} property - The name of the property the node refers to.
  9182. * @param {string} inputType - The uniform type that should be used to represent the property value.
  9183. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  9184. * the node refers to the material of the current rendered object.
  9185. */
  9186. constructor( property, inputType, material = null ) {
  9187. super( property, inputType, material );
  9188. /**
  9189. * The material the property belongs to. When no material is set,
  9190. * the node refers to the material of the current rendered object.
  9191. *
  9192. * @type {?Material}
  9193. * @default null
  9194. */
  9195. this.material = material;
  9196. /**
  9197. * This flag can be used for type testing.
  9198. *
  9199. * @type {boolean}
  9200. * @readonly
  9201. * @default true
  9202. */
  9203. this.isMaterialReferenceNode = true;
  9204. }
  9205. /**
  9206. * Updates the reference based on the given state. The state is only evaluated
  9207. * {@link MaterialReferenceNode#material} is not set.
  9208. *
  9209. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9210. * @return {Object} The updated reference.
  9211. */
  9212. updateReference( state ) {
  9213. this.reference = this.material !== null ? this.material : state.material;
  9214. return this.reference;
  9215. }
  9216. }
  9217. /**
  9218. * TSL function for creating a material reference node.
  9219. *
  9220. * @tsl
  9221. * @function
  9222. * @param {string} name - The name of the property the node refers to.
  9223. * @param {string} type - The uniform type that should be used to represent the property value.
  9224. * @param {?Material} [material=null] - The material the property belongs to.
  9225. * When no material is set, the node refers to the material of the current rendered object.
  9226. * @returns {MaterialReferenceNode}
  9227. */
  9228. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  9229. /**
  9230. * TSL object that represents the tangent attribute of the current rendered object.
  9231. *
  9232. * @tsl
  9233. * @type {Node<vec4>}
  9234. */
  9235. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  9236. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  9237. builder.geometry.computeTangents();
  9238. }
  9239. return attribute( 'tangent', 'vec4' );
  9240. } )();
  9241. /**
  9242. * TSL object that represents the vertex tangent in local space of the current rendered object.
  9243. *
  9244. * @tsl
  9245. * @type {Node<vec3>}
  9246. */
  9247. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  9248. /**
  9249. * TSL object that represents the vertex tangent in view space of the current rendered object.
  9250. *
  9251. * @tsl
  9252. * @type {Node<vec3>}
  9253. */
  9254. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  9255. /**
  9256. * TSL object that represents the vertex tangent in world space of the current rendered object.
  9257. *
  9258. * @tsl
  9259. * @type {Node<vec3>}
  9260. */
  9261. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  9262. /**
  9263. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  9264. *
  9265. * @tsl
  9266. * @type {Node<vec3>}
  9267. */
  9268. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  9269. /**
  9270. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  9271. *
  9272. * @tsl
  9273. * @type {Node<vec3>}
  9274. */
  9275. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  9276. /**
  9277. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  9278. *
  9279. * @tsl
  9280. * @private
  9281. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  9282. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  9283. * @returns {Node<vec3>} The bitangent node.
  9284. */
  9285. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], builder ) => {
  9286. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  9287. if ( builder.material.flatShading !== true ) {
  9288. bitangent = varying( bitangent, varyingName );
  9289. }
  9290. return bitangent;
  9291. } ).once();
  9292. /**
  9293. * TSL object that represents the bitangent attribute of the current rendered object.
  9294. *
  9295. * @tsl
  9296. * @type {Node<vec3>}
  9297. */
  9298. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  9299. /**
  9300. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  9301. *
  9302. * @tsl
  9303. * @type {Node<vec3>}
  9304. */
  9305. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  9306. /**
  9307. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  9308. *
  9309. * @tsl
  9310. * @type {Node<vec3>}
  9311. */
  9312. const bitangentView = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  9313. /**
  9314. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  9315. *
  9316. * @tsl
  9317. * @type {Node<vec3>}
  9318. */
  9319. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  9320. /**
  9321. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  9322. *
  9323. * @tsl
  9324. * @type {Node<vec3>}
  9325. */
  9326. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ), 'v_transformedBitangentView' ).normalize().toVar( 'transformedBitangentView' );
  9327. /**
  9328. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  9329. *
  9330. * @tsl
  9331. * @type {Node<vec4>}
  9332. */
  9333. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  9334. /**
  9335. * TSL object that represents the TBN matrix in view space.
  9336. *
  9337. * @tsl
  9338. * @type {Node<mat3>}
  9339. */
  9340. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  9341. /**
  9342. * TSL object that represents the parallax direction.
  9343. *
  9344. * @tsl
  9345. * @type {Node<mat3>}
  9346. */
  9347. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  9348. /**
  9349. * TSL function for computing parallax uv coordinates.
  9350. *
  9351. * @tsl
  9352. * @function
  9353. * @param {Node<vec2>} uv - A uv node.
  9354. * @param {Node<vec2>} scale - A scale node.
  9355. * @returns {Node<vec2>} Parallax uv coordinates.
  9356. */
  9357. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  9358. /**
  9359. * TSL function for computing bent normals.
  9360. *
  9361. * @tsl
  9362. * @function
  9363. * @returns {Node<vec3>} Bent normals.
  9364. */
  9365. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  9366. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  9367. let bentNormal = anisotropyB.cross( positionViewDirection );
  9368. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  9369. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  9370. return bentNormal;
  9371. } )();
  9372. // Normal Mapping Without Precomputed Tangents
  9373. // http://www.thetenthplanet.de/archives/1180
  9374. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  9375. const { eye_pos, surf_norm, mapN, uv } = inputs;
  9376. const q0 = eye_pos.dFdx();
  9377. const q1 = eye_pos.dFdy();
  9378. const st0 = uv.dFdx();
  9379. const st1 = uv.dFdy();
  9380. const N = surf_norm; // normalized
  9381. const q1perp = q1.cross( N );
  9382. const q0perp = N.cross( q0 );
  9383. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  9384. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  9385. const det = T.dot( T ).max( B.dot( B ) );
  9386. const scale = faceDirection.mul( det.inverseSqrt() );
  9387. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  9388. } );
  9389. /**
  9390. * This class can be used for applying normals maps to materials.
  9391. *
  9392. * ```js
  9393. * material.normalNode = normalMap( texture( normalTex ) );
  9394. * ```
  9395. *
  9396. * @augments TempNode
  9397. */
  9398. class NormalMapNode extends TempNode {
  9399. static get type() {
  9400. return 'NormalMapNode';
  9401. }
  9402. /**
  9403. * Constructs a new normal map node.
  9404. *
  9405. * @param {Node<vec3>} node - Represents the normal map data.
  9406. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9407. */
  9408. constructor( node, scaleNode = null ) {
  9409. super( 'vec3' );
  9410. /**
  9411. * Represents the normal map data.
  9412. *
  9413. * @type {Node<vec3>}
  9414. */
  9415. this.node = node;
  9416. /**
  9417. * Controls the intensity of the effect.
  9418. *
  9419. * @type {?Node<vec2>}
  9420. * @default null
  9421. */
  9422. this.scaleNode = scaleNode;
  9423. /**
  9424. * The normal map type.
  9425. *
  9426. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  9427. * @default TangentSpaceNormalMap
  9428. */
  9429. this.normalMapType = TangentSpaceNormalMap;
  9430. }
  9431. setup( builder ) {
  9432. const { normalMapType, scaleNode } = this;
  9433. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  9434. if ( scaleNode !== null ) {
  9435. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  9436. }
  9437. let outputNode = null;
  9438. if ( normalMapType === ObjectSpaceNormalMap ) {
  9439. outputNode = transformNormalToView( normalMap );
  9440. } else if ( normalMapType === TangentSpaceNormalMap ) {
  9441. const tangent = builder.hasGeometryAttribute( 'tangent' );
  9442. if ( tangent === true ) {
  9443. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  9444. } else {
  9445. outputNode = perturbNormal2Arb( {
  9446. eye_pos: positionView,
  9447. surf_norm: normalView,
  9448. mapN: normalMap,
  9449. uv: uv()
  9450. } );
  9451. }
  9452. }
  9453. return outputNode;
  9454. }
  9455. }
  9456. /**
  9457. * TSL function for creating a normal map node.
  9458. *
  9459. * @tsl
  9460. * @function
  9461. * @param {Node<vec3>} node - Represents the normal map data.
  9462. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9463. * @returns {NormalMapNode}
  9464. */
  9465. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  9466. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  9467. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  9468. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  9469. // It's used to preserve the same TextureNode instance
  9470. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  9471. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  9472. return vec2(
  9473. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  9474. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  9475. ).mul( bumpScale );
  9476. } );
  9477. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9478. const perturbNormalArb = Fn( ( inputs ) => {
  9479. const { surf_pos, surf_norm, dHdxy } = inputs;
  9480. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  9481. const vSigmaX = surf_pos.dFdx().normalize();
  9482. const vSigmaY = surf_pos.dFdy().normalize();
  9483. const vN = surf_norm; // normalized
  9484. const R1 = vSigmaY.cross( vN );
  9485. const R2 = vN.cross( vSigmaX );
  9486. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  9487. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  9488. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  9489. } );
  9490. /**
  9491. * This class can be used for applying bump maps to materials.
  9492. *
  9493. * ```js
  9494. * material.normalNode = bumpMap( texture( bumpTex ) );
  9495. * ```
  9496. *
  9497. * @augments TempNode
  9498. */
  9499. class BumpMapNode extends TempNode {
  9500. static get type() {
  9501. return 'BumpMapNode';
  9502. }
  9503. /**
  9504. * Constructs a new bump map node.
  9505. *
  9506. * @param {Node<float>} textureNode - Represents the bump map data.
  9507. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9508. */
  9509. constructor( textureNode, scaleNode = null ) {
  9510. super( 'vec3' );
  9511. /**
  9512. * Represents the bump map data.
  9513. *
  9514. * @type {Node<float>}
  9515. */
  9516. this.textureNode = textureNode;
  9517. /**
  9518. * Controls the intensity of the bump effect.
  9519. *
  9520. * @type {?Node<float>}
  9521. * @default null
  9522. */
  9523. this.scaleNode = scaleNode;
  9524. }
  9525. setup() {
  9526. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  9527. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  9528. return perturbNormalArb( {
  9529. surf_pos: positionView,
  9530. surf_norm: normalView,
  9531. dHdxy
  9532. } );
  9533. }
  9534. }
  9535. /**
  9536. * TSL function for creating a bump map node.
  9537. *
  9538. * @tsl
  9539. * @function
  9540. * @param {Node<float>} textureNode - Represents the bump map data.
  9541. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9542. * @returns {BumpMapNode}
  9543. */
  9544. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  9545. const _propertyCache = new Map();
  9546. /**
  9547. * This class should simplify the node access to material properties.
  9548. * It internal uses reference nodes to make sure changes to material
  9549. * properties are automatically reflected to predefined TSL objects
  9550. * like e.g. `materialColor`.
  9551. *
  9552. * @augments Node
  9553. */
  9554. class MaterialNode extends Node {
  9555. static get type() {
  9556. return 'MaterialNode';
  9557. }
  9558. /**
  9559. * Constructs a new material node.
  9560. *
  9561. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  9562. */
  9563. constructor( scope ) {
  9564. super();
  9565. /**
  9566. * The scope defines what material property is referred by the node.
  9567. *
  9568. * @type {string}
  9569. */
  9570. this.scope = scope;
  9571. }
  9572. /**
  9573. * Returns a cached reference node for the given property and type.
  9574. *
  9575. * @param {string} property - The name of the material property.
  9576. * @param {string} type - The uniform type of the property.
  9577. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9578. */
  9579. getCache( property, type ) {
  9580. let node = _propertyCache.get( property );
  9581. if ( node === undefined ) {
  9582. node = materialReference( property, type );
  9583. _propertyCache.set( property, node );
  9584. }
  9585. return node;
  9586. }
  9587. /**
  9588. * Returns a float-typed material reference node for the given property name.
  9589. *
  9590. * @param {string} property - The name of the material property.
  9591. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  9592. */
  9593. getFloat( property ) {
  9594. return this.getCache( property, 'float' );
  9595. }
  9596. /**
  9597. * Returns a color-typed material reference node for the given property name.
  9598. *
  9599. * @param {string} property - The name of the material property.
  9600. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  9601. */
  9602. getColor( property ) {
  9603. return this.getCache( property, 'color' );
  9604. }
  9605. /**
  9606. * Returns a texture-typed material reference node for the given property name.
  9607. *
  9608. * @param {string} property - The name of the material property.
  9609. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9610. */
  9611. getTexture( property ) {
  9612. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  9613. }
  9614. /**
  9615. * The node setup is done depending on the selected scope. Multiple material properties
  9616. * might be grouped into a single node composition if they logically belong together.
  9617. *
  9618. * @param {NodeBuilder} builder - The current node builder.
  9619. * @return {Node} The node representing the selected scope.
  9620. */
  9621. setup( builder ) {
  9622. const material = builder.context.material;
  9623. const scope = this.scope;
  9624. let node = null;
  9625. if ( scope === MaterialNode.COLOR ) {
  9626. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  9627. if ( material.map && material.map.isTexture === true ) {
  9628. node = colorNode.mul( this.getTexture( 'map' ) );
  9629. } else {
  9630. node = colorNode;
  9631. }
  9632. } else if ( scope === MaterialNode.OPACITY ) {
  9633. const opacityNode = this.getFloat( scope );
  9634. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  9635. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  9636. } else {
  9637. node = opacityNode;
  9638. }
  9639. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  9640. if ( material.specularMap && material.specularMap.isTexture === true ) {
  9641. node = this.getTexture( 'specular' ).r;
  9642. } else {
  9643. node = float( 1 );
  9644. }
  9645. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  9646. const specularIntensityNode = this.getFloat( scope );
  9647. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  9648. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  9649. } else {
  9650. node = specularIntensityNode;
  9651. }
  9652. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  9653. const specularColorNode = this.getColor( scope );
  9654. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  9655. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  9656. } else {
  9657. node = specularColorNode;
  9658. }
  9659. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  9660. const roughnessNode = this.getFloat( scope );
  9661. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  9662. node = roughnessNode.mul( this.getTexture( scope ).g );
  9663. } else {
  9664. node = roughnessNode;
  9665. }
  9666. } else if ( scope === MaterialNode.METALNESS ) {
  9667. const metalnessNode = this.getFloat( scope );
  9668. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  9669. node = metalnessNode.mul( this.getTexture( scope ).b );
  9670. } else {
  9671. node = metalnessNode;
  9672. }
  9673. } else if ( scope === MaterialNode.EMISSIVE ) {
  9674. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  9675. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  9676. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  9677. node = emissiveNode.mul( this.getTexture( scope ) );
  9678. } else {
  9679. node = emissiveNode;
  9680. }
  9681. } else if ( scope === MaterialNode.NORMAL ) {
  9682. if ( material.normalMap ) {
  9683. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  9684. node.normalMapType = material.normalMapType;
  9685. } else if ( material.bumpMap ) {
  9686. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  9687. } else {
  9688. node = normalView;
  9689. }
  9690. } else if ( scope === MaterialNode.CLEARCOAT ) {
  9691. const clearcoatNode = this.getFloat( scope );
  9692. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  9693. node = clearcoatNode.mul( this.getTexture( scope ).r );
  9694. } else {
  9695. node = clearcoatNode;
  9696. }
  9697. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  9698. const clearcoatRoughnessNode = this.getFloat( scope );
  9699. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  9700. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  9701. } else {
  9702. node = clearcoatRoughnessNode;
  9703. }
  9704. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  9705. if ( material.clearcoatNormalMap ) {
  9706. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  9707. } else {
  9708. node = normalView;
  9709. }
  9710. } else if ( scope === MaterialNode.SHEEN ) {
  9711. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  9712. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  9713. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  9714. } else {
  9715. node = sheenNode;
  9716. }
  9717. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  9718. const sheenRoughnessNode = this.getFloat( scope );
  9719. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  9720. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  9721. } else {
  9722. node = sheenRoughnessNode;
  9723. }
  9724. node = node.clamp( 0.07, 1.0 );
  9725. } else if ( scope === MaterialNode.ANISOTROPY ) {
  9726. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  9727. const anisotropyPolar = this.getTexture( scope );
  9728. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  9729. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  9730. } else {
  9731. node = materialAnisotropyVector;
  9732. }
  9733. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  9734. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  9735. if ( material.iridescenceThicknessMap ) {
  9736. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  9737. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  9738. } else {
  9739. node = iridescenceThicknessMaximum;
  9740. }
  9741. } else if ( scope === MaterialNode.TRANSMISSION ) {
  9742. const transmissionNode = this.getFloat( scope );
  9743. if ( material.transmissionMap ) {
  9744. node = transmissionNode.mul( this.getTexture( scope ).r );
  9745. } else {
  9746. node = transmissionNode;
  9747. }
  9748. } else if ( scope === MaterialNode.THICKNESS ) {
  9749. const thicknessNode = this.getFloat( scope );
  9750. if ( material.thicknessMap ) {
  9751. node = thicknessNode.mul( this.getTexture( scope ).g );
  9752. } else {
  9753. node = thicknessNode;
  9754. }
  9755. } else if ( scope === MaterialNode.IOR ) {
  9756. node = this.getFloat( scope );
  9757. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  9758. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  9759. } else if ( scope === MaterialNode.AO ) {
  9760. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  9761. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  9762. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  9763. } else {
  9764. const outputType = this.getNodeType( builder );
  9765. node = this.getCache( scope, outputType );
  9766. }
  9767. return node;
  9768. }
  9769. }
  9770. MaterialNode.ALPHA_TEST = 'alphaTest';
  9771. MaterialNode.COLOR = 'color';
  9772. MaterialNode.OPACITY = 'opacity';
  9773. MaterialNode.SHININESS = 'shininess';
  9774. MaterialNode.SPECULAR = 'specular';
  9775. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  9776. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  9777. MaterialNode.SPECULAR_COLOR = 'specularColor';
  9778. MaterialNode.REFLECTIVITY = 'reflectivity';
  9779. MaterialNode.ROUGHNESS = 'roughness';
  9780. MaterialNode.METALNESS = 'metalness';
  9781. MaterialNode.NORMAL = 'normal';
  9782. MaterialNode.CLEARCOAT = 'clearcoat';
  9783. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  9784. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  9785. MaterialNode.EMISSIVE = 'emissive';
  9786. MaterialNode.ROTATION = 'rotation';
  9787. MaterialNode.SHEEN = 'sheen';
  9788. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  9789. MaterialNode.ANISOTROPY = 'anisotropy';
  9790. MaterialNode.IRIDESCENCE = 'iridescence';
  9791. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  9792. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  9793. MaterialNode.IOR = 'ior';
  9794. MaterialNode.TRANSMISSION = 'transmission';
  9795. MaterialNode.THICKNESS = 'thickness';
  9796. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  9797. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  9798. MaterialNode.LINE_SCALE = 'scale';
  9799. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  9800. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  9801. MaterialNode.LINE_WIDTH = 'linewidth';
  9802. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  9803. MaterialNode.POINT_SIZE = 'size';
  9804. MaterialNode.DISPERSION = 'dispersion';
  9805. MaterialNode.LIGHT_MAP = 'light';
  9806. MaterialNode.AO = 'ao';
  9807. /**
  9808. * TSL object that represents alpha test of the current material.
  9809. *
  9810. * @tsl
  9811. * @type {Node<float>}
  9812. */
  9813. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  9814. /**
  9815. * TSL object that represents the diffuse color of the current material.
  9816. * The value is composed via `color` * `map`.
  9817. *
  9818. * @tsl
  9819. * @type {Node<vec3>}
  9820. */
  9821. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  9822. /**
  9823. * TSL object that represents the shininess of the current material.
  9824. *
  9825. * @tsl
  9826. * @type {Node<float>}
  9827. */
  9828. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  9829. /**
  9830. * TSL object that represents the emissive color of the current material.
  9831. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  9832. *
  9833. * @tsl
  9834. * @type {Node<vec3>}
  9835. */
  9836. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  9837. /**
  9838. * TSL object that represents the opacity of the current material.
  9839. * The value is composed via `opacity` * `alphaMap`.
  9840. *
  9841. * @tsl
  9842. * @type {Node<float>}
  9843. */
  9844. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  9845. /**
  9846. * TSL object that represents the specular of the current material.
  9847. *
  9848. * @tsl
  9849. * @type {Node<vec3>}
  9850. */
  9851. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  9852. /**
  9853. * TSL object that represents the specular intensity of the current material.
  9854. * The value is composed via `specularIntensity` * `specularMap.a`.
  9855. *
  9856. * @tsl
  9857. * @type {Node<float>}
  9858. */
  9859. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  9860. /**
  9861. * TSL object that represents the specular color of the current material.
  9862. * The value is composed via `specularColor` * `specularMap.rgb`.
  9863. *
  9864. * @tsl
  9865. * @type {Node<vec3>}
  9866. */
  9867. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  9868. /**
  9869. * TSL object that represents the specular strength of the current material.
  9870. * The value is composed via `specularMap.r`.
  9871. *
  9872. * @tsl
  9873. * @type {Node<float>}
  9874. */
  9875. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  9876. /**
  9877. * TSL object that represents the reflectivity of the current material.
  9878. *
  9879. * @tsl
  9880. * @type {Node<float>}
  9881. */
  9882. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  9883. /**
  9884. * TSL object that represents the roughness of the current material.
  9885. * The value is composed via `roughness` * `roughnessMap.g`.
  9886. *
  9887. * @tsl
  9888. * @type {Node<float>}
  9889. */
  9890. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  9891. /**
  9892. * TSL object that represents the metalness of the current material.
  9893. * The value is composed via `metalness` * `metalnessMap.b`.
  9894. *
  9895. * @tsl
  9896. * @type {Node<float>}
  9897. */
  9898. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  9899. /**
  9900. * TSL object that represents the normal of the current material.
  9901. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  9902. *
  9903. * @tsl
  9904. * @type {Node<vec3>}
  9905. */
  9906. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  9907. /**
  9908. * TSL object that represents the clearcoat of the current material.
  9909. * The value is composed via `clearcoat` * `clearcoatMap.r`
  9910. *
  9911. * @tsl
  9912. * @type {Node<float>}
  9913. */
  9914. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  9915. /**
  9916. * TSL object that represents the clearcoat roughness of the current material.
  9917. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  9918. *
  9919. * @tsl
  9920. * @type {Node<float>}
  9921. */
  9922. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  9923. /**
  9924. * TSL object that represents the clearcoat normal of the current material.
  9925. * The value will be either `clearcoatNormalMap` or `normalView`.
  9926. *
  9927. * @tsl
  9928. * @type {Node<vec3>}
  9929. */
  9930. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  9931. /**
  9932. * TSL object that represents the rotation of the current sprite material.
  9933. *
  9934. * @tsl
  9935. * @type {Node<float>}
  9936. */
  9937. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  9938. /**
  9939. * TSL object that represents the sheen color of the current material.
  9940. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  9941. *
  9942. * @tsl
  9943. * @type {Node<vec3>}
  9944. */
  9945. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  9946. /**
  9947. * TSL object that represents the sheen roughness of the current material.
  9948. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  9949. *
  9950. * @tsl
  9951. * @type {Node<float>}
  9952. */
  9953. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  9954. /**
  9955. * TSL object that represents the anisotropy of the current material.
  9956. *
  9957. * @tsl
  9958. * @type {Node<vec2>}
  9959. */
  9960. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  9961. /**
  9962. * TSL object that represents the iridescence of the current material.
  9963. *
  9964. * @tsl
  9965. * @type {Node<float>}
  9966. */
  9967. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  9968. /**
  9969. * TSL object that represents the iridescence IOR of the current material.
  9970. *
  9971. * @tsl
  9972. * @type {Node<float>}
  9973. */
  9974. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  9975. /**
  9976. * TSL object that represents the iridescence thickness of the current material.
  9977. *
  9978. * @tsl
  9979. * @type {Node<float>}
  9980. */
  9981. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  9982. /**
  9983. * TSL object that represents the transmission of the current material.
  9984. * The value is composed via `transmission` * `transmissionMap.r`.
  9985. *
  9986. * @tsl
  9987. * @type {Node<float>}
  9988. */
  9989. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  9990. /**
  9991. * TSL object that represents the thickness of the current material.
  9992. * The value is composed via `thickness` * `thicknessMap.g`.
  9993. *
  9994. * @tsl
  9995. * @type {Node<float>}
  9996. */
  9997. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  9998. /**
  9999. * TSL object that represents the IOR of the current material.
  10000. *
  10001. * @tsl
  10002. * @type {Node<float>}
  10003. */
  10004. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  10005. /**
  10006. * TSL object that represents the attenuation distance of the current material.
  10007. *
  10008. * @tsl
  10009. * @type {Node<float>}
  10010. */
  10011. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  10012. /**
  10013. * TSL object that represents the attenuation color of the current material.
  10014. *
  10015. * @tsl
  10016. * @type {Node<vec3>}
  10017. */
  10018. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  10019. /**
  10020. * TSL object that represents the scale of the current dashed line material.
  10021. *
  10022. * @tsl
  10023. * @type {Node<float>}
  10024. */
  10025. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  10026. /**
  10027. * TSL object that represents the dash size of the current dashed line material.
  10028. *
  10029. * @tsl
  10030. * @type {Node<float>}
  10031. */
  10032. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  10033. /**
  10034. * TSL object that represents the gap size of the current dashed line material.
  10035. *
  10036. * @tsl
  10037. * @type {Node<float>}
  10038. */
  10039. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  10040. /**
  10041. * TSL object that represents the line width of the current line material.
  10042. *
  10043. * @tsl
  10044. * @type {Node<float>}
  10045. */
  10046. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  10047. /**
  10048. * TSL object that represents the dash offset of the current line material.
  10049. *
  10050. * @tsl
  10051. * @type {Node<float>}
  10052. */
  10053. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  10054. /**
  10055. * TSL object that represents the point size of the current points material.
  10056. *
  10057. * @tsl
  10058. * @type {Node<float>}
  10059. */
  10060. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  10061. /**
  10062. * TSL object that represents the dispersion of the current material.
  10063. *
  10064. * @tsl
  10065. * @type {Node<float>}
  10066. */
  10067. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  10068. /**
  10069. * TSL object that represents the light map of the current material.
  10070. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  10071. *
  10072. * @tsl
  10073. * @type {Node<vec3>}
  10074. */
  10075. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  10076. /**
  10077. * TSL object that represents the ambient occlusion map of the current material.
  10078. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  10079. *
  10080. * @tsl
  10081. * @type {Node<float>}
  10082. */
  10083. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  10084. /**
  10085. * TSL object that represents the anisotropy vector of the current material.
  10086. *
  10087. * @tsl
  10088. * @type {Node<vec2>}
  10089. */
  10090. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  10091. return frame.material;
  10092. } ).onRenderUpdate( function ( { material } ) {
  10093. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  10094. } );
  10095. /**
  10096. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  10097. *
  10098. * @tsl
  10099. * @type {VaryingNode<vec4>}
  10100. */
  10101. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10102. return builder.context.setupModelViewProjection();
  10103. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  10104. /**
  10105. * This class represents shader indices of different types. The following predefined node
  10106. * objects cover frequent use cases:
  10107. *
  10108. * - `vertexIndex`: The index of a vertex within a mesh.
  10109. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  10110. * - `drawIndex`: The index of a draw call.
  10111. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  10112. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  10113. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  10114. *
  10115. * @augments Node
  10116. */
  10117. class IndexNode extends Node {
  10118. static get type() {
  10119. return 'IndexNode';
  10120. }
  10121. /**
  10122. * Constructs a new index node.
  10123. *
  10124. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  10125. */
  10126. constructor( scope ) {
  10127. super( 'uint' );
  10128. /**
  10129. * The scope of the index node.
  10130. *
  10131. * @type {string}
  10132. */
  10133. this.scope = scope;
  10134. /**
  10135. * This flag can be used for type testing.
  10136. *
  10137. * @type {boolean}
  10138. * @readonly
  10139. * @default true
  10140. */
  10141. this.isIndexNode = true;
  10142. }
  10143. generate( builder ) {
  10144. const nodeType = this.getNodeType( builder );
  10145. const scope = this.scope;
  10146. let propertyName;
  10147. if ( scope === IndexNode.VERTEX ) {
  10148. propertyName = builder.getVertexIndex();
  10149. } else if ( scope === IndexNode.INSTANCE ) {
  10150. propertyName = builder.getInstanceIndex();
  10151. } else if ( scope === IndexNode.DRAW ) {
  10152. propertyName = builder.getDrawIndex();
  10153. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  10154. propertyName = builder.getInvocationLocalIndex();
  10155. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  10156. propertyName = builder.getInvocationSubgroupIndex();
  10157. } else if ( scope === IndexNode.SUBGROUP ) {
  10158. propertyName = builder.getSubgroupIndex();
  10159. } else {
  10160. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  10161. }
  10162. let output;
  10163. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  10164. output = propertyName;
  10165. } else {
  10166. const nodeVarying = varying( this );
  10167. output = nodeVarying.build( builder, nodeType );
  10168. }
  10169. return output;
  10170. }
  10171. }
  10172. IndexNode.VERTEX = 'vertex';
  10173. IndexNode.INSTANCE = 'instance';
  10174. IndexNode.SUBGROUP = 'subgroup';
  10175. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  10176. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  10177. IndexNode.DRAW = 'draw';
  10178. /**
  10179. * TSL object that represents the index of a vertex within a mesh.
  10180. *
  10181. * @tsl
  10182. * @type {IndexNode}
  10183. */
  10184. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  10185. /**
  10186. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  10187. *
  10188. * @tsl
  10189. * @type {IndexNode}
  10190. */
  10191. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  10192. /**
  10193. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  10194. *
  10195. * @tsl
  10196. * @type {IndexNode}
  10197. */
  10198. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  10199. /**
  10200. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  10201. *
  10202. * @tsl
  10203. * @type {IndexNode}
  10204. */
  10205. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  10206. /**
  10207. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  10208. *
  10209. * @tsl
  10210. * @type {IndexNode}
  10211. */
  10212. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  10213. /**
  10214. * TSL object that represents the index of a draw call.
  10215. *
  10216. * @tsl
  10217. * @type {IndexNode}
  10218. */
  10219. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  10220. /**
  10221. * This node implements the vertex shader logic which is required
  10222. * when rendering 3D objects via instancing. The code makes sure
  10223. * vertex positions, normals and colors can be modified via instanced
  10224. * data.
  10225. *
  10226. * @augments Node
  10227. */
  10228. class InstanceNode extends Node {
  10229. static get type() {
  10230. return 'InstanceNode';
  10231. }
  10232. /**
  10233. * Constructs a new instance node.
  10234. *
  10235. * @param {number} count - The number of instances.
  10236. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10237. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10238. */
  10239. constructor( count, instanceMatrix, instanceColor = null ) {
  10240. super( 'void' );
  10241. /**
  10242. * The number of instances.
  10243. *
  10244. * @type {number}
  10245. */
  10246. this.count = count;
  10247. /**
  10248. * Instanced buffer attribute representing the transformation of instances.
  10249. *
  10250. * @type {InstancedBufferAttribute}
  10251. */
  10252. this.instanceMatrix = instanceMatrix;
  10253. /**
  10254. * Instanced buffer attribute representing the color of instances.
  10255. *
  10256. * @type {InstancedBufferAttribute}
  10257. */
  10258. this.instanceColor = instanceColor;
  10259. /**
  10260. * The node that represents the instance matrix data.
  10261. *
  10262. * @type {?Node}
  10263. */
  10264. this.instanceMatrixNode = null;
  10265. /**
  10266. * The node that represents the instance color data.
  10267. *
  10268. * @type {?Node}
  10269. * @default null
  10270. */
  10271. this.instanceColorNode = null;
  10272. /**
  10273. * The update type is set to `frame` since an update
  10274. * of instanced buffer data must be checked per frame.
  10275. *
  10276. * @type {string}
  10277. * @default 'frame'
  10278. */
  10279. this.updateType = NodeUpdateType.FRAME;
  10280. /**
  10281. * A reference to a buffer that is used by `instanceMatrixNode`.
  10282. *
  10283. * @type {?InstancedInterleavedBuffer}
  10284. */
  10285. this.buffer = null;
  10286. /**
  10287. * A reference to a buffer that is used by `instanceColorNode`.
  10288. *
  10289. * @type {?InstancedBufferAttribute}
  10290. */
  10291. this.bufferColor = null;
  10292. }
  10293. /**
  10294. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10295. * to predefined node variables for accumulation. That follows the same patterns
  10296. * like with morph and skinning nodes.
  10297. *
  10298. * @param {NodeBuilder} builder - The current node builder.
  10299. */
  10300. setup( builder ) {
  10301. const { count, instanceMatrix, instanceColor } = this;
  10302. let { instanceMatrixNode, instanceColorNode } = this;
  10303. if ( instanceMatrixNode === null ) {
  10304. // Both WebGPU and WebGL backends have UBO max limited to 64kb. Matrix count number bigger than 1000 ( 16 * 4 * 1000 = 64kb ) will fallback to attribute.
  10305. if ( count <= 1000 ) {
  10306. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  10307. } else {
  10308. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  10309. this.buffer = buffer;
  10310. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10311. const instanceBuffers = [
  10312. // F.Signature -> bufferAttribute( array, type, stride, offset )
  10313. bufferFn( buffer, 'vec4', 16, 0 ),
  10314. bufferFn( buffer, 'vec4', 16, 4 ),
  10315. bufferFn( buffer, 'vec4', 16, 8 ),
  10316. bufferFn( buffer, 'vec4', 16, 12 )
  10317. ];
  10318. instanceMatrixNode = mat4( ...instanceBuffers );
  10319. }
  10320. this.instanceMatrixNode = instanceMatrixNode;
  10321. }
  10322. if ( instanceColor && instanceColorNode === null ) {
  10323. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  10324. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10325. this.bufferColor = buffer;
  10326. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  10327. this.instanceColorNode = instanceColorNode;
  10328. }
  10329. // POSITION
  10330. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  10331. positionLocal.assign( instancePosition );
  10332. // NORMAL
  10333. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10334. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  10335. // ASSIGNS
  10336. normalLocal.assign( instanceNormal );
  10337. }
  10338. // COLOR
  10339. if ( this.instanceColorNode !== null ) {
  10340. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  10341. }
  10342. }
  10343. /**
  10344. * Checks if the internal buffers required an update.
  10345. *
  10346. * @param {NodeFrame} frame - The current node frame.
  10347. */
  10348. update( /*frame*/ ) {
  10349. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  10350. this.buffer.version = this.instanceMatrix.version;
  10351. }
  10352. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  10353. this.bufferColor.version = this.instanceColor.version;
  10354. }
  10355. }
  10356. }
  10357. /**
  10358. * TSL function for creating an instance node.
  10359. *
  10360. * @tsl
  10361. * @function
  10362. * @param {number} count - The number of instances.
  10363. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10364. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10365. * @returns {InstanceNode}
  10366. */
  10367. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  10368. /**
  10369. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  10370. * It allows an easier setup of the instance node.
  10371. *
  10372. * @augments InstanceNode
  10373. */
  10374. class InstancedMeshNode extends InstanceNode {
  10375. static get type() {
  10376. return 'InstancedMeshNode';
  10377. }
  10378. /**
  10379. * Constructs a new instanced mesh node.
  10380. *
  10381. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  10382. */
  10383. constructor( instancedMesh ) {
  10384. const { count, instanceMatrix, instanceColor } = instancedMesh;
  10385. super( count, instanceMatrix, instanceColor );
  10386. /**
  10387. * A reference to the instanced mesh.
  10388. *
  10389. * @type {InstancedMesh}
  10390. */
  10391. this.instancedMesh = instancedMesh;
  10392. }
  10393. }
  10394. /**
  10395. * TSL function for creating an instanced mesh node.
  10396. *
  10397. * @tsl
  10398. * @function
  10399. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  10400. * @returns {InstancedMeshNode}
  10401. */
  10402. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  10403. /**
  10404. * This node implements the vertex shader logic which is required
  10405. * when rendering 3D objects via batching. `BatchNode` must be used
  10406. * with instances of {@link BatchedMesh}.
  10407. *
  10408. * @augments Node
  10409. */
  10410. class BatchNode extends Node {
  10411. static get type() {
  10412. return 'BatchNode';
  10413. }
  10414. /**
  10415. * Constructs a new batch node.
  10416. *
  10417. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10418. */
  10419. constructor( batchMesh ) {
  10420. super( 'void' );
  10421. /**
  10422. * A reference to batched mesh.
  10423. *
  10424. * @type {BatchedMesh}
  10425. */
  10426. this.batchMesh = batchMesh;
  10427. /**
  10428. * The batching index node.
  10429. *
  10430. * @type {?IndexNode}
  10431. * @default null
  10432. */
  10433. this.batchingIdNode = null;
  10434. }
  10435. /**
  10436. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10437. * to predefined node variables for accumulation. That follows the same patterns
  10438. * like with morph and skinning nodes.
  10439. *
  10440. * @param {NodeBuilder} builder - The current node builder.
  10441. */
  10442. setup( builder ) {
  10443. if ( this.batchingIdNode === null ) {
  10444. if ( builder.getDrawIndex() === null ) {
  10445. this.batchingIdNode = instanceIndex;
  10446. } else {
  10447. this.batchingIdNode = drawIndex;
  10448. }
  10449. }
  10450. const getIndirectIndex = Fn( ( [ id ] ) => {
  10451. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  10452. const x = int( id ).mod( size );
  10453. const y = int( id ).div( size );
  10454. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  10455. } ).setLayout( {
  10456. name: 'getIndirectIndex',
  10457. type: 'uint',
  10458. inputs: [
  10459. { name: 'id', type: 'int' }
  10460. ]
  10461. } );
  10462. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  10463. const matricesTexture = this.batchMesh._matricesTexture;
  10464. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  10465. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  10466. const x = j.mod( size );
  10467. const y = j.div( size );
  10468. const batchingMatrix = mat4(
  10469. textureLoad( matricesTexture, ivec2( x, y ) ),
  10470. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  10471. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  10472. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  10473. );
  10474. const colorsTexture = this.batchMesh._colorsTexture;
  10475. if ( colorsTexture !== null ) {
  10476. const getBatchingColor = Fn( ( [ id ] ) => {
  10477. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  10478. const j = id;
  10479. const x = j.mod( size );
  10480. const y = j.div( size );
  10481. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  10482. } ).setLayout( {
  10483. name: 'getBatchingColor',
  10484. type: 'vec3',
  10485. inputs: [
  10486. { name: 'id', type: 'int' }
  10487. ]
  10488. } );
  10489. const color = getBatchingColor( indirectId );
  10490. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  10491. }
  10492. const bm = mat3( batchingMatrix );
  10493. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  10494. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  10495. const batchingNormal = bm.mul( transformedNormal ).xyz;
  10496. normalLocal.assign( batchingNormal );
  10497. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10498. tangentLocal.mulAssign( bm );
  10499. }
  10500. }
  10501. }
  10502. /**
  10503. * TSL function for creating a batch node.
  10504. *
  10505. * @tsl
  10506. * @function
  10507. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10508. * @returns {BatchNode}
  10509. */
  10510. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  10511. /**
  10512. * This class enables element access on instances of {@link StorageBufferNode}.
  10513. * In most cases, it is indirectly used when accessing elements with the
  10514. * {@link StorageBufferNode#element} method.
  10515. *
  10516. * ```js
  10517. * const position = positionStorage.element( instanceIndex );
  10518. * ```
  10519. *
  10520. * @augments ArrayElementNode
  10521. */
  10522. class StorageArrayElementNode extends ArrayElementNode {
  10523. static get type() {
  10524. return 'StorageArrayElementNode';
  10525. }
  10526. /**
  10527. * Constructs storage buffer element node.
  10528. *
  10529. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  10530. * @param {Node} indexNode - The index node that defines the element access.
  10531. */
  10532. constructor( storageBufferNode, indexNode ) {
  10533. super( storageBufferNode, indexNode );
  10534. /**
  10535. * This flag can be used for type testing.
  10536. *
  10537. * @type {boolean}
  10538. * @readonly
  10539. * @default true
  10540. */
  10541. this.isStorageArrayElementNode = true;
  10542. }
  10543. /**
  10544. * The storage buffer node.
  10545. *
  10546. * @param {Node} value
  10547. * @type {StorageBufferNode}
  10548. */
  10549. set storageBufferNode( value ) {
  10550. this.node = value;
  10551. }
  10552. get storageBufferNode() {
  10553. return this.node;
  10554. }
  10555. getMemberType( builder, name ) {
  10556. const structTypeNode = this.storageBufferNode.structTypeNode;
  10557. if ( structTypeNode ) {
  10558. return structTypeNode.getMemberType( builder, name );
  10559. }
  10560. return 'void';
  10561. }
  10562. setup( builder ) {
  10563. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10564. if ( this.node.isPBO === true ) {
  10565. builder.setupPBO( this.node );
  10566. }
  10567. }
  10568. return super.setup( builder );
  10569. }
  10570. generate( builder, output ) {
  10571. let snippet;
  10572. const isAssignContext = builder.context.assign;
  10573. //
  10574. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10575. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  10576. snippet = builder.generatePBO( this );
  10577. } else {
  10578. snippet = this.node.build( builder );
  10579. }
  10580. } else {
  10581. snippet = super.generate( builder );
  10582. }
  10583. if ( isAssignContext !== true ) {
  10584. const type = this.getNodeType( builder );
  10585. snippet = builder.format( snippet, type, output );
  10586. }
  10587. return snippet;
  10588. }
  10589. }
  10590. /**
  10591. * TSL function for creating a storage element node.
  10592. *
  10593. * @tsl
  10594. * @function
  10595. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  10596. * @param {Node} indexNode - The index node that defines the element access.
  10597. * @returns {StorageArrayElementNode}
  10598. */
  10599. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  10600. /**
  10601. * This node is used in context of compute shaders and allows to define a
  10602. * storage buffer for data. A typical workflow is to create instances of
  10603. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  10604. * setup up a compute shader that writes into the buffers and then convert
  10605. * the storage buffers to attribute nodes for rendering.
  10606. *
  10607. * ```js
  10608. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  10609. *
  10610. * const computeInit = Fn( () => { // the compute shader
  10611. *
  10612. * const position = positionBuffer.element( instanceIndex );
  10613. *
  10614. * // compute position data
  10615. *
  10616. * position.x = 1;
  10617. * position.y = 1;
  10618. * position.z = 1;
  10619. *
  10620. * } )().compute( particleCount );
  10621. *
  10622. * const particleMaterial = new THREE.SpriteNodeMaterial();
  10623. * particleMaterial.positionNode = positionBuffer.toAttribute();
  10624. *
  10625. * renderer.computeAsync( computeInit );
  10626. *
  10627. * ```
  10628. *
  10629. * @augments BufferNode
  10630. */
  10631. class StorageBufferNode extends BufferNode {
  10632. static get type() {
  10633. return 'StorageBufferNode';
  10634. }
  10635. /**
  10636. * Constructs a new storage buffer node.
  10637. *
  10638. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10639. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  10640. * @param {number} [bufferCount=0] - The buffer count.
  10641. */
  10642. constructor( value, bufferType = null, bufferCount = 0 ) {
  10643. let nodeType, structTypeNode = null;
  10644. if ( bufferType && bufferType.isStruct ) {
  10645. nodeType = 'struct';
  10646. structTypeNode = bufferType.layout;
  10647. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  10648. bufferCount = value.count;
  10649. }
  10650. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  10651. nodeType = getTypeFromLength( value.itemSize );
  10652. bufferCount = value.count;
  10653. } else {
  10654. nodeType = bufferType;
  10655. }
  10656. super( value, nodeType, bufferCount );
  10657. /**
  10658. * This flag can be used for type testing.
  10659. *
  10660. * @type {boolean}
  10661. * @readonly
  10662. * @default true
  10663. */
  10664. this.isStorageBufferNode = true;
  10665. /**
  10666. * The buffer struct type.
  10667. *
  10668. * @type {?StructTypeNode}
  10669. * @default null
  10670. */
  10671. this.structTypeNode = structTypeNode;
  10672. /**
  10673. * The access type of the texture node.
  10674. *
  10675. * @type {string}
  10676. * @default 'readWrite'
  10677. */
  10678. this.access = NodeAccess.READ_WRITE;
  10679. /**
  10680. * Whether the node is atomic or not.
  10681. *
  10682. * @type {boolean}
  10683. * @default false
  10684. */
  10685. this.isAtomic = false;
  10686. /**
  10687. * Whether the node represents a PBO or not.
  10688. * Only relevant for WebGL.
  10689. *
  10690. * @type {boolean}
  10691. * @default false
  10692. */
  10693. this.isPBO = false;
  10694. /**
  10695. * A reference to the internal buffer attribute node.
  10696. *
  10697. * @type {?BufferAttributeNode}
  10698. * @default null
  10699. */
  10700. this._attribute = null;
  10701. /**
  10702. * A reference to the internal varying node.
  10703. *
  10704. * @type {?VaryingNode}
  10705. * @default null
  10706. */
  10707. this._varying = null;
  10708. /**
  10709. * `StorageBufferNode` sets this property to `true` by default.
  10710. *
  10711. * @type {boolean}
  10712. * @default true
  10713. */
  10714. this.global = true;
  10715. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  10716. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  10717. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  10718. else value.isStorageBufferAttribute = true;
  10719. }
  10720. }
  10721. /**
  10722. * This method is overwritten since the buffer data might be shared
  10723. * and thus the hash should be shared as well.
  10724. *
  10725. * @param {NodeBuilder} builder - The current node builder.
  10726. * @return {string} The hash.
  10727. */
  10728. getHash( builder ) {
  10729. if ( this.bufferCount === 0 ) {
  10730. let bufferData = builder.globalCache.getData( this.value );
  10731. if ( bufferData === undefined ) {
  10732. bufferData = {
  10733. node: this
  10734. };
  10735. builder.globalCache.setData( this.value, bufferData );
  10736. }
  10737. return bufferData.node.uuid;
  10738. }
  10739. return this.uuid;
  10740. }
  10741. /**
  10742. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  10743. *
  10744. * @param {NodeBuilder} builder - The current node builder.
  10745. * @return {string} The input type.
  10746. */
  10747. getInputType( /*builder*/ ) {
  10748. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  10749. }
  10750. /**
  10751. * Enables element access with the given index node.
  10752. *
  10753. * @param {IndexNode} indexNode - The index node.
  10754. * @return {StorageArrayElementNode} A node representing the element access.
  10755. */
  10756. element( indexNode ) {
  10757. return storageElement( this, indexNode );
  10758. }
  10759. /**
  10760. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  10761. *
  10762. * @param {boolean} value - The value so set.
  10763. * @return {StorageBufferNode} A reference to this node.
  10764. */
  10765. setPBO( value ) {
  10766. this.isPBO = value;
  10767. return this;
  10768. }
  10769. /**
  10770. * Returns the `isPBO` value.
  10771. *
  10772. * @return {boolean} Whether the node represents a PBO or not.
  10773. */
  10774. getPBO() {
  10775. return this.isPBO;
  10776. }
  10777. /**
  10778. * Defines the node access.
  10779. *
  10780. * @param {string} value - The node access.
  10781. * @return {StorageBufferNode} A reference to this node.
  10782. */
  10783. setAccess( value ) {
  10784. this.access = value;
  10785. return this;
  10786. }
  10787. /**
  10788. * Convenience method for configuring a read-only node access.
  10789. *
  10790. * @return {StorageBufferNode} A reference to this node.
  10791. */
  10792. toReadOnly() {
  10793. return this.setAccess( NodeAccess.READ_ONLY );
  10794. }
  10795. /**
  10796. * Defines whether the node is atomic or not.
  10797. *
  10798. * @param {boolean} value - The atomic flag.
  10799. * @return {StorageBufferNode} A reference to this node.
  10800. */
  10801. setAtomic( value ) {
  10802. this.isAtomic = value;
  10803. return this;
  10804. }
  10805. /**
  10806. * Convenience method for making this node atomic.
  10807. *
  10808. * @return {StorageBufferNode} A reference to this node.
  10809. */
  10810. toAtomic() {
  10811. return this.setAtomic( true );
  10812. }
  10813. /**
  10814. * Returns attribute data for this storage buffer node.
  10815. *
  10816. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  10817. */
  10818. getAttributeData() {
  10819. if ( this._attribute === null ) {
  10820. this._attribute = bufferAttribute( this.value );
  10821. this._varying = varying( this._attribute );
  10822. }
  10823. return {
  10824. attribute: this._attribute,
  10825. varying: this._varying
  10826. };
  10827. }
  10828. /**
  10829. * This method is overwritten since the node type from the availability of storage buffers
  10830. * and the attribute data.
  10831. *
  10832. * @param {NodeBuilder} builder - The current node builder.
  10833. * @return {string} The node type.
  10834. */
  10835. getNodeType( builder ) {
  10836. if ( this.structTypeNode !== null ) {
  10837. return this.structTypeNode.getNodeType( builder );
  10838. }
  10839. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10840. return super.getNodeType( builder );
  10841. }
  10842. const { attribute } = this.getAttributeData();
  10843. return attribute.getNodeType( builder );
  10844. }
  10845. /**
  10846. * Returns the type of a member of the struct.
  10847. *
  10848. * @param {NodeBuilder} builder - The current node builder.
  10849. * @param {string} name - The name of the member.
  10850. * @return {string} The type of the member.
  10851. */
  10852. getMemberType( builder, name ) {
  10853. if ( this.structTypeNode !== null ) {
  10854. return this.structTypeNode.getMemberType( builder, name );
  10855. }
  10856. return 'void';
  10857. }
  10858. /**
  10859. * Generates the code snippet of the storage buffer node.
  10860. *
  10861. * @param {NodeBuilder} builder - The current node builder.
  10862. * @return {string} The generated code snippet.
  10863. */
  10864. generate( builder ) {
  10865. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  10866. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10867. return super.generate( builder );
  10868. }
  10869. const { attribute, varying } = this.getAttributeData();
  10870. const output = varying.build( builder );
  10871. builder.registerTransform( output, attribute );
  10872. return output;
  10873. }
  10874. }
  10875. /**
  10876. * TSL function for creating a storage buffer node.
  10877. *
  10878. * @tsl
  10879. * @function
  10880. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10881. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  10882. * @param {number} [count=0] - The buffer count.
  10883. * @returns {StorageBufferNode}
  10884. */
  10885. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  10886. /**
  10887. * @tsl
  10888. * @function
  10889. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  10890. *
  10891. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10892. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  10893. * @param {number} count - The buffer count.
  10894. * @returns {StorageBufferNode}
  10895. */
  10896. const storageObject = ( value, type, count ) => { // @deprecated, r171
  10897. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  10898. return storage( value, type, count ).setPBO( true );
  10899. };
  10900. const _frameId = new WeakMap();
  10901. /**
  10902. * This node implements the vertex transformation shader logic which is required
  10903. * for skinning/skeletal animation.
  10904. *
  10905. * @augments Node
  10906. */
  10907. class SkinningNode extends Node {
  10908. static get type() {
  10909. return 'SkinningNode';
  10910. }
  10911. /**
  10912. * Constructs a new skinning node.
  10913. *
  10914. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10915. */
  10916. constructor( skinnedMesh ) {
  10917. super( 'void' );
  10918. /**
  10919. * The skinned mesh.
  10920. *
  10921. * @type {SkinnedMesh}
  10922. */
  10923. this.skinnedMesh = skinnedMesh;
  10924. /**
  10925. * The update type overwritten since skinning nodes are updated per object.
  10926. *
  10927. * @type {string}
  10928. */
  10929. this.updateType = NodeUpdateType.OBJECT;
  10930. //
  10931. /**
  10932. * The skin index attribute.
  10933. *
  10934. * @type {AttributeNode}
  10935. */
  10936. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  10937. /**
  10938. * The skin weight attribute.
  10939. *
  10940. * @type {AttributeNode}
  10941. */
  10942. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  10943. /**
  10944. * The bind matrix node.
  10945. *
  10946. * @type {Node<mat4>}
  10947. */
  10948. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  10949. /**
  10950. * The bind matrix inverse node.
  10951. *
  10952. * @type {Node<mat4>}
  10953. */
  10954. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  10955. /**
  10956. * The bind matrices as a uniform buffer node.
  10957. *
  10958. * @type {Node}
  10959. */
  10960. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  10961. /**
  10962. * The current vertex position in local space.
  10963. *
  10964. * @type {Node<vec3>}
  10965. */
  10966. this.positionNode = positionLocal;
  10967. /**
  10968. * The result of vertex position in local space.
  10969. *
  10970. * @type {Node<vec3>}
  10971. */
  10972. this.toPositionNode = positionLocal;
  10973. /**
  10974. * The previous bind matrices as a uniform buffer node.
  10975. * Required for computing motion vectors.
  10976. *
  10977. * @type {?Node}
  10978. * @default null
  10979. */
  10980. this.previousBoneMatricesNode = null;
  10981. }
  10982. /**
  10983. * Transforms the given vertex position via skinning.
  10984. *
  10985. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  10986. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  10987. * @return {Node<vec3>} The transformed vertex position.
  10988. */
  10989. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  10990. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  10991. const boneMatX = boneMatrices.element( skinIndexNode.x );
  10992. const boneMatY = boneMatrices.element( skinIndexNode.y );
  10993. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  10994. const boneMatW = boneMatrices.element( skinIndexNode.w );
  10995. // POSITION
  10996. const skinVertex = bindMatrixNode.mul( position );
  10997. const skinned = add(
  10998. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  10999. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  11000. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  11001. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  11002. );
  11003. return bindMatrixInverseNode.mul( skinned ).xyz;
  11004. }
  11005. /**
  11006. * Transforms the given vertex normal via skinning.
  11007. *
  11008. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11009. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  11010. * @return {Node<vec3>} The transformed vertex normal.
  11011. */
  11012. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  11013. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11014. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11015. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11016. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11017. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11018. // NORMAL
  11019. let skinMatrix = add(
  11020. skinWeightNode.x.mul( boneMatX ),
  11021. skinWeightNode.y.mul( boneMatY ),
  11022. skinWeightNode.z.mul( boneMatZ ),
  11023. skinWeightNode.w.mul( boneMatW )
  11024. );
  11025. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  11026. return skinMatrix.transformDirection( normal ).xyz;
  11027. }
  11028. /**
  11029. * Computes the transformed/skinned vertex position of the previous frame.
  11030. *
  11031. * @param {NodeBuilder} builder - The current node builder.
  11032. * @return {Node<vec3>} The skinned position from the previous frame.
  11033. */
  11034. getPreviousSkinnedPosition( builder ) {
  11035. const skinnedMesh = builder.object;
  11036. if ( this.previousBoneMatricesNode === null ) {
  11037. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  11038. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11039. }
  11040. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  11041. }
  11042. /**
  11043. * Returns `true` if bone matrices from the previous frame are required. Relevant
  11044. * when computing motion vectors with {@link VelocityNode}.
  11045. *
  11046. * @param {NodeBuilder} builder - The current node builder.
  11047. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  11048. */
  11049. needsPreviousBoneMatrices( builder ) {
  11050. const mrt = builder.renderer.getMRT();
  11051. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  11052. }
  11053. /**
  11054. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  11055. *
  11056. * @param {NodeBuilder} builder - The current node builder.
  11057. * @return {Node<vec3>} The transformed vertex position.
  11058. */
  11059. setup( builder ) {
  11060. if ( this.needsPreviousBoneMatrices( builder ) ) {
  11061. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  11062. }
  11063. const skinPosition = this.getSkinnedPosition();
  11064. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  11065. //
  11066. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11067. const skinNormal = this.getSkinnedNormal();
  11068. normalLocal.assign( skinNormal );
  11069. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11070. tangentLocal.assign( skinNormal );
  11071. }
  11072. }
  11073. return skinPosition;
  11074. }
  11075. /**
  11076. * Generates the code snippet of the skinning node.
  11077. *
  11078. * @param {NodeBuilder} builder - The current node builder.
  11079. * @param {string} output - The current output.
  11080. * @return {string} The generated code snippet.
  11081. */
  11082. generate( builder, output ) {
  11083. if ( output !== 'void' ) {
  11084. return super.generate( builder, output );
  11085. }
  11086. }
  11087. /**
  11088. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  11089. *
  11090. * @param {NodeFrame} frame - The current node frame.
  11091. */
  11092. update( frame ) {
  11093. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  11094. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  11095. _frameId.set( skeleton, frame.frameId );
  11096. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  11097. skeleton.update();
  11098. }
  11099. }
  11100. /**
  11101. * TSL function for creating a skinning node.
  11102. *
  11103. * @tsl
  11104. * @function
  11105. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11106. * @returns {SkinningNode}
  11107. */
  11108. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  11109. /**
  11110. * TSL function for computing skinning.
  11111. *
  11112. * @tsl
  11113. * @function
  11114. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11115. * @param {Node<vec3>} [toPosition=null] - The target position.
  11116. * @returns {SkinningNode}
  11117. */
  11118. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  11119. const node = new SkinningNode( skinnedMesh );
  11120. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11121. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11122. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11123. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  11124. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  11125. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  11126. node.toPositionNode = toPosition;
  11127. return nodeObject( node );
  11128. };
  11129. /**
  11130. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  11131. * ```js
  11132. * Loop( count, ( { i } ) => {
  11133. *
  11134. * } );
  11135. * ```
  11136. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  11137. * ```js
  11138. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  11139. *
  11140. * } );
  11141. *```
  11142. * Nested loops can be defined in a compacted form:
  11143. * ```js
  11144. * Loop( 10, 5, ( { i, j } ) => {
  11145. *
  11146. * } );
  11147. * ```
  11148. * Loops that should run backwards can be defined like so:
  11149. * ```js
  11150. * Loop( { start: 10 }, () => {} );
  11151. * ```
  11152. * It is possible to execute with boolean values, similar to the `while` syntax.
  11153. * ```js
  11154. * const value = float( 0 ).toVar();
  11155. *
  11156. * Loop( value.lessThan( 10 ), () => {
  11157. *
  11158. * value.addAssign( 1 );
  11159. *
  11160. * } );
  11161. * ```
  11162. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  11163. * @augments Node
  11164. */
  11165. class LoopNode extends Node {
  11166. static get type() {
  11167. return 'LoopNode';
  11168. }
  11169. /**
  11170. * Constructs a new loop node.
  11171. *
  11172. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  11173. */
  11174. constructor( params = [] ) {
  11175. super();
  11176. this.params = params;
  11177. }
  11178. /**
  11179. * Returns a loop variable name based on an index. The pattern is
  11180. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  11181. *
  11182. * @param {number} index - The index.
  11183. * @return {string} The loop variable name.
  11184. */
  11185. getVarName( index ) {
  11186. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  11187. }
  11188. /**
  11189. * Returns properties about this node.
  11190. *
  11191. * @param {NodeBuilder} builder - The current node builder.
  11192. * @return {Object} The node properties.
  11193. */
  11194. getProperties( builder ) {
  11195. const properties = builder.getNodeProperties( this );
  11196. if ( properties.stackNode !== undefined ) return properties;
  11197. //
  11198. const inputs = {};
  11199. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11200. const param = this.params[ i ];
  11201. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  11202. const type = ( param.isNode !== true && param.type ) || 'int';
  11203. inputs[ name ] = expression( name, type );
  11204. }
  11205. const stack = builder.addStack(); // TODO: cache() it
  11206. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  11207. properties.stackNode = stack;
  11208. const baseParam = this.params[ 0 ];
  11209. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  11210. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  11211. }
  11212. builder.removeStack();
  11213. return properties;
  11214. }
  11215. /**
  11216. * This method is overwritten since the node type is inferred based on the loop configuration.
  11217. *
  11218. * @param {NodeBuilder} builder - The current node builder.
  11219. * @return {string} The node type.
  11220. */
  11221. getNodeType( builder ) {
  11222. const { returnsNode } = this.getProperties( builder );
  11223. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  11224. }
  11225. setup( builder ) {
  11226. // setup properties
  11227. this.getProperties( builder );
  11228. }
  11229. generate( builder ) {
  11230. const properties = this.getProperties( builder );
  11231. const params = this.params;
  11232. const stackNode = properties.stackNode;
  11233. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  11234. const param = params[ i ];
  11235. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  11236. if ( param.isNode ) {
  11237. if ( param.getNodeType( builder ) === 'bool' ) {
  11238. isWhile = true;
  11239. type = 'bool';
  11240. end = param.build( builder, type );
  11241. } else {
  11242. type = 'int';
  11243. name = this.getVarName( i );
  11244. start = '0';
  11245. end = param.build( builder, type );
  11246. condition = '<';
  11247. }
  11248. } else {
  11249. type = param.type || 'int';
  11250. name = param.name || this.getVarName( i );
  11251. start = param.start;
  11252. end = param.end;
  11253. condition = param.condition;
  11254. update = param.update;
  11255. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  11256. else if ( start && start.isNode ) start = start.build( builder, type );
  11257. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  11258. else if ( end && end.isNode ) end = end.build( builder, type );
  11259. if ( start !== undefined && end === undefined ) {
  11260. start = start + ' - 1';
  11261. end = '0';
  11262. condition = '>=';
  11263. } else if ( end !== undefined && start === undefined ) {
  11264. start = '0';
  11265. condition = '<';
  11266. }
  11267. if ( condition === undefined ) {
  11268. if ( Number( start ) > Number( end ) ) {
  11269. condition = '>=';
  11270. } else {
  11271. condition = '<';
  11272. }
  11273. }
  11274. }
  11275. let loopSnippet;
  11276. if ( isWhile ) {
  11277. loopSnippet = `while ( ${ end } )`;
  11278. } else {
  11279. const internalParam = { start, end};
  11280. //
  11281. const startSnippet = internalParam.start;
  11282. const endSnippet = internalParam.end;
  11283. let updateSnippet;
  11284. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  11285. if ( update !== undefined && update !== null ) {
  11286. switch ( typeof update ) {
  11287. case 'function':
  11288. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  11289. const snippet = flow.code.replace( /\t|;/g, '' );
  11290. updateSnippet = snippet;
  11291. break;
  11292. case 'number':
  11293. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  11294. break;
  11295. case 'string':
  11296. updateSnippet = name + ' ' + update;
  11297. break;
  11298. default:
  11299. if ( update.isNode ) {
  11300. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  11301. } else {
  11302. console.error( 'THREE.TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  11303. updateSnippet = 'break /* invalid update */';
  11304. }
  11305. }
  11306. } else {
  11307. if ( type === 'int' || type === 'uint' ) {
  11308. update = condition.includes( '<' ) ? '++' : '--';
  11309. } else {
  11310. update = deltaOperator() + ' 1.';
  11311. }
  11312. updateSnippet = name + ' ' + update;
  11313. }
  11314. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  11315. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  11316. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  11317. }
  11318. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  11319. }
  11320. const stackSnippet = stackNode.build( builder, 'void' );
  11321. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  11322. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  11323. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11324. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  11325. }
  11326. builder.addFlowTab();
  11327. return returnsSnippet;
  11328. }
  11329. }
  11330. /**
  11331. * TSL function for creating a loop node.
  11332. *
  11333. * @tsl
  11334. * @function
  11335. * @param {...any} params - A list of parameters.
  11336. * @returns {LoopNode}
  11337. */
  11338. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).toStack();
  11339. /**
  11340. * TSL function for creating a `Continue()` expression.
  11341. *
  11342. * @tsl
  11343. * @function
  11344. * @returns {ExpressionNode}
  11345. */
  11346. const Continue = () => expression( 'continue' ).toStack();
  11347. /**
  11348. * TSL function for creating a `Break()` expression.
  11349. *
  11350. * @tsl
  11351. * @function
  11352. * @returns {ExpressionNode}
  11353. */
  11354. const Break = () => expression( 'break' ).toStack();
  11355. // Deprecated
  11356. /**
  11357. * @tsl
  11358. * @function
  11359. * @deprecated since r168. Use {@link Loop} instead.
  11360. *
  11361. * @param {...any} params
  11362. * @returns {LoopNode}
  11363. */
  11364. const loop = ( ...params ) => { // @deprecated, r168
  11365. console.warn( 'THREE.TSL: loop() has been renamed to Loop().' );
  11366. return Loop( ...params );
  11367. };
  11368. const _morphTextures = /*@__PURE__*/ new WeakMap();
  11369. const _morphVec4 = /*@__PURE__*/ new Vector4();
  11370. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  11371. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  11372. const y = texelIndex.div( width );
  11373. const x = texelIndex.sub( y.mul( width ) );
  11374. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  11375. return bufferAttrib.mul( influence );
  11376. } );
  11377. function getEntry( geometry ) {
  11378. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11379. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  11380. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  11381. // instead of using attributes, the WebGL 2 code path encodes morph targets
  11382. // into an array of data textures. Each layer represents a single morph target.
  11383. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11384. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11385. let entry = _morphTextures.get( geometry );
  11386. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  11387. if ( entry !== undefined ) entry.texture.dispose();
  11388. const morphTargets = geometry.morphAttributes.position || [];
  11389. const morphNormals = geometry.morphAttributes.normal || [];
  11390. const morphColors = geometry.morphAttributes.color || [];
  11391. let vertexDataCount = 0;
  11392. if ( hasMorphPosition === true ) vertexDataCount = 1;
  11393. if ( hasMorphNormals === true ) vertexDataCount = 2;
  11394. if ( hasMorphColors === true ) vertexDataCount = 3;
  11395. let width = geometry.attributes.position.count * vertexDataCount;
  11396. let height = 1;
  11397. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  11398. if ( width > maxTextureSize ) {
  11399. height = Math.ceil( width / maxTextureSize );
  11400. width = maxTextureSize;
  11401. }
  11402. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  11403. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  11404. bufferTexture.type = FloatType;
  11405. bufferTexture.needsUpdate = true;
  11406. // fill buffer
  11407. const vertexDataStride = vertexDataCount * 4;
  11408. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  11409. const morphTarget = morphTargets[ i ];
  11410. const morphNormal = morphNormals[ i ];
  11411. const morphColor = morphColors[ i ];
  11412. const offset = width * height * 4 * i;
  11413. for ( let j = 0; j < morphTarget.count; j ++ ) {
  11414. const stride = j * vertexDataStride;
  11415. if ( hasMorphPosition === true ) {
  11416. _morphVec4.fromBufferAttribute( morphTarget, j );
  11417. buffer[ offset + stride + 0 ] = _morphVec4.x;
  11418. buffer[ offset + stride + 1 ] = _morphVec4.y;
  11419. buffer[ offset + stride + 2 ] = _morphVec4.z;
  11420. buffer[ offset + stride + 3 ] = 0;
  11421. }
  11422. if ( hasMorphNormals === true ) {
  11423. _morphVec4.fromBufferAttribute( morphNormal, j );
  11424. buffer[ offset + stride + 4 ] = _morphVec4.x;
  11425. buffer[ offset + stride + 5 ] = _morphVec4.y;
  11426. buffer[ offset + stride + 6 ] = _morphVec4.z;
  11427. buffer[ offset + stride + 7 ] = 0;
  11428. }
  11429. if ( hasMorphColors === true ) {
  11430. _morphVec4.fromBufferAttribute( morphColor, j );
  11431. buffer[ offset + stride + 8 ] = _morphVec4.x;
  11432. buffer[ offset + stride + 9 ] = _morphVec4.y;
  11433. buffer[ offset + stride + 10 ] = _morphVec4.z;
  11434. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  11435. }
  11436. }
  11437. }
  11438. entry = {
  11439. count: morphTargetsCount,
  11440. texture: bufferTexture,
  11441. stride: vertexDataCount,
  11442. size: new Vector2( width, height )
  11443. };
  11444. _morphTextures.set( geometry, entry );
  11445. function disposeTexture() {
  11446. bufferTexture.dispose();
  11447. _morphTextures.delete( geometry );
  11448. geometry.removeEventListener( 'dispose', disposeTexture );
  11449. }
  11450. geometry.addEventListener( 'dispose', disposeTexture );
  11451. }
  11452. return entry;
  11453. }
  11454. /**
  11455. * This node implements the vertex transformation shader logic which is required
  11456. * for morph target animation.
  11457. *
  11458. * @augments Node
  11459. */
  11460. class MorphNode extends Node {
  11461. static get type() {
  11462. return 'MorphNode';
  11463. }
  11464. /**
  11465. * Constructs a new morph node.
  11466. *
  11467. * @param {Mesh} mesh - The mesh holding the morph targets.
  11468. */
  11469. constructor( mesh ) {
  11470. super( 'void' );
  11471. /**
  11472. * The mesh holding the morph targets.
  11473. *
  11474. * @type {Mesh}
  11475. */
  11476. this.mesh = mesh;
  11477. /**
  11478. * A uniform node which represents the morph base influence value.
  11479. *
  11480. * @type {UniformNode<float>}
  11481. */
  11482. this.morphBaseInfluence = uniform( 1 );
  11483. /**
  11484. * The update type overwritten since morph nodes are updated per object.
  11485. *
  11486. * @type {string}
  11487. */
  11488. this.updateType = NodeUpdateType.OBJECT;
  11489. }
  11490. /**
  11491. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  11492. *
  11493. * @param {NodeBuilder} builder - The current node builder.
  11494. */
  11495. setup( builder ) {
  11496. const { geometry } = builder;
  11497. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11498. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  11499. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11500. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11501. // nodes
  11502. const { texture: bufferMap, stride, size } = getEntry( geometry );
  11503. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  11504. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  11505. const width = int( size.width );
  11506. Loop( morphTargetsCount, ( { i } ) => {
  11507. const influence = float( 0 ).toVar();
  11508. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  11509. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  11510. } else {
  11511. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  11512. }
  11513. If( influence.notEqual( 0 ), () => {
  11514. if ( hasMorphPosition === true ) {
  11515. positionLocal.addAssign( getMorph( {
  11516. bufferMap,
  11517. influence,
  11518. stride,
  11519. width,
  11520. depth: i,
  11521. offset: int( 0 )
  11522. } ) );
  11523. }
  11524. if ( hasMorphNormals === true ) {
  11525. normalLocal.addAssign( getMorph( {
  11526. bufferMap,
  11527. influence,
  11528. stride,
  11529. width,
  11530. depth: i,
  11531. offset: int( 1 )
  11532. } ) );
  11533. }
  11534. } );
  11535. } );
  11536. }
  11537. /**
  11538. * Updates the state of the morphed mesh by updating the base influence.
  11539. *
  11540. * @param {NodeFrame} frame - The current node frame.
  11541. */
  11542. update( /*frame*/ ) {
  11543. const morphBaseInfluence = this.morphBaseInfluence;
  11544. if ( this.mesh.geometry.morphTargetsRelative ) {
  11545. morphBaseInfluence.value = 1;
  11546. } else {
  11547. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  11548. }
  11549. }
  11550. }
  11551. /**
  11552. * TSL function for creating a morph node.
  11553. *
  11554. * @tsl
  11555. * @function
  11556. * @param {Mesh} mesh - The mesh holding the morph targets.
  11557. * @returns {MorphNode}
  11558. */
  11559. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  11560. /**
  11561. * Base class for lighting nodes.
  11562. *
  11563. * @augments Node
  11564. */
  11565. class LightingNode extends Node {
  11566. static get type() {
  11567. return 'LightingNode';
  11568. }
  11569. /**
  11570. * Constructs a new lighting node.
  11571. */
  11572. constructor() {
  11573. super( 'vec3' );
  11574. /**
  11575. * This flag can be used for type testing.
  11576. *
  11577. * @type {boolean}
  11578. * @readonly
  11579. * @default true
  11580. */
  11581. this.isLightingNode = true;
  11582. }
  11583. }
  11584. /**
  11585. * A generic class that can be used by nodes which contribute
  11586. * ambient occlusion to the scene. E.g. an ambient occlusion map
  11587. * node can be used as input for this module. Used in {@link NodeMaterial}.
  11588. *
  11589. * @augments LightingNode
  11590. */
  11591. class AONode extends LightingNode {
  11592. static get type() {
  11593. return 'AONode';
  11594. }
  11595. /**
  11596. * Constructs a new AO node.
  11597. *
  11598. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  11599. */
  11600. constructor( aoNode = null ) {
  11601. super();
  11602. /**
  11603. * The ambient occlusion node.
  11604. *
  11605. * @type {?Node<float>}
  11606. * @default null
  11607. */
  11608. this.aoNode = aoNode;
  11609. }
  11610. setup( builder ) {
  11611. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  11612. }
  11613. }
  11614. /**
  11615. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  11616. * by adding lighting specific context data. It represents the runtime context of
  11617. * {@link LightsNode}.
  11618. *
  11619. * @augments ContextNode
  11620. */
  11621. class LightingContextNode extends ContextNode {
  11622. static get type() {
  11623. return 'LightingContextNode';
  11624. }
  11625. /**
  11626. * Constructs a new lighting context node.
  11627. *
  11628. * @param {LightsNode} lightsNode - The lights node.
  11629. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  11630. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  11631. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  11632. */
  11633. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  11634. super( lightsNode );
  11635. /**
  11636. * The current lighting model.
  11637. *
  11638. * @type {?LightingModel}
  11639. * @default null
  11640. */
  11641. this.lightingModel = lightingModel;
  11642. /**
  11643. * A backdrop node.
  11644. *
  11645. * @type {?Node<vec3>}
  11646. * @default null
  11647. */
  11648. this.backdropNode = backdropNode;
  11649. /**
  11650. * A backdrop alpha node.
  11651. *
  11652. * @type {?Node<float>}
  11653. * @default null
  11654. */
  11655. this.backdropAlphaNode = backdropAlphaNode;
  11656. this._value = null;
  11657. }
  11658. /**
  11659. * Returns a lighting context object.
  11660. *
  11661. * @return {{
  11662. * radiance: Node<vec3>,
  11663. * irradiance: Node<vec3>,
  11664. * iblIrradiance: Node<vec3>,
  11665. * ambientOcclusion: Node<float>,
  11666. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  11667. * backdrop: Node<vec3>,
  11668. * backdropAlpha: Node<float>
  11669. * }} The lighting context object.
  11670. */
  11671. getContext() {
  11672. const { backdropNode, backdropAlphaNode } = this;
  11673. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  11674. directSpecular = vec3().toVar( 'directSpecular' ),
  11675. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  11676. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  11677. const reflectedLight = {
  11678. directDiffuse,
  11679. directSpecular,
  11680. indirectDiffuse,
  11681. indirectSpecular
  11682. };
  11683. const context = {
  11684. radiance: vec3().toVar( 'radiance' ),
  11685. irradiance: vec3().toVar( 'irradiance' ),
  11686. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  11687. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  11688. reflectedLight,
  11689. backdrop: backdropNode,
  11690. backdropAlpha: backdropAlphaNode
  11691. };
  11692. return context;
  11693. }
  11694. setup( builder ) {
  11695. this.value = this._value || ( this._value = this.getContext() );
  11696. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  11697. return super.setup( builder );
  11698. }
  11699. }
  11700. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  11701. /**
  11702. * A generic class that can be used by nodes which contribute
  11703. * irradiance to the scene. E.g. a light map node can be used
  11704. * as input for this module. Used in {@link NodeMaterial}.
  11705. *
  11706. * @augments LightingNode
  11707. */
  11708. class IrradianceNode extends LightingNode {
  11709. static get type() {
  11710. return 'IrradianceNode';
  11711. }
  11712. /**
  11713. * Constructs a new irradiance node.
  11714. *
  11715. * @param {Node<vec3>} node - A node contributing irradiance.
  11716. */
  11717. constructor( node ) {
  11718. super();
  11719. /**
  11720. * A node contributing irradiance.
  11721. *
  11722. * @type {Node<vec3>}
  11723. */
  11724. this.node = node;
  11725. }
  11726. setup( builder ) {
  11727. builder.context.irradiance.addAssign( this.node );
  11728. }
  11729. }
  11730. let screenSizeVec, viewportVec;
  11731. /**
  11732. * This node provides a collection of screen related metrics.
  11733. * Depending on {@link ScreenNode#scope}, the nodes can represent
  11734. * resolution or viewport data as well as fragment or uv coordinates.
  11735. *
  11736. * @augments Node
  11737. */
  11738. class ScreenNode extends Node {
  11739. static get type() {
  11740. return 'ScreenNode';
  11741. }
  11742. /**
  11743. * Constructs a new screen node.
  11744. *
  11745. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  11746. */
  11747. constructor( scope ) {
  11748. super();
  11749. /**
  11750. * The node represents different metric depending on which scope is selected.
  11751. *
  11752. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  11753. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  11754. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  11755. * - `ScreenNode.UV`: Normalized coordinates.
  11756. *
  11757. * @type {('coordinate'|'viewport'|'size'|'uv')}
  11758. */
  11759. this.scope = scope;
  11760. /**
  11761. * This flag can be used for type testing.
  11762. *
  11763. * @type {boolean}
  11764. * @readonly
  11765. * @default true
  11766. */
  11767. this.isViewportNode = true;
  11768. }
  11769. /**
  11770. * This method is overwritten since the node type depends on the selected scope.
  11771. *
  11772. * @return {('vec2'|'vec4')} The node type.
  11773. */
  11774. getNodeType() {
  11775. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  11776. else return 'vec2';
  11777. }
  11778. /**
  11779. * This method is overwritten since the node's update type depends on the selected scope.
  11780. *
  11781. * @return {NodeUpdateType} The update type.
  11782. */
  11783. getUpdateType() {
  11784. let updateType = NodeUpdateType.NONE;
  11785. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  11786. updateType = NodeUpdateType.RENDER;
  11787. }
  11788. this.updateType = updateType;
  11789. return updateType;
  11790. }
  11791. /**
  11792. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  11793. * from the current renderer.
  11794. *
  11795. * @param {NodeFrame} frame - A reference to the current node frame.
  11796. */
  11797. update( { renderer } ) {
  11798. const renderTarget = renderer.getRenderTarget();
  11799. if ( this.scope === ScreenNode.VIEWPORT ) {
  11800. if ( renderTarget !== null ) {
  11801. viewportVec.copy( renderTarget.viewport );
  11802. } else {
  11803. renderer.getViewport( viewportVec );
  11804. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  11805. }
  11806. } else {
  11807. if ( renderTarget !== null ) {
  11808. screenSizeVec.width = renderTarget.width;
  11809. screenSizeVec.height = renderTarget.height;
  11810. } else {
  11811. renderer.getDrawingBufferSize( screenSizeVec );
  11812. }
  11813. }
  11814. }
  11815. setup( /*builder*/ ) {
  11816. const scope = this.scope;
  11817. let output = null;
  11818. if ( scope === ScreenNode.SIZE ) {
  11819. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  11820. } else if ( scope === ScreenNode.VIEWPORT ) {
  11821. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  11822. } else {
  11823. output = vec2( screenCoordinate.div( screenSize ) );
  11824. }
  11825. return output;
  11826. }
  11827. generate( builder ) {
  11828. if ( this.scope === ScreenNode.COORDINATE ) {
  11829. let coord = builder.getFragCoord();
  11830. if ( builder.isFlipY() ) {
  11831. // follow webgpu standards
  11832. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  11833. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  11834. }
  11835. return coord;
  11836. }
  11837. return super.generate( builder );
  11838. }
  11839. }
  11840. ScreenNode.COORDINATE = 'coordinate';
  11841. ScreenNode.VIEWPORT = 'viewport';
  11842. ScreenNode.SIZE = 'size';
  11843. ScreenNode.UV = 'uv';
  11844. // Screen
  11845. /**
  11846. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  11847. *
  11848. * @tsl
  11849. * @type {ScreenNode<vec2>}
  11850. */
  11851. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  11852. /**
  11853. * TSL object that represents the screen resolution in physical pixel units.
  11854. *
  11855. * @tsl
  11856. * @type {ScreenNode<vec2>}
  11857. */
  11858. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  11859. /**
  11860. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  11861. *
  11862. * @tsl
  11863. * @type {ScreenNode<vec2>}
  11864. */
  11865. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  11866. // Viewport
  11867. /**
  11868. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  11869. *
  11870. * @tsl
  11871. * @type {ScreenNode<vec4>}
  11872. */
  11873. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  11874. /**
  11875. * TSL object that represents the viewport resolution in physical pixel units.
  11876. *
  11877. * @tsl
  11878. * @type {ScreenNode<vec2>}
  11879. */
  11880. const viewportSize = viewport.zw;
  11881. /**
  11882. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  11883. *
  11884. * @tsl
  11885. * @type {ScreenNode<vec2>}
  11886. */
  11887. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  11888. /**
  11889. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  11890. *
  11891. * @tsl
  11892. * @type {ScreenNode<vec2>}
  11893. */
  11894. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  11895. // Deprecated
  11896. /**
  11897. * @deprecated since r169. Use {@link screenSize} instead.
  11898. */
  11899. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  11900. console.warn( 'THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  11901. return screenSize;
  11902. }, 'vec2' ).once() )();
  11903. /**
  11904. * @tsl
  11905. * @deprecated since r168. Use {@link screenUV} instead.
  11906. * @type {Node<vec2>}
  11907. */
  11908. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  11909. console.warn( 'THREE.TSL: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  11910. return screenUV;
  11911. }, 'vec2' ).once() )();
  11912. /**
  11913. * @tsl
  11914. * @deprecated since r168. Use `screenUV.flipY()` instead.
  11915. * @type {Node<vec2>}
  11916. */
  11917. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  11918. console.warn( 'THREE.TSL: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  11919. return screenUV.flipY();
  11920. }, 'vec2' ).once() )();
  11921. const _size$4 = /*@__PURE__*/ new Vector2();
  11922. /**
  11923. * A special type of texture node which represents the data of the current viewport
  11924. * as a texture. The module extracts data from the current bound framebuffer with
  11925. * a copy operation so no extra render pass is required to produce the texture data
  11926. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  11927. * variety of effects like refractive or transmissive materials.
  11928. *
  11929. * @augments TextureNode
  11930. */
  11931. class ViewportTextureNode extends TextureNode {
  11932. static get type() {
  11933. return 'ViewportTextureNode';
  11934. }
  11935. /**
  11936. * Constructs a new viewport texture node.
  11937. *
  11938. * @param {Node} [uvNode=screenUV] - The uv node.
  11939. * @param {?Node} [levelNode=null] - The level node.
  11940. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  11941. */
  11942. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  11943. if ( framebufferTexture === null ) {
  11944. framebufferTexture = new FramebufferTexture();
  11945. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  11946. }
  11947. super( framebufferTexture, uvNode, levelNode );
  11948. /**
  11949. * Whether to generate mipmaps or not.
  11950. *
  11951. * @type {boolean}
  11952. * @default false
  11953. */
  11954. this.generateMipmaps = false;
  11955. /**
  11956. * This flag can be used for type testing.
  11957. *
  11958. * @type {boolean}
  11959. * @readonly
  11960. * @default true
  11961. */
  11962. this.isOutputTextureNode = true;
  11963. /**
  11964. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  11965. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  11966. *
  11967. * @type {string}
  11968. * @default 'frame'
  11969. */
  11970. this.updateBeforeType = NodeUpdateType.FRAME;
  11971. }
  11972. updateBefore( frame ) {
  11973. const renderer = frame.renderer;
  11974. renderer.getDrawingBufferSize( _size$4 );
  11975. //
  11976. const framebufferTexture = this.value;
  11977. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  11978. framebufferTexture.image.width = _size$4.width;
  11979. framebufferTexture.image.height = _size$4.height;
  11980. framebufferTexture.needsUpdate = true;
  11981. }
  11982. //
  11983. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  11984. framebufferTexture.generateMipmaps = this.generateMipmaps;
  11985. renderer.copyFramebufferToTexture( framebufferTexture );
  11986. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  11987. }
  11988. clone() {
  11989. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  11990. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  11991. return viewportTextureNode;
  11992. }
  11993. }
  11994. /**
  11995. * TSL function for creating a viewport texture node.
  11996. *
  11997. * @tsl
  11998. * @function
  11999. * @param {?Node} [uvNode=screenUV] - The uv node.
  12000. * @param {?Node} [levelNode=null] - The level node.
  12001. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12002. * @returns {ViewportTextureNode}
  12003. */
  12004. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  12005. /**
  12006. * TSL function for creating a viewport texture node with enabled mipmap generation.
  12007. *
  12008. * @tsl
  12009. * @function
  12010. * @param {?Node} [uvNode=screenUV] - The uv node.
  12011. * @param {?Node} [levelNode=null] - The level node.
  12012. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12013. * @returns {ViewportTextureNode}
  12014. */
  12015. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  12016. let sharedDepthbuffer = null;
  12017. /**
  12018. * Represents the depth of the current viewport as a texture. This module
  12019. * can be used in combination with viewport texture to achieve effects
  12020. * that require depth evaluation.
  12021. *
  12022. * @augments ViewportTextureNode
  12023. */
  12024. class ViewportDepthTextureNode extends ViewportTextureNode {
  12025. static get type() {
  12026. return 'ViewportDepthTextureNode';
  12027. }
  12028. /**
  12029. * Constructs a new viewport depth texture node.
  12030. *
  12031. * @param {Node} [uvNode=screenUV] - The uv node.
  12032. * @param {?Node} [levelNode=null] - The level node.
  12033. */
  12034. constructor( uvNode = screenUV, levelNode = null ) {
  12035. if ( sharedDepthbuffer === null ) {
  12036. sharedDepthbuffer = new DepthTexture();
  12037. }
  12038. super( uvNode, levelNode, sharedDepthbuffer );
  12039. }
  12040. }
  12041. /**
  12042. * TSL function for a viewport depth texture node.
  12043. *
  12044. * @tsl
  12045. * @function
  12046. * @param {?Node} [uvNode=screenUV] - The uv node.
  12047. * @param {?Node} [levelNode=null] - The level node.
  12048. * @returns {ViewportDepthTextureNode}
  12049. */
  12050. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  12051. /**
  12052. * This node offers a collection of features in context of the depth logic in the fragment shader.
  12053. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  12054. * fragment or for depth evaluation purposes.
  12055. *
  12056. * @augments Node
  12057. */
  12058. class ViewportDepthNode extends Node {
  12059. static get type() {
  12060. return 'ViewportDepthNode';
  12061. }
  12062. /**
  12063. * Constructs a new viewport depth node.
  12064. *
  12065. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  12066. * @param {?Node} [valueNode=null] - The value node.
  12067. */
  12068. constructor( scope, valueNode = null ) {
  12069. super( 'float' );
  12070. /**
  12071. * The node behaves differently depending on which scope is selected.
  12072. *
  12073. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  12074. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  12075. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  12076. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  12077. *
  12078. * @type {('depth'|'depthBase'|'linearDepth')}
  12079. */
  12080. this.scope = scope;
  12081. /**
  12082. * Can be used to define a custom depth value.
  12083. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  12084. *
  12085. * @type {?Node}
  12086. * @default null
  12087. */
  12088. this.valueNode = valueNode;
  12089. /**
  12090. * This flag can be used for type testing.
  12091. *
  12092. * @type {boolean}
  12093. * @readonly
  12094. * @default true
  12095. */
  12096. this.isViewportDepthNode = true;
  12097. }
  12098. generate( builder ) {
  12099. const { scope } = this;
  12100. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12101. return builder.getFragDepth();
  12102. }
  12103. return super.generate( builder );
  12104. }
  12105. setup( { camera } ) {
  12106. const { scope } = this;
  12107. const value = this.valueNode;
  12108. let node = null;
  12109. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12110. if ( value !== null ) {
  12111. node = depthBase().assign( value );
  12112. }
  12113. } else if ( scope === ViewportDepthNode.DEPTH ) {
  12114. if ( camera.isPerspectiveCamera ) {
  12115. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  12116. } else {
  12117. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12118. }
  12119. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  12120. if ( value !== null ) {
  12121. if ( camera.isPerspectiveCamera ) {
  12122. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  12123. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  12124. } else {
  12125. node = value;
  12126. }
  12127. } else {
  12128. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12129. }
  12130. }
  12131. return node;
  12132. }
  12133. }
  12134. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  12135. ViewportDepthNode.DEPTH = 'depth';
  12136. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  12137. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  12138. /**
  12139. * TSL function for converting a viewZ value to an orthographic depth value.
  12140. *
  12141. * @tsl
  12142. * @function
  12143. * @param {Node<float>} viewZ - The viewZ node.
  12144. * @param {Node<float>} near - The camera's near value.
  12145. * @param {Node<float>} far - The camera's far value.
  12146. * @returns {Node<float>}
  12147. */
  12148. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  12149. /**
  12150. * TSL function for converting an orthographic depth value to a viewZ value.
  12151. *
  12152. * @tsl
  12153. * @function
  12154. * @param {Node<float>} depth - The orthographic depth.
  12155. * @param {Node<float>} near - The camera's near value.
  12156. * @param {Node<float>} far - The camera's far value.
  12157. * @returns {Node<float>}
  12158. */
  12159. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  12160. /**
  12161. * TSL function for converting a viewZ value to a perspective depth value.
  12162. *
  12163. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  12164. *
  12165. * @tsl
  12166. * @function
  12167. * @param {Node<float>} viewZ - The viewZ node.
  12168. * @param {Node<float>} near - The camera's near value.
  12169. * @param {Node<float>} far - The camera's far value.
  12170. * @returns {Node<float>}
  12171. */
  12172. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  12173. /**
  12174. * TSL function for converting a perspective depth value to a viewZ value.
  12175. *
  12176. * @tsl
  12177. * @function
  12178. * @param {Node<float>} depth - The perspective depth.
  12179. * @param {Node<float>} near - The camera's near value.
  12180. * @param {Node<float>} far - The camera's far value.
  12181. * @returns {Node<float>}
  12182. */
  12183. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  12184. /**
  12185. * TSL function for converting a viewZ value to a logarithmic depth value.
  12186. *
  12187. * @tsl
  12188. * @function
  12189. * @param {Node<float>} viewZ - The viewZ node.
  12190. * @param {Node<float>} near - The camera's near value.
  12191. * @param {Node<float>} far - The camera's far value.
  12192. * @returns {Node<float>}
  12193. */
  12194. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  12195. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  12196. // The final logarithmic depth formula used here is adapted from one described in an
  12197. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  12198. // which was an improvement upon an earlier formula one described in an
  12199. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  12200. // Ulrich's formula is the following:
  12201. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  12202. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  12203. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  12204. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  12205. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  12206. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  12207. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  12208. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  12209. // be used, and ultimately Ulrich's "near plane" version was chosen.
  12210. // Outerra eventually made another improvement to their original "C-constant" variant,
  12211. // but it still does not incorporate the camera near plane (for this version,
  12212. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  12213. // Here we make 4 changes to Ulrich's formula:
  12214. // 1. Clamp the camera near plane so we don't divide by 0.
  12215. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  12216. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  12217. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  12218. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  12219. // so we do the same here, hence the 'viewZ.negate()' call.
  12220. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  12221. near = near.max( 1e-6 ).toVar();
  12222. const numerator = log2( viewZ.negate().div( near ) );
  12223. const denominator = log2( far.div( near ) );
  12224. return numerator.div( denominator );
  12225. };
  12226. /**
  12227. * TSL function for converting a logarithmic depth value to a viewZ value.
  12228. *
  12229. * @tsl
  12230. * @function
  12231. * @param {Node<float>} depth - The logarithmic depth.
  12232. * @param {Node<float>} near - The camera's near value.
  12233. * @param {Node<float>} far - The camera's far value.
  12234. * @returns {Node<float>}
  12235. */
  12236. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  12237. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  12238. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  12239. // a negative viewZ).
  12240. const exponent = depth.mul( log( far.div( near ) ) );
  12241. return float( Math.E ).pow( exponent ).mul( near ).negate();
  12242. };
  12243. /**
  12244. * TSL function for defining a value for the current fragment's depth.
  12245. *
  12246. * @tsl
  12247. * @function
  12248. * @param {Node<float>} value - The depth value to set.
  12249. * @returns {ViewportDepthNode<float>}
  12250. */
  12251. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  12252. /**
  12253. * TSL object that represents the depth value for the current fragment.
  12254. *
  12255. * @tsl
  12256. * @type {ViewportDepthNode}
  12257. */
  12258. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  12259. /**
  12260. * TSL function for converting a perspective depth value to linear depth.
  12261. *
  12262. * @tsl
  12263. * @function
  12264. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  12265. * @returns {ViewportDepthNode<float>}
  12266. */
  12267. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  12268. /**
  12269. * TSL object that represents the linear (orthographic) depth value of the current fragment
  12270. *
  12271. * @tsl
  12272. * @type {ViewportDepthNode}
  12273. */
  12274. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  12275. depth.assign = ( value ) => depthBase( value );
  12276. /**
  12277. * This node is used in {@link NodeMaterial} to setup the clipping
  12278. * which can happen hardware-accelerated (if supported) and optionally
  12279. * use alpha-to-coverage for anti-aliasing clipped edges.
  12280. *
  12281. * @augments Node
  12282. */
  12283. class ClippingNode extends Node {
  12284. static get type() {
  12285. return 'ClippingNode';
  12286. }
  12287. /**
  12288. * Constructs a new clipping node.
  12289. *
  12290. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  12291. * the selected scope influences the behavior of the node and what type of code is generated.
  12292. */
  12293. constructor( scope = ClippingNode.DEFAULT ) {
  12294. super();
  12295. /**
  12296. * The node's scope. Similar to other nodes, the selected scope influences
  12297. * the behavior of the node and what type of code is generated.
  12298. *
  12299. * @type {('default'|'hardware'|'alphaToCoverage')}
  12300. */
  12301. this.scope = scope;
  12302. }
  12303. /**
  12304. * Setups the node depending on the selected scope.
  12305. *
  12306. * @param {NodeBuilder} builder - The current node builder.
  12307. * @return {Node} The result node.
  12308. */
  12309. setup( builder ) {
  12310. super.setup( builder );
  12311. const clippingContext = builder.clippingContext;
  12312. const { intersectionPlanes, unionPlanes } = clippingContext;
  12313. this.hardwareClipping = builder.material.hardwareClipping;
  12314. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  12315. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  12316. } else if ( this.scope === ClippingNode.HARDWARE ) {
  12317. return this.setupHardwareClipping( unionPlanes, builder );
  12318. } else {
  12319. return this.setupDefault( intersectionPlanes, unionPlanes );
  12320. }
  12321. }
  12322. /**
  12323. * Setups alpha to coverage.
  12324. *
  12325. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12326. * @param {Array<Vector4>} unionPlanes - The union planes.
  12327. * @return {Node} The result node.
  12328. */
  12329. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  12330. return Fn( () => {
  12331. const distanceToPlane = float().toVar( 'distanceToPlane' );
  12332. const distanceGradient = float().toVar( 'distanceToGradient' );
  12333. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  12334. const numUnionPlanes = unionPlanes.length;
  12335. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12336. const clippingPlanes = uniformArray( unionPlanes );
  12337. Loop( numUnionPlanes, ( { i } ) => {
  12338. const plane = clippingPlanes.element( i );
  12339. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12340. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12341. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  12342. } );
  12343. }
  12344. const numIntersectionPlanes = intersectionPlanes.length;
  12345. if ( numIntersectionPlanes > 0 ) {
  12346. const clippingPlanes = uniformArray( intersectionPlanes );
  12347. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  12348. Loop( numIntersectionPlanes, ( { i } ) => {
  12349. const plane = clippingPlanes.element( i );
  12350. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12351. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12352. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  12353. } );
  12354. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  12355. }
  12356. diffuseColor.a.mulAssign( clipOpacity );
  12357. diffuseColor.a.equal( 0.0 ).discard();
  12358. } )();
  12359. }
  12360. /**
  12361. * Setups the default clipping.
  12362. *
  12363. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12364. * @param {Array<Vector4>} unionPlanes - The union planes.
  12365. * @return {Node} The result node.
  12366. */
  12367. setupDefault( intersectionPlanes, unionPlanes ) {
  12368. return Fn( () => {
  12369. const numUnionPlanes = unionPlanes.length;
  12370. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12371. const clippingPlanes = uniformArray( unionPlanes );
  12372. Loop( numUnionPlanes, ( { i } ) => {
  12373. const plane = clippingPlanes.element( i );
  12374. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  12375. } );
  12376. }
  12377. const numIntersectionPlanes = intersectionPlanes.length;
  12378. if ( numIntersectionPlanes > 0 ) {
  12379. const clippingPlanes = uniformArray( intersectionPlanes );
  12380. const clipped = bool( true ).toVar( 'clipped' );
  12381. Loop( numIntersectionPlanes, ( { i } ) => {
  12382. const plane = clippingPlanes.element( i );
  12383. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  12384. } );
  12385. clipped.discard();
  12386. }
  12387. } )();
  12388. }
  12389. /**
  12390. * Setups hardware clipping.
  12391. *
  12392. * @param {Array<Vector4>} unionPlanes - The union planes.
  12393. * @param {NodeBuilder} builder - The current node builder.
  12394. * @return {Node} The result node.
  12395. */
  12396. setupHardwareClipping( unionPlanes, builder ) {
  12397. const numUnionPlanes = unionPlanes.length;
  12398. builder.enableHardwareClipping( numUnionPlanes );
  12399. return Fn( () => {
  12400. const clippingPlanes = uniformArray( unionPlanes );
  12401. const hw_clip_distances = builtin( builder.getClipDistance() );
  12402. Loop( numUnionPlanes, ( { i } ) => {
  12403. const plane = clippingPlanes.element( i );
  12404. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  12405. hw_clip_distances.element( i ).assign( distance );
  12406. } );
  12407. } )();
  12408. }
  12409. }
  12410. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  12411. ClippingNode.DEFAULT = 'default';
  12412. ClippingNode.HARDWARE = 'hardware';
  12413. /**
  12414. * TSL function for setting up the default clipping logic.
  12415. *
  12416. * @tsl
  12417. * @function
  12418. * @returns {ClippingNode}
  12419. */
  12420. const clipping = () => nodeObject( new ClippingNode() );
  12421. /**
  12422. * TSL function for setting up alpha to coverage.
  12423. *
  12424. * @tsl
  12425. * @function
  12426. * @returns {ClippingNode}
  12427. */
  12428. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  12429. /**
  12430. * TSL function for setting up hardware-based clipping.
  12431. *
  12432. * @tsl
  12433. * @function
  12434. * @returns {ClippingNode}
  12435. */
  12436. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  12437. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  12438. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  12439. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12440. return fract( mul( 1.0e4, sin( mul( 17.0, value.x ).add( mul( 0.1, value.y ) ) ) ).mul( add( 0.1, abs( sin( mul( 13.0, value.y ).add( value.x ) ) ) ) ) );
  12441. } );
  12442. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12443. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  12444. } );
  12445. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  12446. // Find the discretized derivatives of our coordinates
  12447. const maxDeriv = max$1(
  12448. length( dFdx( position.xyz ) ),
  12449. length( dFdy( position.xyz ) )
  12450. );
  12451. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  12452. // Find two nearest log-discretized noise scales
  12453. const pixScales = vec2(
  12454. exp2( floor( log2( pixScale ) ) ),
  12455. exp2( ceil( log2( pixScale ) ) )
  12456. );
  12457. // Compute alpha thresholds at our two noise scales
  12458. const alpha = vec2(
  12459. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  12460. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  12461. );
  12462. // Factor to interpolate lerp with
  12463. const lerpFactor = fract( log2( pixScale ) );
  12464. // Interpolate alpha threshold from noise at two scales
  12465. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  12466. // Pass into CDF to compute uniformly distrib threshold
  12467. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  12468. const cases = vec3(
  12469. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  12470. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  12471. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  12472. // Find our final, uniformly distributed alpha threshold (ατ)
  12473. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  12474. // Avoids ατ == 0. Could also do ατ =1-ατ
  12475. return clamp( threshold, 1.0e-6, 1.0 );
  12476. } ).setLayout( {
  12477. name: 'getAlphaHashThreshold',
  12478. type: 'float',
  12479. inputs: [
  12480. { name: 'position', type: 'vec3' }
  12481. ]
  12482. } );
  12483. /**
  12484. * An attribute node for representing vertex colors.
  12485. *
  12486. * @augments AttributeNode
  12487. */
  12488. class VertexColorNode extends AttributeNode {
  12489. static get type() {
  12490. return 'VertexColorNode';
  12491. }
  12492. /**
  12493. * Constructs a new vertex color node.
  12494. *
  12495. * @param {number} index - The attribute index.
  12496. */
  12497. constructor( index ) {
  12498. super( null, 'vec4' );
  12499. /**
  12500. * This flag can be used for type testing.
  12501. *
  12502. * @type {boolean}
  12503. * @readonly
  12504. * @default true
  12505. */
  12506. this.isVertexColorNode = true;
  12507. /**
  12508. * The attribute index to enable more than one sets of vertex colors.
  12509. *
  12510. * @type {number}
  12511. * @default 0
  12512. */
  12513. this.index = index;
  12514. }
  12515. /**
  12516. * Overwrites the default implementation by honoring the attribute index.
  12517. *
  12518. * @param {NodeBuilder} builder - The current node builder.
  12519. * @return {string} The attribute name.
  12520. */
  12521. getAttributeName( /*builder*/ ) {
  12522. const index = this.index;
  12523. return 'color' + ( index > 0 ? index : '' );
  12524. }
  12525. generate( builder ) {
  12526. const attributeName = this.getAttributeName( builder );
  12527. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  12528. let result;
  12529. if ( geometryAttribute === true ) {
  12530. result = super.generate( builder );
  12531. } else {
  12532. // Vertex color fallback should be white
  12533. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  12534. }
  12535. return result;
  12536. }
  12537. serialize( data ) {
  12538. super.serialize( data );
  12539. data.index = this.index;
  12540. }
  12541. deserialize( data ) {
  12542. super.deserialize( data );
  12543. this.index = data.index;
  12544. }
  12545. }
  12546. /**
  12547. * TSL function for creating a reference node.
  12548. *
  12549. * @tsl
  12550. * @function
  12551. * @param {number} [index=0] - The attribute index.
  12552. * @returns {VertexColorNode}
  12553. */
  12554. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  12555. /**
  12556. * Base class for all node materials.
  12557. *
  12558. * @augments Material
  12559. */
  12560. class NodeMaterial extends Material {
  12561. static get type() {
  12562. return 'NodeMaterial';
  12563. }
  12564. /**
  12565. * Represents the type of the node material.
  12566. *
  12567. * @type {string}
  12568. */
  12569. get type() {
  12570. return this.constructor.type;
  12571. }
  12572. set type( _value ) { /* */ }
  12573. /**
  12574. * Constructs a new node material.
  12575. */
  12576. constructor() {
  12577. super();
  12578. /**
  12579. * This flag can be used for type testing.
  12580. *
  12581. * @type {boolean}
  12582. * @readonly
  12583. * @default true
  12584. */
  12585. this.isNodeMaterial = true;
  12586. /**
  12587. * Whether this material is affected by fog or not.
  12588. *
  12589. * @type {boolean}
  12590. * @default true
  12591. */
  12592. this.fog = true;
  12593. /**
  12594. * Whether this material is affected by lights or not.
  12595. *
  12596. * @type {boolean}
  12597. * @default false
  12598. */
  12599. this.lights = false;
  12600. /**
  12601. * Whether this material uses hardware clipping or not.
  12602. * This property is managed by the engine and should not be
  12603. * modified by apps.
  12604. *
  12605. * @type {boolean}
  12606. * @default false
  12607. */
  12608. this.hardwareClipping = false;
  12609. /**
  12610. * Node materials which set their `lights` property to `true`
  12611. * are affected by all lights of the scene. Sometimes selective
  12612. * lighting is wanted which means only _some_ lights in the scene
  12613. * affect a material. This can be achieved by creating an instance
  12614. * of {@link LightsNode} with a list of selective
  12615. * lights and assign the node to this property.
  12616. *
  12617. * ```js
  12618. * const customLightsNode = lights( [ light1, light2 ] );
  12619. * material.lightsNode = customLightsNode;
  12620. * ```
  12621. *
  12622. * @type {?LightsNode}
  12623. * @default null
  12624. */
  12625. this.lightsNode = null;
  12626. /**
  12627. * The environment of node materials can be defined by an environment
  12628. * map assigned to the `envMap` property or by `Scene.environment`
  12629. * if the node material is a PBR material. This node property allows to overwrite
  12630. * the default behavior and define the environment with a custom node.
  12631. *
  12632. * ```js
  12633. * material.envNode = pmremTexture( renderTarget.texture );
  12634. * ```
  12635. *
  12636. * @type {?Node<vec3>}
  12637. * @default null
  12638. */
  12639. this.envNode = null;
  12640. /**
  12641. * The lighting of node materials might be influenced by ambient occlusion.
  12642. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  12643. * and the respective `aoMapIntensity`. This node property allows to overwrite
  12644. * the default and define the ambient occlusion with a custom node instead.
  12645. *
  12646. * If you don't want to overwrite the diffuse color but modify the existing
  12647. * values instead, use {@link materialAO}.
  12648. *
  12649. * @type {?Node<float>}
  12650. * @default null
  12651. */
  12652. this.aoNode = null;
  12653. /**
  12654. * The diffuse color of node materials is by default inferred from the
  12655. * `color` and `map` properties. This node property allows to overwrite the default
  12656. * and define the diffuse color with a node instead.
  12657. *
  12658. * ```js
  12659. * material.colorNode = color( 0xff0000 ); // define red color
  12660. * ```
  12661. *
  12662. * If you don't want to overwrite the diffuse color but modify the existing
  12663. * values instead, use {@link materialColor}.
  12664. *
  12665. * ```js
  12666. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  12667. * ```
  12668. *
  12669. * @type {?Node<vec3>}
  12670. * @default null
  12671. */
  12672. this.colorNode = null;
  12673. /**
  12674. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  12675. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  12676. * and define the normals with a node instead.
  12677. *
  12678. * If you don't want to overwrite the normals but modify the existing values instead,
  12679. * use {@link materialNormal}.
  12680. *
  12681. * @type {?Node<vec3>}
  12682. * @default null
  12683. */
  12684. this.normalNode = null;
  12685. /**
  12686. * The opacity of node materials is by default inferred from the `opacity`
  12687. * and `alphaMap` properties. This node property allows to overwrite the default
  12688. * and define the opacity with a node instead.
  12689. *
  12690. * If you don't want to overwrite the normals but modify the existing
  12691. * value instead, use {@link materialOpacity}.
  12692. *
  12693. * @type {?Node<float>}
  12694. * @default null
  12695. */
  12696. this.opacityNode = null;
  12697. /**
  12698. * This node can be used to implement a variety of filter-like effects. The idea is
  12699. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  12700. * to create an arbitrary effect and then assign the node composition to this property.
  12701. * Everything behind the object using this material will now be affected by a filter.
  12702. *
  12703. * ```js
  12704. * const material = new NodeMaterial()
  12705. * material.transparent = true;
  12706. *
  12707. * // everything behind the object will be monochromatic
  12708. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  12709. * ```
  12710. *
  12711. * Backdrop computations are part of the lighting so only lit materials can use this property.
  12712. *
  12713. * @type {?Node<vec3>}
  12714. * @default null
  12715. */
  12716. this.backdropNode = null;
  12717. /**
  12718. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  12719. *
  12720. * @type {?Node<float>}
  12721. * @default null
  12722. */
  12723. this.backdropAlphaNode = null;
  12724. /**
  12725. * The alpha test of node materials is by default inferred from the `alphaTest`
  12726. * property. This node property allows to overwrite the default and define the
  12727. * alpha test with a node instead.
  12728. *
  12729. * If you don't want to overwrite the alpha test but modify the existing
  12730. * value instead, use {@link materialAlphaTest}.
  12731. *
  12732. * @type {?Node<float>}
  12733. * @default null
  12734. */
  12735. this.alphaTestNode = null;
  12736. /**
  12737. * Discards the fragment if the mask value is `false`.
  12738. *
  12739. * @type {?Node<bool>}
  12740. * @default null
  12741. */
  12742. this.maskNode = null;
  12743. /**
  12744. * The local vertex positions are computed based on multiple factors like the
  12745. * attribute data, morphing or skinning. This node property allows to overwrite
  12746. * the default and define local vertex positions with nodes instead.
  12747. *
  12748. * If you don't want to overwrite the vertex positions but modify the existing
  12749. * values instead, use {@link positionLocal}.
  12750. *
  12751. *```js
  12752. * material.positionNode = positionLocal.add( displace );
  12753. * ```
  12754. *
  12755. * @type {?Node<vec3>}
  12756. * @default null
  12757. */
  12758. this.positionNode = null;
  12759. /**
  12760. * This node property is intended for logic which modifies geometry data once or per animation step.
  12761. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  12762. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  12763. * can be implemented.
  12764. *
  12765. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  12766. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  12767. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  12768. * eventually assigned to `geometryNode`.
  12769. *
  12770. * @type {?Function}
  12771. * @default null
  12772. */
  12773. this.geometryNode = null;
  12774. /**
  12775. * Allows to overwrite depth values in the fragment shader.
  12776. *
  12777. * @type {?Node<float>}
  12778. * @default null
  12779. */
  12780. this.depthNode = null;
  12781. /**
  12782. * Allows to overwrite the position used for shadow map rendering which
  12783. * is by default {@link positionWorld}, the vertex position
  12784. * in world space.
  12785. *
  12786. * @type {?Node<float>}
  12787. * @default null
  12788. */
  12789. this.receivedShadowPositionNode = null;
  12790. /**
  12791. * Allows to overwrite the geometry position used for shadow map projection which
  12792. * is by default {@link positionLocal}, the vertex position in local space.
  12793. *
  12794. * @type {?Node<float>}
  12795. * @default null
  12796. */
  12797. this.castShadowPositionNode = null;
  12798. /**
  12799. * This node can be used to influence how an object using this node material
  12800. * receive shadows.
  12801. *
  12802. * ```js
  12803. * const totalShadows = float( 1 ).toVar();
  12804. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  12805. * totalShadows.mulAssign( shadow );
  12806. * //return float( 1 ); // bypass received shadows
  12807. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  12808. * } );
  12809. *
  12810. * @type {?(Function|FunctionNode<vec4>)}
  12811. * @default null
  12812. */
  12813. this.receivedShadowNode = null;
  12814. /**
  12815. * This node can be used to influence how an object using this node material
  12816. * casts shadows. To apply a color to shadows, you can simply do:
  12817. *
  12818. * ```js
  12819. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  12820. * ```
  12821. *
  12822. * Which can be nice to fake colored shadows of semi-transparent objects. It
  12823. * is also common to use the property with `Fn` function so checks are performed
  12824. * per fragment.
  12825. *
  12826. * ```js
  12827. * materialCustomShadow.castShadowNode = Fn( () => {
  12828. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  12829. * return materialColor;
  12830. * } )();
  12831. * ```
  12832. *
  12833. * @type {?Node<vec4>}
  12834. * @default null
  12835. */
  12836. this.castShadowNode = null;
  12837. /**
  12838. * This node can be used to define the final output of the material.
  12839. *
  12840. * TODO: Explain the differences to `fragmentNode`.
  12841. *
  12842. * @type {?Node<vec4>}
  12843. * @default null
  12844. */
  12845. this.outputNode = null;
  12846. /**
  12847. * MRT configuration is done on renderer or pass level. This node allows to
  12848. * overwrite what values are written into MRT targets on material level. This
  12849. * can be useful for implementing selective FX features that should only affect
  12850. * specific objects.
  12851. *
  12852. * @type {?MRTNode}
  12853. * @default null
  12854. */
  12855. this.mrtNode = null;
  12856. /**
  12857. * This node property can be used if you need complete freedom in implementing
  12858. * the fragment shader. Assigning a node will replace the built-in material
  12859. * logic used in the fragment stage.
  12860. *
  12861. * @type {?Node<vec4>}
  12862. * @default null
  12863. */
  12864. this.fragmentNode = null;
  12865. /**
  12866. * This node property can be used if you need complete freedom in implementing
  12867. * the vertex shader. Assigning a node will replace the built-in material logic
  12868. * used in the vertex stage.
  12869. *
  12870. * @type {?Node<vec4>}
  12871. * @default null
  12872. */
  12873. this.vertexNode = null;
  12874. // Deprecated properties
  12875. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  12876. get: () => {
  12877. return this.receivedShadowPositionNode;
  12878. },
  12879. set: ( value ) => {
  12880. console.warn( 'THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  12881. this.receivedShadowPositionNode = value;
  12882. }
  12883. } );
  12884. }
  12885. /**
  12886. * Allows to define a custom cache key that influence the material key computation
  12887. * for render objects.
  12888. *
  12889. * @return {string} The custom cache key.
  12890. */
  12891. customProgramCacheKey() {
  12892. return this.type + getCacheKey$1( this );
  12893. }
  12894. /**
  12895. * Builds this material with the given node builder.
  12896. *
  12897. * @param {NodeBuilder} builder - The current node builder.
  12898. */
  12899. build( builder ) {
  12900. this.setup( builder );
  12901. }
  12902. /**
  12903. * Setups a node material observer with the given builder.
  12904. *
  12905. * @param {NodeBuilder} builder - The current node builder.
  12906. * @return {NodeMaterialObserver} The node material observer.
  12907. */
  12908. setupObserver( builder ) {
  12909. return new NodeMaterialObserver( builder );
  12910. }
  12911. /**
  12912. * Setups the vertex and fragment stage of this node material.
  12913. *
  12914. * @param {NodeBuilder} builder - The current node builder.
  12915. */
  12916. setup( builder ) {
  12917. builder.context.setupNormal = () => this.setupNormal( builder );
  12918. builder.context.setupPositionView = () => this.setupPositionView( builder );
  12919. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  12920. const renderer = builder.renderer;
  12921. const renderTarget = renderer.getRenderTarget();
  12922. // < VERTEX STAGE >
  12923. builder.addStack();
  12924. const mvp = this.setupVertex( builder );
  12925. const vertexNode = this.vertexNode || mvp;
  12926. builder.stack.outputNode = vertexNode;
  12927. this.setupHardwareClipping( builder );
  12928. if ( this.geometryNode !== null ) {
  12929. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  12930. }
  12931. builder.addFlow( 'vertex', builder.removeStack() );
  12932. // < FRAGMENT STAGE >
  12933. builder.addStack();
  12934. let resultNode;
  12935. const clippingNode = this.setupClipping( builder );
  12936. if ( this.depthWrite === true || this.depthTest === true ) {
  12937. // only write depth if depth buffer is configured
  12938. if ( renderTarget !== null ) {
  12939. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  12940. } else {
  12941. if ( renderer.depth === true ) this.setupDepth( builder );
  12942. }
  12943. }
  12944. if ( this.fragmentNode === null ) {
  12945. this.setupDiffuseColor( builder );
  12946. this.setupVariants( builder );
  12947. const outgoingLightNode = this.setupLighting( builder );
  12948. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  12949. // force unsigned floats - useful for RenderTargets
  12950. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  12951. resultNode = this.setupOutput( builder, basicOutput );
  12952. // OUTPUT NODE
  12953. output.assign( resultNode );
  12954. //
  12955. const isCustomOutput = this.outputNode !== null;
  12956. if ( isCustomOutput ) resultNode = this.outputNode;
  12957. // MRT
  12958. if ( renderTarget !== null ) {
  12959. const mrt = renderer.getMRT();
  12960. const materialMRT = this.mrtNode;
  12961. if ( mrt !== null ) {
  12962. if ( isCustomOutput ) output.assign( resultNode );
  12963. resultNode = mrt;
  12964. if ( materialMRT !== null ) {
  12965. resultNode = mrt.merge( materialMRT );
  12966. }
  12967. } else if ( materialMRT !== null ) {
  12968. resultNode = materialMRT;
  12969. }
  12970. }
  12971. } else {
  12972. let fragmentNode = this.fragmentNode;
  12973. if ( fragmentNode.isOutputStructNode !== true ) {
  12974. fragmentNode = vec4( fragmentNode );
  12975. }
  12976. resultNode = this.setupOutput( builder, fragmentNode );
  12977. }
  12978. builder.stack.outputNode = resultNode;
  12979. builder.addFlow( 'fragment', builder.removeStack() );
  12980. // < OBSERVER >
  12981. builder.observer = this.setupObserver( builder );
  12982. }
  12983. /**
  12984. * Setups the clipping node.
  12985. *
  12986. * @param {NodeBuilder} builder - The current node builder.
  12987. * @return {ClippingNode} The clipping node.
  12988. */
  12989. setupClipping( builder ) {
  12990. if ( builder.clippingContext === null ) return null;
  12991. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  12992. let result = null;
  12993. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  12994. const samples = builder.renderer.samples;
  12995. if ( this.alphaToCoverage && samples > 1 ) {
  12996. // to be added to flow when the color/alpha value has been determined
  12997. result = clippingAlpha();
  12998. } else {
  12999. builder.stack.add( clipping() );
  13000. }
  13001. }
  13002. return result;
  13003. }
  13004. /**
  13005. * Setups the hardware clipping if available on the current device.
  13006. *
  13007. * @param {NodeBuilder} builder - The current node builder.
  13008. */
  13009. setupHardwareClipping( builder ) {
  13010. this.hardwareClipping = false;
  13011. if ( builder.clippingContext === null ) return;
  13012. const candidateCount = builder.clippingContext.unionPlanes.length;
  13013. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  13014. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  13015. builder.stack.add( hardwareClipping() );
  13016. this.hardwareClipping = true;
  13017. }
  13018. return;
  13019. }
  13020. /**
  13021. * Setups the depth of this material.
  13022. *
  13023. * @param {NodeBuilder} builder - The current node builder.
  13024. */
  13025. setupDepth( builder ) {
  13026. const { renderer, camera } = builder;
  13027. // Depth
  13028. let depthNode = this.depthNode;
  13029. if ( depthNode === null ) {
  13030. const mrt = renderer.getMRT();
  13031. if ( mrt && mrt.has( 'depth' ) ) {
  13032. depthNode = mrt.get( 'depth' );
  13033. } else if ( renderer.logarithmicDepthBuffer === true ) {
  13034. if ( camera.isPerspectiveCamera ) {
  13035. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  13036. } else {
  13037. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13038. }
  13039. }
  13040. }
  13041. if ( depthNode !== null ) {
  13042. depth.assign( depthNode ).toStack();
  13043. }
  13044. }
  13045. /**
  13046. * Setups the position node in view space. This method exists
  13047. * so derived node materials can modify the implementation e.g. sprite materials.
  13048. *
  13049. * @param {NodeBuilder} builder - The current node builder.
  13050. * @return {Node<vec3>} The position in view space.
  13051. */
  13052. setupPositionView( /*builder*/ ) {
  13053. return modelViewMatrix.mul( positionLocal ).xyz;
  13054. }
  13055. /**
  13056. * Setups the position in clip space.
  13057. *
  13058. * @param {NodeBuilder} builder - The current node builder.
  13059. * @return {Node<vec4>} The position in view space.
  13060. */
  13061. setupModelViewProjection( /*builder*/ ) {
  13062. return cameraProjectionMatrix.mul( positionView );
  13063. }
  13064. /**
  13065. * Setups the logic for the vertex stage.
  13066. *
  13067. * @param {NodeBuilder} builder - The current node builder.
  13068. * @return {Node<vec4>} The position in clip space.
  13069. */
  13070. setupVertex( builder ) {
  13071. builder.addStack();
  13072. this.setupPosition( builder );
  13073. builder.context.vertex = builder.removeStack();
  13074. return modelViewProjection;
  13075. }
  13076. /**
  13077. * Setups the computation of the position in local space.
  13078. *
  13079. * @param {NodeBuilder} builder - The current node builder.
  13080. * @return {Node<vec3>} The position in local space.
  13081. */
  13082. setupPosition( builder ) {
  13083. const { object, geometry } = builder;
  13084. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  13085. morphReference( object ).toStack();
  13086. }
  13087. if ( object.isSkinnedMesh === true ) {
  13088. skinning( object ).toStack();
  13089. }
  13090. if ( this.displacementMap ) {
  13091. const displacementMap = materialReference( 'displacementMap', 'texture' );
  13092. const displacementScale = materialReference( 'displacementScale', 'float' );
  13093. const displacementBias = materialReference( 'displacementBias', 'float' );
  13094. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  13095. }
  13096. if ( object.isBatchedMesh ) {
  13097. batch( object ).toStack();
  13098. }
  13099. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  13100. instancedMesh( object ).toStack();
  13101. }
  13102. if ( this.positionNode !== null ) {
  13103. positionLocal.assign( namespace( this.positionNode, 'POSITION' ) );
  13104. }
  13105. return positionLocal;
  13106. }
  13107. /**
  13108. * Setups the computation of the material's diffuse color.
  13109. *
  13110. * @param {NodeBuilder} builder - The current node builder.
  13111. * @param {BufferGeometry} geometry - The geometry.
  13112. */
  13113. setupDiffuseColor( { object, geometry } ) {
  13114. // MASK
  13115. if ( this.maskNode !== null ) {
  13116. // Discard if the mask is `false`
  13117. bool( this.maskNode ).not().discard();
  13118. }
  13119. // COLOR
  13120. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  13121. // VERTEX COLORS
  13122. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  13123. colorNode = colorNode.mul( vertexColor() );
  13124. }
  13125. // INSTANCED COLORS
  13126. if ( object.instanceColor ) {
  13127. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  13128. colorNode = instanceColor.mul( colorNode );
  13129. }
  13130. if ( object.isBatchedMesh && object._colorsTexture ) {
  13131. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  13132. colorNode = batchColor.mul( colorNode );
  13133. }
  13134. // DIFFUSE COLOR
  13135. diffuseColor.assign( colorNode );
  13136. // OPACITY
  13137. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13138. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  13139. // ALPHA TEST
  13140. let alphaTestNode = null;
  13141. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  13142. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  13143. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  13144. }
  13145. // ALPHA HASH
  13146. if ( this.alphaHash === true ) {
  13147. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  13148. }
  13149. // OPAQUE
  13150. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  13151. if ( isOpaque ) {
  13152. diffuseColor.a.assign( 1.0 );
  13153. } else if ( alphaTestNode === null ) {
  13154. diffuseColor.a.lessThanEqual( 0 ).discard();
  13155. }
  13156. }
  13157. /**
  13158. * Abstract interface method that can be implemented by derived materials
  13159. * to setup material-specific node variables.
  13160. *
  13161. * @abstract
  13162. * @param {NodeBuilder} builder - The current node builder.
  13163. */
  13164. setupVariants( /*builder*/ ) {
  13165. // Interface function.
  13166. }
  13167. /**
  13168. * Setups the outgoing light node variable
  13169. *
  13170. * @return {Node<vec3>} The outgoing light node.
  13171. */
  13172. setupOutgoingLight() {
  13173. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  13174. }
  13175. /**
  13176. * Setups the normal node from the material.
  13177. *
  13178. * @return {Node<vec3>} The normal node.
  13179. */
  13180. setupNormal() {
  13181. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  13182. }
  13183. /**
  13184. * Setups the environment node from the material.
  13185. *
  13186. * @param {NodeBuilder} builder - The current node builder.
  13187. * @return {Node<vec4>} The environment node.
  13188. */
  13189. setupEnvironment( /*builder*/ ) {
  13190. let node = null;
  13191. if ( this.envNode ) {
  13192. node = this.envNode;
  13193. } else if ( this.envMap ) {
  13194. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  13195. }
  13196. return node;
  13197. }
  13198. /**
  13199. * Setups the light map node from the material.
  13200. *
  13201. * @param {NodeBuilder} builder - The current node builder.
  13202. * @return {Node<vec3>} The light map node.
  13203. */
  13204. setupLightMap( builder ) {
  13205. let node = null;
  13206. if ( builder.material.lightMap ) {
  13207. node = new IrradianceNode( materialLightMap );
  13208. }
  13209. return node;
  13210. }
  13211. /**
  13212. * Setups the lights node based on the scene, environment and material.
  13213. *
  13214. * @param {NodeBuilder} builder - The current node builder.
  13215. * @return {LightsNode} The lights node.
  13216. */
  13217. setupLights( builder ) {
  13218. const materialLightsNode = [];
  13219. //
  13220. const envNode = this.setupEnvironment( builder );
  13221. if ( envNode && envNode.isLightingNode ) {
  13222. materialLightsNode.push( envNode );
  13223. }
  13224. const lightMapNode = this.setupLightMap( builder );
  13225. if ( lightMapNode && lightMapNode.isLightingNode ) {
  13226. materialLightsNode.push( lightMapNode );
  13227. }
  13228. if ( this.aoNode !== null || builder.material.aoMap ) {
  13229. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  13230. materialLightsNode.push( new AONode( aoNode ) );
  13231. }
  13232. let lightsN = this.lightsNode || builder.lightsNode;
  13233. if ( materialLightsNode.length > 0 ) {
  13234. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  13235. }
  13236. return lightsN;
  13237. }
  13238. /**
  13239. * This method should be implemented by most derived materials
  13240. * since it defines the material's lighting model.
  13241. *
  13242. * @abstract
  13243. * @param {NodeBuilder} builder - The current node builder.
  13244. * @return {LightingModel} The lighting model.
  13245. */
  13246. setupLightingModel( /*builder*/ ) {
  13247. // Interface function.
  13248. }
  13249. /**
  13250. * Setups the outgoing light node.
  13251. *
  13252. * @param {NodeBuilder} builder - The current node builder.
  13253. * @return {Node<vec3>} The outgoing light node.
  13254. */
  13255. setupLighting( builder ) {
  13256. const { material } = builder;
  13257. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  13258. // OUTGOING LIGHT
  13259. const lights = this.lights === true || this.lightsNode !== null;
  13260. const lightsNode = lights ? this.setupLights( builder ) : null;
  13261. let outgoingLightNode = this.setupOutgoingLight( builder );
  13262. if ( lightsNode && lightsNode.getScope().hasLights ) {
  13263. const lightingModel = this.setupLightingModel( builder ) || null;
  13264. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  13265. } else if ( backdropNode !== null ) {
  13266. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  13267. }
  13268. // EMISSIVE
  13269. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  13270. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  13271. outgoingLightNode = outgoingLightNode.add( emissive );
  13272. }
  13273. return outgoingLightNode;
  13274. }
  13275. /**
  13276. * Setup the fog.
  13277. *
  13278. * @param {NodeBuilder} builder - The current node builder.
  13279. * @param {Node<vec4>} outputNode - The existing output node.
  13280. * @return {Node<vec4>} The output node.
  13281. */
  13282. setupFog( builder, outputNode ) {
  13283. const fogNode = builder.fogNode;
  13284. if ( fogNode ) {
  13285. output.assign( outputNode );
  13286. outputNode = vec4( fogNode );
  13287. }
  13288. return outputNode;
  13289. }
  13290. /**
  13291. * Setups the output node.
  13292. *
  13293. * @param {NodeBuilder} builder - The current node builder.
  13294. * @param {Node<vec4>} outputNode - The existing output node.
  13295. * @return {Node<vec4>} The output node.
  13296. */
  13297. setupOutput( builder, outputNode ) {
  13298. // FOG
  13299. if ( this.fog === true ) {
  13300. outputNode = this.setupFog( builder, outputNode );
  13301. }
  13302. return outputNode;
  13303. }
  13304. /**
  13305. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  13306. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  13307. * defining all material properties of the classic type in the node type.
  13308. *
  13309. * @param {Material} material - The material to copy properties with their values to this node material.
  13310. */
  13311. setDefaultValues( material ) {
  13312. // This approach is to reuse the native refreshUniforms*
  13313. // and turn available the use of features like transmission and environment in core
  13314. for ( const property in material ) {
  13315. const value = material[ property ];
  13316. if ( this[ property ] === undefined ) {
  13317. this[ property ] = value;
  13318. if ( value && value.clone ) this[ property ] = value.clone();
  13319. }
  13320. }
  13321. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  13322. for ( const key in descriptors ) {
  13323. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  13324. descriptors[ key ].get !== undefined ) {
  13325. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  13326. }
  13327. }
  13328. }
  13329. /**
  13330. * Serializes this material to JSON.
  13331. *
  13332. * @param {?(Object|string)} meta - The meta information for serialization.
  13333. * @return {Object} The serialized node.
  13334. */
  13335. toJSON( meta ) {
  13336. const isRoot = ( meta === undefined || typeof meta === 'string' );
  13337. if ( isRoot ) {
  13338. meta = {
  13339. textures: {},
  13340. images: {},
  13341. nodes: {}
  13342. };
  13343. }
  13344. const data = Material.prototype.toJSON.call( this, meta );
  13345. const nodeChildren = getNodeChildren( this );
  13346. data.inputNodes = {};
  13347. for ( const { property, childNode } of nodeChildren ) {
  13348. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  13349. }
  13350. // TODO: Copied from Object3D.toJSON
  13351. function extractFromCache( cache ) {
  13352. const values = [];
  13353. for ( const key in cache ) {
  13354. const data = cache[ key ];
  13355. delete data.metadata;
  13356. values.push( data );
  13357. }
  13358. return values;
  13359. }
  13360. if ( isRoot ) {
  13361. const textures = extractFromCache( meta.textures );
  13362. const images = extractFromCache( meta.images );
  13363. const nodes = extractFromCache( meta.nodes );
  13364. if ( textures.length > 0 ) data.textures = textures;
  13365. if ( images.length > 0 ) data.images = images;
  13366. if ( nodes.length > 0 ) data.nodes = nodes;
  13367. }
  13368. return data;
  13369. }
  13370. /**
  13371. * Copies the properties of the given node material to this instance.
  13372. *
  13373. * @param {NodeMaterial} source - The material to copy.
  13374. * @return {NodeMaterial} A reference to this node material.
  13375. */
  13376. copy( source ) {
  13377. this.lightsNode = source.lightsNode;
  13378. this.envNode = source.envNode;
  13379. this.colorNode = source.colorNode;
  13380. this.normalNode = source.normalNode;
  13381. this.opacityNode = source.opacityNode;
  13382. this.backdropNode = source.backdropNode;
  13383. this.backdropAlphaNode = source.backdropAlphaNode;
  13384. this.alphaTestNode = source.alphaTestNode;
  13385. this.maskNode = source.maskNode;
  13386. this.positionNode = source.positionNode;
  13387. this.geometryNode = source.geometryNode;
  13388. this.depthNode = source.depthNode;
  13389. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  13390. this.castShadowPositionNode = source.castShadowPositionNode;
  13391. this.receivedShadowNode = source.receivedShadowNode;
  13392. this.castShadowNode = source.castShadowNode;
  13393. this.outputNode = source.outputNode;
  13394. this.mrtNode = source.mrtNode;
  13395. this.fragmentNode = source.fragmentNode;
  13396. this.vertexNode = source.vertexNode;
  13397. return super.copy( source );
  13398. }
  13399. }
  13400. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  13401. /**
  13402. * Node material version of {@link LineBasicMaterial}.
  13403. *
  13404. * @augments NodeMaterial
  13405. */
  13406. class LineBasicNodeMaterial extends NodeMaterial {
  13407. static get type() {
  13408. return 'LineBasicNodeMaterial';
  13409. }
  13410. /**
  13411. * Constructs a new line basic node material.
  13412. *
  13413. * @param {Object} [parameters] - The configuration parameter.
  13414. */
  13415. constructor( parameters ) {
  13416. super();
  13417. /**
  13418. * This flag can be used for type testing.
  13419. *
  13420. * @type {boolean}
  13421. * @readonly
  13422. * @default true
  13423. */
  13424. this.isLineBasicNodeMaterial = true;
  13425. this.setDefaultValues( _defaultValues$d );
  13426. this.setValues( parameters );
  13427. }
  13428. }
  13429. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  13430. /**
  13431. * Node material version of {@link LineDashedMaterial}.
  13432. *
  13433. * @augments NodeMaterial
  13434. */
  13435. class LineDashedNodeMaterial extends NodeMaterial {
  13436. static get type() {
  13437. return 'LineDashedNodeMaterial';
  13438. }
  13439. /**
  13440. * Constructs a new line dashed node material.
  13441. *
  13442. * @param {Object} [parameters] - The configuration parameter.
  13443. */
  13444. constructor( parameters ) {
  13445. super();
  13446. /**
  13447. * This flag can be used for type testing.
  13448. *
  13449. * @type {boolean}
  13450. * @readonly
  13451. * @default true
  13452. */
  13453. this.isLineDashedNodeMaterial = true;
  13454. this.setDefaultValues( _defaultValues$c );
  13455. /**
  13456. * The dash offset.
  13457. *
  13458. * @type {number}
  13459. * @default 0
  13460. */
  13461. this.dashOffset = 0;
  13462. /**
  13463. * The offset of dash materials is by default inferred from the `dashOffset`
  13464. * property. This node property allows to overwrite the default
  13465. * and define the offset with a node instead.
  13466. *
  13467. * If you don't want to overwrite the offset but modify the existing
  13468. * value instead, use {@link materialLineDashOffset}.
  13469. *
  13470. * @type {?Node<float>}
  13471. * @default null
  13472. */
  13473. this.offsetNode = null;
  13474. /**
  13475. * The scale of dash materials is by default inferred from the `scale`
  13476. * property. This node property allows to overwrite the default
  13477. * and define the scale with a node instead.
  13478. *
  13479. * If you don't want to overwrite the scale but modify the existing
  13480. * value instead, use {@link materialLineScale}.
  13481. *
  13482. * @type {?Node<float>}
  13483. * @default null
  13484. */
  13485. this.dashScaleNode = null;
  13486. /**
  13487. * The dash size of dash materials is by default inferred from the `dashSize`
  13488. * property. This node property allows to overwrite the default
  13489. * and define the dash size with a node instead.
  13490. *
  13491. * If you don't want to overwrite the dash size but modify the existing
  13492. * value instead, use {@link materialLineDashSize}.
  13493. *
  13494. * @type {?Node<float>}
  13495. * @default null
  13496. */
  13497. this.dashSizeNode = null;
  13498. /**
  13499. * The gap size of dash materials is by default inferred from the `gapSize`
  13500. * property. This node property allows to overwrite the default
  13501. * and define the gap size with a node instead.
  13502. *
  13503. * If you don't want to overwrite the gap size but modify the existing
  13504. * value instead, use {@link materialLineGapSize}.
  13505. *
  13506. * @type {?Node<float>}
  13507. * @default null
  13508. */
  13509. this.gapSizeNode = null;
  13510. this.setValues( parameters );
  13511. }
  13512. /**
  13513. * Setups the dash specific node variables.
  13514. *
  13515. * @param {NodeBuilder} builder - The current node builder.
  13516. */
  13517. setupVariants( /* builder */ ) {
  13518. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  13519. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  13520. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  13521. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  13522. dashSize.assign( dashSizeNode );
  13523. gapSize.assign( gapSizeNode );
  13524. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  13525. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  13526. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  13527. }
  13528. }
  13529. let _sharedFramebuffer = null;
  13530. /**
  13531. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  13532. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  13533. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  13534. *
  13535. * @augments ViewportTextureNode
  13536. */
  13537. class ViewportSharedTextureNode extends ViewportTextureNode {
  13538. static get type() {
  13539. return 'ViewportSharedTextureNode';
  13540. }
  13541. /**
  13542. * Constructs a new viewport shared texture node.
  13543. *
  13544. * @param {Node} [uvNode=screenUV] - The uv node.
  13545. * @param {?Node} [levelNode=null] - The level node.
  13546. */
  13547. constructor( uvNode = screenUV, levelNode = null ) {
  13548. if ( _sharedFramebuffer === null ) {
  13549. _sharedFramebuffer = new FramebufferTexture();
  13550. }
  13551. super( uvNode, levelNode, _sharedFramebuffer );
  13552. }
  13553. updateReference() {
  13554. return this;
  13555. }
  13556. }
  13557. /**
  13558. * TSL function for creating a shared viewport texture node.
  13559. *
  13560. * @tsl
  13561. * @function
  13562. * @param {?Node} [uvNode=screenUV] - The uv node.
  13563. * @param {?Node} [levelNode=null] - The level node.
  13564. * @returns {ViewportSharedTextureNode}
  13565. */
  13566. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  13567. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  13568. /**
  13569. * This node material can be used to render lines with a size larger than one
  13570. * by representing them as instanced meshes.
  13571. *
  13572. * @augments NodeMaterial
  13573. */
  13574. class Line2NodeMaterial extends NodeMaterial {
  13575. static get type() {
  13576. return 'Line2NodeMaterial';
  13577. }
  13578. /**
  13579. * Constructs a new node material for wide line rendering.
  13580. *
  13581. * @param {Object} [parameters={}] - The configuration parameter.
  13582. */
  13583. constructor( parameters = {} ) {
  13584. super();
  13585. /**
  13586. * This flag can be used for type testing.
  13587. *
  13588. * @type {boolean}
  13589. * @readonly
  13590. * @default true
  13591. */
  13592. this.isLine2NodeMaterial = true;
  13593. this.setDefaultValues( _defaultValues$b );
  13594. /**
  13595. * Whether vertex colors should be used or not.
  13596. *
  13597. * @type {boolean}
  13598. * @default false
  13599. */
  13600. this.useColor = parameters.vertexColors;
  13601. /**
  13602. * The dash offset.
  13603. *
  13604. * @type {number}
  13605. * @default 0
  13606. */
  13607. this.dashOffset = 0;
  13608. /**
  13609. * The line width.
  13610. *
  13611. * @type {number}
  13612. * @default 0
  13613. */
  13614. this.lineWidth = 1;
  13615. /**
  13616. * Defines the lines color.
  13617. *
  13618. * @type {?Node<vec3>}
  13619. * @default null
  13620. */
  13621. this.lineColorNode = null;
  13622. /**
  13623. * Defines the offset.
  13624. *
  13625. * @type {?Node<float>}
  13626. * @default null
  13627. */
  13628. this.offsetNode = null;
  13629. /**
  13630. * Defines the dash scale.
  13631. *
  13632. * @type {?Node<float>}
  13633. * @default null
  13634. */
  13635. this.dashScaleNode = null;
  13636. /**
  13637. * Defines the dash size.
  13638. *
  13639. * @type {?Node<float>}
  13640. * @default null
  13641. */
  13642. this.dashSizeNode = null;
  13643. /**
  13644. * Defines the gap size.
  13645. *
  13646. * @type {?Node<float>}
  13647. * @default null
  13648. */
  13649. this.gapSizeNode = null;
  13650. /**
  13651. * Blending is set to `NoBlending` since transparency
  13652. * is not supported, yet.
  13653. *
  13654. * @type {number}
  13655. * @default 0
  13656. */
  13657. this.blending = NoBlending;
  13658. this._useDash = parameters.dashed;
  13659. this._useAlphaToCoverage = true;
  13660. this._useWorldUnits = false;
  13661. this.setValues( parameters );
  13662. }
  13663. /**
  13664. * Setups the vertex and fragment stage of this node material.
  13665. *
  13666. * @param {NodeBuilder} builder - The current node builder.
  13667. */
  13668. setup( builder ) {
  13669. const { renderer } = builder;
  13670. const useAlphaToCoverage = this._useAlphaToCoverage;
  13671. const useColor = this.useColor;
  13672. const useDash = this._useDash;
  13673. const useWorldUnits = this._useWorldUnits;
  13674. const trimSegment = Fn( ( { start, end } ) => {
  13675. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  13676. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  13677. const nearEstimate = b.mul( -0.5 ).div( a );
  13678. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  13679. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  13680. } ).setLayout( {
  13681. name: 'trimSegment',
  13682. type: 'vec4',
  13683. inputs: [
  13684. { name: 'start', type: 'vec4' },
  13685. { name: 'end', type: 'vec4' }
  13686. ]
  13687. } );
  13688. this.vertexNode = Fn( () => {
  13689. const instanceStart = attribute( 'instanceStart' );
  13690. const instanceEnd = attribute( 'instanceEnd' );
  13691. // camera space
  13692. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  13693. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  13694. if ( useDash ) {
  13695. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  13696. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  13697. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  13698. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  13699. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  13700. lineDistance = lineDistance.add( offsetNode );
  13701. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  13702. }
  13703. if ( useWorldUnits ) {
  13704. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  13705. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  13706. }
  13707. const aspect = viewport.z.div( viewport.w );
  13708. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  13709. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  13710. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  13711. // perhaps there is a more elegant solution -- WestLangley
  13712. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  13713. If( perspective, () => {
  13714. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  13715. end.assign( trimSegment( { start: start, end: end } ) );
  13716. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  13717. start.assign( trimSegment( { start: end, end: start } ) );
  13718. } );
  13719. } );
  13720. // clip space
  13721. const clipStart = cameraProjectionMatrix.mul( start );
  13722. const clipEnd = cameraProjectionMatrix.mul( end );
  13723. // ndc space
  13724. const ndcStart = clipStart.xyz.div( clipStart.w );
  13725. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  13726. // direction
  13727. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  13728. // account for clip-space aspect ratio
  13729. dir.x.assign( dir.x.mul( aspect ) );
  13730. dir.assign( dir.normalize() );
  13731. const clip = vec4().toVar();
  13732. if ( useWorldUnits ) {
  13733. // get the offset direction as perpendicular to the view vector
  13734. const worldDir = end.xyz.sub( start.xyz ).normalize();
  13735. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  13736. const worldUp = worldDir.cross( tmpFwd ).normalize();
  13737. const worldFwd = worldDir.cross( worldUp );
  13738. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  13739. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  13740. // height offset
  13741. const hw = materialLineWidth.mul( 0.5 );
  13742. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  13743. // don't extend the line if we're rendering dashes because we
  13744. // won't be rendering the endcaps
  13745. if ( ! useDash ) {
  13746. // cap extension
  13747. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  13748. // add width to the box
  13749. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  13750. // endcaps
  13751. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  13752. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  13753. } );
  13754. }
  13755. // project the worldpos
  13756. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  13757. // shift the depth of the projected points so the line
  13758. // segments overlap neatly
  13759. const clipPose = vec3().toVar();
  13760. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  13761. clip.z.assign( clipPose.z.mul( clip.w ) );
  13762. } else {
  13763. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  13764. // undo aspect ratio adjustment
  13765. dir.x.assign( dir.x.div( aspect ) );
  13766. offset.x.assign( offset.x.div( aspect ) );
  13767. // sign flip
  13768. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  13769. // endcaps
  13770. If( positionGeometry.y.lessThan( 0.0 ), () => {
  13771. offset.assign( offset.sub( dir ) );
  13772. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  13773. offset.assign( offset.add( dir ) );
  13774. } );
  13775. // adjust for linewidth
  13776. offset.assign( offset.mul( materialLineWidth ) );
  13777. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  13778. offset.assign( offset.div( viewport.w ) );
  13779. // select end
  13780. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  13781. // back to clip space
  13782. offset.assign( offset.mul( clip.w ) );
  13783. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  13784. }
  13785. return clip;
  13786. } )();
  13787. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  13788. const p13 = p1.sub( p3 );
  13789. const p43 = p4.sub( p3 );
  13790. const p21 = p2.sub( p1 );
  13791. const d1343 = p13.dot( p43 );
  13792. const d4321 = p43.dot( p21 );
  13793. const d1321 = p13.dot( p21 );
  13794. const d4343 = p43.dot( p43 );
  13795. const d2121 = p21.dot( p21 );
  13796. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  13797. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  13798. const mua = numer.div( denom ).clamp();
  13799. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  13800. return vec2( mua, mub );
  13801. } );
  13802. this.colorNode = Fn( () => {
  13803. const vUv = uv();
  13804. if ( useDash ) {
  13805. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  13806. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  13807. dashSize.assign( dashSizeNode );
  13808. gapSize.assign( gapSizeNode );
  13809. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  13810. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  13811. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  13812. }
  13813. const alpha = float( 1 ).toVar( 'alpha' );
  13814. if ( useWorldUnits ) {
  13815. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  13816. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  13817. // Find the closest points on the view ray and the line segment
  13818. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  13819. const lineDir = worldEnd.sub( worldStart );
  13820. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  13821. const p1 = worldStart.add( lineDir.mul( params.x ) );
  13822. const p2 = rayEnd.mul( params.y );
  13823. const delta = p1.sub( p2 );
  13824. const len = delta.length();
  13825. const norm = len.div( materialLineWidth );
  13826. if ( ! useDash ) {
  13827. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  13828. const dnorm = norm.fwidth();
  13829. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  13830. } else {
  13831. norm.greaterThan( 0.5 ).discard();
  13832. }
  13833. }
  13834. } else {
  13835. // round endcaps
  13836. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  13837. const a = vUv.x;
  13838. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  13839. const len2 = a.mul( a ).add( b.mul( b ) );
  13840. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  13841. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  13842. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  13843. } );
  13844. } else {
  13845. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  13846. const a = vUv.x;
  13847. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  13848. const len2 = a.mul( a ).add( b.mul( b ) );
  13849. len2.greaterThan( 1.0 ).discard();
  13850. } );
  13851. }
  13852. }
  13853. let lineColorNode;
  13854. if ( this.lineColorNode ) {
  13855. lineColorNode = this.lineColorNode;
  13856. } else {
  13857. if ( useColor ) {
  13858. const instanceColorStart = attribute( 'instanceColorStart' );
  13859. const instanceColorEnd = attribute( 'instanceColorEnd' );
  13860. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  13861. lineColorNode = instanceColor.mul( materialColor );
  13862. } else {
  13863. lineColorNode = materialColor;
  13864. }
  13865. }
  13866. return vec4( lineColorNode, alpha );
  13867. } )();
  13868. if ( this.transparent ) {
  13869. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13870. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  13871. }
  13872. super.setup( builder );
  13873. }
  13874. /**
  13875. * Whether the lines should sized in world units or not.
  13876. * When set to `false` the unit is pixel.
  13877. *
  13878. * @type {boolean}
  13879. * @default false
  13880. */
  13881. get worldUnits() {
  13882. return this._useWorldUnits;
  13883. }
  13884. set worldUnits( value ) {
  13885. if ( this._useWorldUnits !== value ) {
  13886. this._useWorldUnits = value;
  13887. this.needsUpdate = true;
  13888. }
  13889. }
  13890. /**
  13891. * Whether the lines should be dashed or not.
  13892. *
  13893. * @type {boolean}
  13894. * @default false
  13895. */
  13896. get dashed() {
  13897. return this._useDash;
  13898. }
  13899. set dashed( value ) {
  13900. if ( this._useDash !== value ) {
  13901. this._useDash = value;
  13902. this.needsUpdate = true;
  13903. }
  13904. }
  13905. /**
  13906. * Whether alpha to coverage should be used or not.
  13907. *
  13908. * @type {boolean}
  13909. * @default true
  13910. */
  13911. get alphaToCoverage() {
  13912. return this._useAlphaToCoverage;
  13913. }
  13914. set alphaToCoverage( value ) {
  13915. if ( this._useAlphaToCoverage !== value ) {
  13916. this._useAlphaToCoverage = value;
  13917. this.needsUpdate = true;
  13918. }
  13919. }
  13920. }
  13921. /**
  13922. * Packs a direction vector into a color value.
  13923. *
  13924. * @tsl
  13925. * @function
  13926. * @param {Node<vec3>} node - The direction to pack.
  13927. * @return {Node<vec3>} The color.
  13928. */
  13929. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  13930. /**
  13931. * Unpacks a color value into a direction vector.
  13932. *
  13933. * @tsl
  13934. * @function
  13935. * @param {Node<vec3>} node - The color to unpack.
  13936. * @return {Node<vec3>} The direction.
  13937. */
  13938. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  13939. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  13940. /**
  13941. * Node material version of {@link MeshNormalMaterial}.
  13942. *
  13943. * @augments NodeMaterial
  13944. */
  13945. class MeshNormalNodeMaterial extends NodeMaterial {
  13946. static get type() {
  13947. return 'MeshNormalNodeMaterial';
  13948. }
  13949. /**
  13950. * Constructs a new mesh normal node material.
  13951. *
  13952. * @param {Object} [parameters] - The configuration parameter.
  13953. */
  13954. constructor( parameters ) {
  13955. super();
  13956. /**
  13957. * This flag can be used for type testing.
  13958. *
  13959. * @type {boolean}
  13960. * @readonly
  13961. * @default true
  13962. */
  13963. this.isMeshNormalNodeMaterial = true;
  13964. this.setDefaultValues( _defaultValues$a );
  13965. this.setValues( parameters );
  13966. }
  13967. /**
  13968. * Overwrites the default implementation by computing the diffuse color
  13969. * based on the normal data.
  13970. */
  13971. setupDiffuseColor() {
  13972. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13973. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  13974. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( transformedNormalView ), opacityNode ), SRGBColorSpace ) );
  13975. }
  13976. }
  13977. /**
  13978. * Can be used to compute texture coordinates for projecting an
  13979. * equirectangular texture onto a mesh for using it as the scene's
  13980. * background.
  13981. *
  13982. * ```js
  13983. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  13984. * ```
  13985. *
  13986. * @augments TempNode
  13987. */
  13988. class EquirectUVNode extends TempNode {
  13989. static get type() {
  13990. return 'EquirectUVNode';
  13991. }
  13992. /**
  13993. * Constructs a new equirect uv node.
  13994. *
  13995. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  13996. */
  13997. constructor( dirNode = positionWorldDirection ) {
  13998. super( 'vec2' );
  13999. /**
  14000. * A direction vector for sampling why is by default `positionWorldDirection`.
  14001. *
  14002. * @type {Node<vec3>}
  14003. */
  14004. this.dirNode = dirNode;
  14005. }
  14006. setup() {
  14007. const dir = this.dirNode;
  14008. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  14009. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  14010. return vec2( u, v );
  14011. }
  14012. }
  14013. /**
  14014. * TSL function for creating an equirect uv node.
  14015. *
  14016. * @tsl
  14017. * @function
  14018. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  14019. * @returns {EquirectUVNode}
  14020. */
  14021. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode ).setParameterLength( 0, 1 );
  14022. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  14023. /**
  14024. * This class represents a cube render target. It is a special version
  14025. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  14026. *
  14027. * @augments WebGLCubeRenderTarget
  14028. */
  14029. class CubeRenderTarget extends WebGLCubeRenderTarget {
  14030. /**
  14031. * Constructs a new cube render target.
  14032. *
  14033. * @param {number} [size=1] - The size of the render target.
  14034. * @param {RenderTarget~Options} [options] - The configuration object.
  14035. */
  14036. constructor( size = 1, options = {} ) {
  14037. super( size, options );
  14038. /**
  14039. * This flag can be used for type testing.
  14040. *
  14041. * @type {boolean}
  14042. * @readonly
  14043. * @default true
  14044. */
  14045. this.isCubeRenderTarget = true;
  14046. }
  14047. /**
  14048. * Converts the given equirectangular texture to a cube map.
  14049. *
  14050. * @param {Renderer} renderer - The renderer.
  14051. * @param {Texture} texture - The equirectangular texture.
  14052. * @return {CubeRenderTarget} A reference to this cube render target.
  14053. */
  14054. fromEquirectangularTexture( renderer, texture$1 ) {
  14055. const currentMinFilter = texture$1.minFilter;
  14056. const currentGenerateMipmaps = texture$1.generateMipmaps;
  14057. texture$1.generateMipmaps = true;
  14058. this.texture.type = texture$1.type;
  14059. this.texture.colorSpace = texture$1.colorSpace;
  14060. this.texture.generateMipmaps = texture$1.generateMipmaps;
  14061. this.texture.minFilter = texture$1.minFilter;
  14062. this.texture.magFilter = texture$1.magFilter;
  14063. const geometry = new BoxGeometry( 5, 5, 5 );
  14064. const uvNode = equirectUV( positionWorldDirection );
  14065. const material = new NodeMaterial();
  14066. material.colorNode = texture( texture$1, uvNode, 0 );
  14067. material.side = BackSide;
  14068. material.blending = NoBlending;
  14069. const mesh = new Mesh( geometry, material );
  14070. const scene = new Scene();
  14071. scene.add( mesh );
  14072. // Avoid blurred poles
  14073. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  14074. const camera = new CubeCamera( 1, 10, this );
  14075. const currentMRT = renderer.getMRT();
  14076. renderer.setMRT( null );
  14077. camera.update( renderer, scene );
  14078. renderer.setMRT( currentMRT );
  14079. texture$1.minFilter = currentMinFilter;
  14080. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  14081. mesh.geometry.dispose();
  14082. mesh.material.dispose();
  14083. return this;
  14084. }
  14085. }
  14086. const _cache$1 = new WeakMap();
  14087. /**
  14088. * This node can be used to automatically convert environment maps in the
  14089. * equirectangular format into the cube map format.
  14090. *
  14091. * @augments TempNode
  14092. */
  14093. class CubeMapNode extends TempNode {
  14094. static get type() {
  14095. return 'CubeMapNode';
  14096. }
  14097. /**
  14098. * Constructs a new cube map node.
  14099. *
  14100. * @param {Node} envNode - The node representing the environment map.
  14101. */
  14102. constructor( envNode ) {
  14103. super( 'vec3' );
  14104. /**
  14105. * The node representing the environment map.
  14106. *
  14107. * @type {Node}
  14108. */
  14109. this.envNode = envNode;
  14110. /**
  14111. * A reference to the internal cube texture.
  14112. *
  14113. * @private
  14114. * @type {?CubeTexture}
  14115. * @default null
  14116. */
  14117. this._cubeTexture = null;
  14118. /**
  14119. * A reference to the internal cube texture node.
  14120. *
  14121. * @private
  14122. * @type {CubeTextureNode}
  14123. */
  14124. this._cubeTextureNode = cubeTexture( null );
  14125. const defaultTexture = new CubeTexture();
  14126. defaultTexture.isRenderTargetTexture = true;
  14127. /**
  14128. * A default cube texture that acts as a placeholder.
  14129. * It is used when the conversion from equirectangular to cube
  14130. * map has not finished yet for a given texture.
  14131. *
  14132. * @private
  14133. * @type {CubeTexture}
  14134. */
  14135. this._defaultTexture = defaultTexture;
  14136. /**
  14137. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  14138. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  14139. *
  14140. * @type {string}
  14141. * @default 'render'
  14142. */
  14143. this.updateBeforeType = NodeUpdateType.RENDER;
  14144. }
  14145. updateBefore( frame ) {
  14146. const { renderer, material } = frame;
  14147. const envNode = this.envNode;
  14148. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14149. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14150. if ( texture && texture.isTexture ) {
  14151. const mapping = texture.mapping;
  14152. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  14153. // check for converted cubemap map
  14154. if ( _cache$1.has( texture ) ) {
  14155. const cubeMap = _cache$1.get( texture );
  14156. mapTextureMapping( cubeMap, texture.mapping );
  14157. this._cubeTexture = cubeMap;
  14158. } else {
  14159. // create cube map from equirectangular map
  14160. const image = texture.image;
  14161. if ( isEquirectangularMapReady$1( image ) ) {
  14162. const renderTarget = new CubeRenderTarget( image.height );
  14163. renderTarget.fromEquirectangularTexture( renderer, texture );
  14164. mapTextureMapping( renderTarget.texture, texture.mapping );
  14165. this._cubeTexture = renderTarget.texture;
  14166. _cache$1.set( texture, renderTarget.texture );
  14167. texture.addEventListener( 'dispose', onTextureDispose );
  14168. } else {
  14169. // default cube texture as fallback when equirectangular texture is not yet loaded
  14170. this._cubeTexture = this._defaultTexture;
  14171. }
  14172. }
  14173. //
  14174. this._cubeTextureNode.value = this._cubeTexture;
  14175. } else {
  14176. // envNode already refers to a cube map
  14177. this._cubeTextureNode = this.envNode;
  14178. }
  14179. }
  14180. }
  14181. }
  14182. setup( builder ) {
  14183. this.updateBefore( builder );
  14184. return this._cubeTextureNode;
  14185. }
  14186. }
  14187. /**
  14188. * Returns true if the given equirectangular image has been fully loaded
  14189. * and is ready for further processing.
  14190. *
  14191. * @private
  14192. * @param {Image} image - The equirectangular image to check.
  14193. * @return {boolean} Whether the image is ready or not.
  14194. */
  14195. function isEquirectangularMapReady$1( image ) {
  14196. if ( image === null || image === undefined ) return false;
  14197. return image.height > 0;
  14198. }
  14199. /**
  14200. * This function is executed when `dispose()` is called on the equirectangular
  14201. * texture. In this case, the generated cube map with its render target
  14202. * is deleted as well.
  14203. *
  14204. * @private
  14205. * @param {Object} event - The event object.
  14206. */
  14207. function onTextureDispose( event ) {
  14208. const texture = event.target;
  14209. texture.removeEventListener( 'dispose', onTextureDispose );
  14210. const renderTarget = _cache$1.get( texture );
  14211. if ( renderTarget !== undefined ) {
  14212. _cache$1.delete( texture );
  14213. renderTarget.dispose();
  14214. }
  14215. }
  14216. /**
  14217. * This function makes sure the generated cube map uses the correct
  14218. * texture mapping that corresponds to the equirectangular original.
  14219. *
  14220. * @private
  14221. * @param {Texture} texture - The cube texture.
  14222. * @param {number} mapping - The original texture mapping.
  14223. */
  14224. function mapTextureMapping( texture, mapping ) {
  14225. if ( mapping === EquirectangularReflectionMapping ) {
  14226. texture.mapping = CubeReflectionMapping;
  14227. } else if ( mapping === EquirectangularRefractionMapping ) {
  14228. texture.mapping = CubeRefractionMapping;
  14229. }
  14230. }
  14231. /**
  14232. * TSL function for creating a cube map node.
  14233. *
  14234. * @tsl
  14235. * @function
  14236. * @param {Node} envNode - The node representing the environment map.
  14237. * @returns {CubeMapNode}
  14238. */
  14239. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  14240. /**
  14241. * Represents a basic model for Image-based lighting (IBL). The environment
  14242. * is defined via environment maps in the equirectangular or cube map format.
  14243. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  14244. * or {@link MeshPhongNodeMaterial}.
  14245. *
  14246. * @augments LightingNode
  14247. */
  14248. class BasicEnvironmentNode extends LightingNode {
  14249. static get type() {
  14250. return 'BasicEnvironmentNode';
  14251. }
  14252. /**
  14253. * Constructs a new basic environment node.
  14254. *
  14255. * @param {Node} [envNode=null] - A node representing the environment.
  14256. */
  14257. constructor( envNode = null ) {
  14258. super();
  14259. /**
  14260. * A node representing the environment.
  14261. *
  14262. * @type {Node}
  14263. * @default null
  14264. */
  14265. this.envNode = envNode;
  14266. }
  14267. setup( builder ) {
  14268. // environment property is used in the finish() method of BasicLightingModel
  14269. builder.context.environment = cubeMapNode( this.envNode );
  14270. }
  14271. }
  14272. /**
  14273. * A specific version of {@link IrradianceNode} that is only relevant
  14274. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  14275. * requires a special scaling factor for the light map.
  14276. *
  14277. * @augments LightingNode
  14278. */
  14279. class BasicLightMapNode extends LightingNode {
  14280. static get type() {
  14281. return 'BasicLightMapNode';
  14282. }
  14283. /**
  14284. * Constructs a new basic light map node.
  14285. *
  14286. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  14287. */
  14288. constructor( lightMapNode = null ) {
  14289. super();
  14290. /**
  14291. * The light map node.
  14292. *
  14293. * @type {?Node<vec3>}
  14294. */
  14295. this.lightMapNode = lightMapNode;
  14296. }
  14297. setup( builder ) {
  14298. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  14299. const RECIPROCAL_PI = float( 1 / Math.PI );
  14300. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  14301. }
  14302. }
  14303. /**
  14304. * Abstract class for implementing lighting models. The module defines
  14305. * multiple methods that concrete lighting models can implement. These
  14306. * methods are executed at different points during the light evaluation
  14307. * process.
  14308. */
  14309. class LightingModel {
  14310. /**
  14311. * This method is intended for setting up lighting model and context data
  14312. * which are later used in the evaluation process.
  14313. *
  14314. * @abstract
  14315. * @param {NodeBuilder} builder - The current node builder.
  14316. */
  14317. start( builder ) {
  14318. // lights ( direct )
  14319. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  14320. // indirect
  14321. this.indirect( builder );
  14322. }
  14323. /**
  14324. * This method is intended for executing final tasks like final updates
  14325. * to the outgoing light.
  14326. *
  14327. * @abstract
  14328. * @param {NodeBuilder} builder - The current node builder.
  14329. */
  14330. finish( /*builder*/ ) { }
  14331. /**
  14332. * This method is intended for implementing the direct light term and
  14333. * executed during the build process of directional, point and spot light nodes.
  14334. *
  14335. * @abstract
  14336. * @param {Object} lightData - The light data.
  14337. * @param {NodeBuilder} builder - The current node builder.
  14338. */
  14339. direct( /*lightData, builder*/ ) { }
  14340. /**
  14341. * This method is intended for implementing the direct light term for
  14342. * rect area light nodes.
  14343. *
  14344. * @abstract
  14345. * @param {Object} lightData - The light data.
  14346. * @param {NodeBuilder} builder - The current node builder.
  14347. */
  14348. directRectArea( /*lightData, builder*/ ) {}
  14349. /**
  14350. * This method is intended for implementing the indirect light term.
  14351. *
  14352. * @abstract
  14353. * @param {NodeBuilder} builder - The current node builder.
  14354. */
  14355. indirect( /*builder*/ ) { }
  14356. /**
  14357. * This method is intended for implementing the ambient occlusion term.
  14358. * Unlike other methods, this method must be called manually by the lighting
  14359. * model in its indirect term.
  14360. *
  14361. * @abstract
  14362. * @param {NodeBuilder} builder - The current node builder.
  14363. */
  14364. ambientOcclusion( /*input, stack, builder*/ ) { }
  14365. }
  14366. /**
  14367. * Represents the lighting model for unlit materials. The only light contribution
  14368. * is baked indirect lighting modulated with ambient occlusion and the material's
  14369. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  14370. *
  14371. * @augments LightingModel
  14372. */
  14373. class BasicLightingModel extends LightingModel {
  14374. /**
  14375. * Constructs a new basic lighting model.
  14376. */
  14377. constructor() {
  14378. super();
  14379. }
  14380. /**
  14381. * Implements the baked indirect lighting with its modulation.
  14382. *
  14383. * @param {NodeBuilder} builder - The current node builder.
  14384. */
  14385. indirect( { context } ) {
  14386. const ambientOcclusion = context.ambientOcclusion;
  14387. const reflectedLight = context.reflectedLight;
  14388. const irradianceLightMap = context.irradianceLightMap;
  14389. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  14390. // accumulation (baked indirect lighting only)
  14391. if ( irradianceLightMap ) {
  14392. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  14393. } else {
  14394. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  14395. }
  14396. // modulation
  14397. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14398. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  14399. }
  14400. /**
  14401. * Implements the environment mapping.
  14402. *
  14403. * @param {NodeBuilder} builder - The current node builder.
  14404. */
  14405. finish( builder ) {
  14406. const { material, context } = builder;
  14407. const outgoingLight = context.outgoingLight;
  14408. const envNode = builder.context.environment;
  14409. if ( envNode ) {
  14410. switch ( material.combine ) {
  14411. case MultiplyOperation:
  14412. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  14413. break;
  14414. case MixOperation:
  14415. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  14416. break;
  14417. case AddOperation:
  14418. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  14419. break;
  14420. default:
  14421. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  14422. break;
  14423. }
  14424. }
  14425. }
  14426. }
  14427. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  14428. /**
  14429. * Node material version of {@link MeshBasicMaterial}.
  14430. *
  14431. * @augments NodeMaterial
  14432. */
  14433. class MeshBasicNodeMaterial extends NodeMaterial {
  14434. static get type() {
  14435. return 'MeshBasicNodeMaterial';
  14436. }
  14437. /**
  14438. * Constructs a new mesh basic node material.
  14439. *
  14440. * @param {Object} [parameters] - The configuration parameter.
  14441. */
  14442. constructor( parameters ) {
  14443. super();
  14444. /**
  14445. * This flag can be used for type testing.
  14446. *
  14447. * @type {boolean}
  14448. * @readonly
  14449. * @default true
  14450. */
  14451. this.isMeshBasicNodeMaterial = true;
  14452. /**
  14453. * Although the basic material is by definition unlit, we set
  14454. * this property to `true` since we use a lighting model to compute
  14455. * the outgoing light of the fragment shader.
  14456. *
  14457. * @type {boolean}
  14458. * @default true
  14459. */
  14460. this.lights = true;
  14461. this.setDefaultValues( _defaultValues$9 );
  14462. this.setValues( parameters );
  14463. }
  14464. /**
  14465. * Basic materials are not affected by normal and bump maps so we
  14466. * return by default {@link normalView}.
  14467. *
  14468. * @return {Node<vec3>} The normal node.
  14469. */
  14470. setupNormal() {
  14471. return normalView; // see #28839
  14472. }
  14473. /**
  14474. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14475. * to implement the default environment mapping.
  14476. *
  14477. * @param {NodeBuilder} builder - The current node builder.
  14478. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14479. */
  14480. setupEnvironment( builder ) {
  14481. const envNode = super.setupEnvironment( builder );
  14482. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14483. }
  14484. /**
  14485. * This method must be overwritten since light maps are evaluated
  14486. * with a special scaling factor for basic materials.
  14487. *
  14488. * @param {NodeBuilder} builder - The current node builder.
  14489. * @return {?BasicLightMapNode<vec3>} The light map node.
  14490. */
  14491. setupLightMap( builder ) {
  14492. let node = null;
  14493. if ( builder.material.lightMap ) {
  14494. node = new BasicLightMapNode( materialLightMap );
  14495. }
  14496. return node;
  14497. }
  14498. /**
  14499. * The material overwrites this method because `lights` is set to `true` but
  14500. * we still want to return the diffuse color as the outgoing light.
  14501. *
  14502. * @return {Node<vec3>} The outgoing light node.
  14503. */
  14504. setupOutgoingLight() {
  14505. return diffuseColor.rgb;
  14506. }
  14507. /**
  14508. * Setups the lighting model.
  14509. *
  14510. * @return {BasicLightingModel} The lighting model.
  14511. */
  14512. setupLightingModel() {
  14513. return new BasicLightingModel();
  14514. }
  14515. }
  14516. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  14517. // Original approximation by Christophe Schlick '94
  14518. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  14519. // Optimized variant (presented by Epic at SIGGRAPH '13)
  14520. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  14521. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  14522. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  14523. } ); // validated
  14524. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  14525. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  14526. } ); // validated
  14527. const G_BlinnPhong_Implicit = () => float( 0.25 );
  14528. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  14529. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  14530. } );
  14531. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  14532. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14533. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  14534. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  14535. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  14536. const G = G_BlinnPhong_Implicit();
  14537. const D = D_BlinnPhong( { dotNH } );
  14538. return F.mul( G ).mul( D );
  14539. } );
  14540. /**
  14541. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  14542. *
  14543. * @augments BasicLightingModel
  14544. */
  14545. class PhongLightingModel extends BasicLightingModel {
  14546. /**
  14547. * Constructs a new phong lighting model.
  14548. *
  14549. * @param {boolean} [specular=true] - Whether specular is supported or not.
  14550. */
  14551. constructor( specular = true ) {
  14552. super();
  14553. /**
  14554. * Whether specular is supported or not. Set this to `false` if you are
  14555. * looking for a Lambert-like material meaning a material for non-shiny
  14556. * surfaces, without specular highlights.
  14557. *
  14558. * @type {boolean}
  14559. * @default true
  14560. */
  14561. this.specular = specular;
  14562. }
  14563. /**
  14564. * Implements the direct lighting. The specular portion is optional an can be controlled
  14565. * with the {@link PhongLightingModel#specular} flag.
  14566. *
  14567. * @param {Object} lightData - The light data.
  14568. */
  14569. direct( { lightDirection, lightColor, reflectedLight } ) {
  14570. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14571. const irradiance = dotNL.mul( lightColor );
  14572. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  14573. if ( this.specular === true ) {
  14574. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  14575. }
  14576. }
  14577. /**
  14578. * Implements the indirect lighting.
  14579. *
  14580. * @param {NodeBuilder} builder - The current node builder.
  14581. */
  14582. indirect( builder ) {
  14583. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  14584. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  14585. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14586. }
  14587. }
  14588. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  14589. /**
  14590. * Node material version of {@link MeshLambertMaterial}.
  14591. *
  14592. * @augments NodeMaterial
  14593. */
  14594. class MeshLambertNodeMaterial extends NodeMaterial {
  14595. static get type() {
  14596. return 'MeshLambertNodeMaterial';
  14597. }
  14598. /**
  14599. * Constructs a new mesh lambert node material.
  14600. *
  14601. * @param {Object} [parameters] - The configuration parameter.
  14602. */
  14603. constructor( parameters ) {
  14604. super();
  14605. /**
  14606. * This flag can be used for type testing.
  14607. *
  14608. * @type {boolean}
  14609. * @readonly
  14610. * @default true
  14611. */
  14612. this.isMeshLambertNodeMaterial = true;
  14613. /**
  14614. * Set to `true` because lambert materials react on lights.
  14615. *
  14616. * @type {boolean}
  14617. * @default true
  14618. */
  14619. this.lights = true;
  14620. this.setDefaultValues( _defaultValues$8 );
  14621. this.setValues( parameters );
  14622. }
  14623. /**
  14624. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14625. * to implement the default environment mapping.
  14626. *
  14627. * @param {NodeBuilder} builder - The current node builder.
  14628. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14629. */
  14630. setupEnvironment( builder ) {
  14631. const envNode = super.setupEnvironment( builder );
  14632. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14633. }
  14634. /**
  14635. * Setups the lighting model.
  14636. *
  14637. * @return {PhongLightingModel} The lighting model.
  14638. */
  14639. setupLightingModel( /*builder*/ ) {
  14640. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  14641. }
  14642. }
  14643. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  14644. /**
  14645. * Node material version of {@link MeshPhongMaterial}.
  14646. *
  14647. * @augments NodeMaterial
  14648. */
  14649. class MeshPhongNodeMaterial extends NodeMaterial {
  14650. static get type() {
  14651. return 'MeshPhongNodeMaterial';
  14652. }
  14653. /**
  14654. * Constructs a new mesh lambert node material.
  14655. *
  14656. * @param {Object} [parameters] - The configuration parameter.
  14657. */
  14658. constructor( parameters ) {
  14659. super();
  14660. /**
  14661. * This flag can be used for type testing.
  14662. *
  14663. * @type {boolean}
  14664. * @readonly
  14665. * @default true
  14666. */
  14667. this.isMeshPhongNodeMaterial = true;
  14668. /**
  14669. * Set to `true` because phong materials react on lights.
  14670. *
  14671. * @type {boolean}
  14672. * @default true
  14673. */
  14674. this.lights = true;
  14675. /**
  14676. * The shininess of phong materials is by default inferred from the `shininess`
  14677. * property. This node property allows to overwrite the default
  14678. * and define the shininess with a node instead.
  14679. *
  14680. * If you don't want to overwrite the shininess but modify the existing
  14681. * value instead, use {@link materialShininess}.
  14682. *
  14683. * @type {?Node<float>}
  14684. * @default null
  14685. */
  14686. this.shininessNode = null;
  14687. /**
  14688. * The specular color of phong materials is by default inferred from the
  14689. * `specular` property. This node property allows to overwrite the default
  14690. * and define the specular color with a node instead.
  14691. *
  14692. * If you don't want to overwrite the specular color but modify the existing
  14693. * value instead, use {@link materialSpecular}.
  14694. *
  14695. * @type {?Node<vec3>}
  14696. * @default null
  14697. */
  14698. this.specularNode = null;
  14699. this.setDefaultValues( _defaultValues$7 );
  14700. this.setValues( parameters );
  14701. }
  14702. /**
  14703. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14704. * to implement the default environment mapping.
  14705. *
  14706. * @param {NodeBuilder} builder - The current node builder.
  14707. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14708. */
  14709. setupEnvironment( builder ) {
  14710. const envNode = super.setupEnvironment( builder );
  14711. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14712. }
  14713. /**
  14714. * Setups the lighting model.
  14715. *
  14716. * @return {PhongLightingModel} The lighting model.
  14717. */
  14718. setupLightingModel( /*builder*/ ) {
  14719. return new PhongLightingModel();
  14720. }
  14721. /**
  14722. * Setups the phong specific node variables.
  14723. *
  14724. * @param {NodeBuilder} builder - The current node builder.
  14725. */
  14726. setupVariants( /*builder*/ ) {
  14727. // SHININESS
  14728. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  14729. shininess.assign( shininessNode );
  14730. // SPECULAR COLOR
  14731. const specularNode = this.specularNode || materialSpecular;
  14732. specularColor.assign( specularNode );
  14733. }
  14734. copy( source ) {
  14735. this.shininessNode = source.shininessNode;
  14736. this.specularNode = source.specularNode;
  14737. return super.copy( source );
  14738. }
  14739. }
  14740. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  14741. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  14742. return float( 0 );
  14743. }
  14744. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  14745. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  14746. return geometryRoughness;
  14747. } );
  14748. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  14749. const { roughness } = inputs;
  14750. const geometryRoughness = getGeometryRoughness();
  14751. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  14752. roughnessFactor = roughnessFactor.add( geometryRoughness );
  14753. roughnessFactor = roughnessFactor.min( 1.0 );
  14754. return roughnessFactor;
  14755. } );
  14756. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  14757. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  14758. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  14759. const a2 = alpha.pow2();
  14760. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  14761. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  14762. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  14763. } ).setLayout( {
  14764. name: 'V_GGX_SmithCorrelated',
  14765. type: 'float',
  14766. inputs: [
  14767. { name: 'alpha', type: 'float' },
  14768. { name: 'dotNL', type: 'float' },
  14769. { name: 'dotNV', type: 'float' }
  14770. ]
  14771. } ); // validated
  14772. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  14773. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  14774. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  14775. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  14776. const v = div( 0.5, gv.add( gl ) );
  14777. return v.saturate();
  14778. } ).setLayout( {
  14779. name: 'V_GGX_SmithCorrelated_Anisotropic',
  14780. type: 'float',
  14781. inputs: [
  14782. { name: 'alphaT', type: 'float', qualifier: 'in' },
  14783. { name: 'alphaB', type: 'float', qualifier: 'in' },
  14784. { name: 'dotTV', type: 'float', qualifier: 'in' },
  14785. { name: 'dotBV', type: 'float', qualifier: 'in' },
  14786. { name: 'dotTL', type: 'float', qualifier: 'in' },
  14787. { name: 'dotBL', type: 'float', qualifier: 'in' },
  14788. { name: 'dotNV', type: 'float', qualifier: 'in' },
  14789. { name: 'dotNL', type: 'float', qualifier: 'in' }
  14790. ]
  14791. } );
  14792. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  14793. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  14794. // alpha is "roughness squared" in Disney’s reparameterization
  14795. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  14796. const a2 = alpha.pow2();
  14797. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  14798. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  14799. } ).setLayout( {
  14800. name: 'D_GGX',
  14801. type: 'float',
  14802. inputs: [
  14803. { name: 'alpha', type: 'float' },
  14804. { name: 'dotNH', type: 'float' }
  14805. ]
  14806. } ); // validated
  14807. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  14808. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  14809. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  14810. const a2 = alphaT.mul( alphaB );
  14811. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  14812. const v2 = v.dot( v );
  14813. const w2 = a2.div( v2 );
  14814. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  14815. } ).setLayout( {
  14816. name: 'D_GGX_Anisotropic',
  14817. type: 'float',
  14818. inputs: [
  14819. { name: 'alphaT', type: 'float', qualifier: 'in' },
  14820. { name: 'alphaB', type: 'float', qualifier: 'in' },
  14821. { name: 'dotNH', type: 'float', qualifier: 'in' },
  14822. { name: 'dotTH', type: 'float', qualifier: 'in' },
  14823. { name: 'dotBH', type: 'float', qualifier: 'in' }
  14824. ]
  14825. } );
  14826. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  14827. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  14828. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  14829. const normalView = inputs.normalView || transformedNormalView;
  14830. const alpha = roughness.pow2(); // UE4's roughness
  14831. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14832. const dotNL = normalView.dot( lightDirection ).clamp();
  14833. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14834. const dotNH = normalView.dot( halfDir ).clamp();
  14835. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  14836. let F = F_Schlick( { f0, f90, dotVH } );
  14837. let V, D;
  14838. if ( defined( USE_IRIDESCENCE ) ) {
  14839. F = iridescence.mix( F, f );
  14840. }
  14841. if ( defined( USE_ANISOTROPY ) ) {
  14842. const dotTL = anisotropyT.dot( lightDirection );
  14843. const dotTV = anisotropyT.dot( positionViewDirection );
  14844. const dotTH = anisotropyT.dot( halfDir );
  14845. const dotBL = anisotropyB.dot( lightDirection );
  14846. const dotBV = anisotropyB.dot( positionViewDirection );
  14847. const dotBH = anisotropyB.dot( halfDir );
  14848. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  14849. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  14850. } else {
  14851. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  14852. D = D_GGX( { alpha, dotNH } );
  14853. }
  14854. return F.mul( V ).mul( D );
  14855. } ); // validated
  14856. // Analytical approximation of the DFG LUT, one half of the
  14857. // split-sum approximation used in indirect specular lighting.
  14858. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  14859. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  14860. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  14861. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  14862. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  14863. const r = roughness.mul( c0 ).add( c1 );
  14864. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  14865. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  14866. return fab;
  14867. } ).setLayout( {
  14868. name: 'DFGApprox',
  14869. type: 'vec2',
  14870. inputs: [
  14871. { name: 'roughness', type: 'float' },
  14872. { name: 'dotNV', type: 'vec3' }
  14873. ]
  14874. } );
  14875. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  14876. const { dotNV, specularColor, specularF90, roughness } = inputs;
  14877. const fab = DFGApprox( { dotNV, roughness } );
  14878. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  14879. } );
  14880. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  14881. const x = dotVH.oneMinus().saturate();
  14882. const x2 = x.mul( x );
  14883. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  14884. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  14885. } ).setLayout( {
  14886. name: 'Schlick_to_F0',
  14887. type: 'vec3',
  14888. inputs: [
  14889. { name: 'f', type: 'vec3' },
  14890. { name: 'f90', type: 'float' },
  14891. { name: 'dotVH', type: 'float' }
  14892. ]
  14893. } );
  14894. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  14895. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  14896. const alpha = roughness.pow2();
  14897. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  14898. const invAlpha = float( 1.0 ).div( alpha );
  14899. const cos2h = dotNH.pow2();
  14900. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  14901. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  14902. } ).setLayout( {
  14903. name: 'D_Charlie',
  14904. type: 'float',
  14905. inputs: [
  14906. { name: 'roughness', type: 'float' },
  14907. { name: 'dotNH', type: 'float' }
  14908. ]
  14909. } );
  14910. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  14911. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  14912. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  14913. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  14914. } ).setLayout( {
  14915. name: 'V_Neubelt',
  14916. type: 'float',
  14917. inputs: [
  14918. { name: 'dotNV', type: 'float' },
  14919. { name: 'dotNL', type: 'float' }
  14920. ]
  14921. } );
  14922. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  14923. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14924. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14925. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  14926. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  14927. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  14928. const V = V_Neubelt( { dotNV, dotNL } );
  14929. return sheen.mul( D ).mul( V );
  14930. } );
  14931. // Rect Area Light
  14932. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  14933. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  14934. // code: https://github.com/selfshadow/ltc_code/
  14935. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  14936. const LUT_SIZE = 64.0;
  14937. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  14938. const LUT_BIAS = 0.5 / LUT_SIZE;
  14939. const dotNV = N.dot( V ).saturate();
  14940. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  14941. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  14942. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  14943. return uv;
  14944. } ).setLayout( {
  14945. name: 'LTC_Uv',
  14946. type: 'vec2',
  14947. inputs: [
  14948. { name: 'N', type: 'vec3' },
  14949. { name: 'V', type: 'vec3' },
  14950. { name: 'roughness', type: 'float' }
  14951. ]
  14952. } );
  14953. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  14954. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  14955. // An approximation of the form factor of a horizon-clipped rectangle.
  14956. const l = f.length();
  14957. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  14958. } ).setLayout( {
  14959. name: 'LTC_ClippedSphereFormFactor',
  14960. type: 'float',
  14961. inputs: [
  14962. { name: 'f', type: 'vec3' }
  14963. ]
  14964. } );
  14965. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  14966. const x = v1.dot( v2 );
  14967. const y = x.abs().toVar();
  14968. // rational polynomial approximation to theta / sin( theta ) / 2PI
  14969. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  14970. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  14971. const v = a.div( b );
  14972. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  14973. return v1.cross( v2 ).mul( theta_sintheta );
  14974. } ).setLayout( {
  14975. name: 'LTC_EdgeVectorFormFactor',
  14976. type: 'vec3',
  14977. inputs: [
  14978. { name: 'v1', type: 'vec3' },
  14979. { name: 'v2', type: 'vec3' }
  14980. ]
  14981. } );
  14982. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  14983. // bail if point is on back side of plane of light
  14984. // assumes ccw winding order of light vertices
  14985. const v1 = p1.sub( p0 ).toVar();
  14986. const v2 = p3.sub( p0 ).toVar();
  14987. const lightNormal = v1.cross( v2 );
  14988. const result = vec3().toVar();
  14989. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  14990. // construct orthonormal basis around N
  14991. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  14992. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  14993. // compute transform
  14994. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  14995. // transform rect
  14996. // & project rect onto sphere
  14997. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  14998. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  14999. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  15000. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  15001. // calculate vector form factor
  15002. const vectorFormFactor = vec3( 0 ).toVar();
  15003. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15004. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15005. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15006. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15007. // adjust for horizon clipping
  15008. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  15009. } );
  15010. return result;
  15011. } ).setLayout( {
  15012. name: 'LTC_Evaluate',
  15013. type: 'vec3',
  15014. inputs: [
  15015. { name: 'N', type: 'vec3' },
  15016. { name: 'V', type: 'vec3' },
  15017. { name: 'P', type: 'vec3' },
  15018. { name: 'mInv', type: 'mat3' },
  15019. { name: 'p0', type: 'vec3' },
  15020. { name: 'p1', type: 'vec3' },
  15021. { name: 'p2', type: 'vec3' },
  15022. { name: 'p3', type: 'vec3' }
  15023. ]
  15024. } );
  15025. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  15026. // bail if point is on back side of plane of light
  15027. // assumes ccw winding order of light vertices
  15028. const v1 = p1.sub( p0 ).toVar();
  15029. const v2 = p3.sub( p0 ).toVar();
  15030. const lightNormal = v1.cross( v2 );
  15031. const result = vec3().toVar();
  15032. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15033. // transform rect
  15034. // & project rect onto sphere
  15035. const coords0 = p0.sub( P ).normalize().toVar();
  15036. const coords1 = p1.sub( P ).normalize().toVar();
  15037. const coords2 = p2.sub( P ).normalize().toVar();
  15038. const coords3 = p3.sub( P ).normalize().toVar();
  15039. // calculate vector form factor
  15040. const vectorFormFactor = vec3( 0 ).toVar();
  15041. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15042. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15043. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15044. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15045. // adjust for horizon clipping
  15046. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  15047. } );
  15048. return result;
  15049. } ).setLayout( {
  15050. name: 'LTC_Evaluate',
  15051. type: 'vec3',
  15052. inputs: [
  15053. { name: 'P', type: 'vec3' },
  15054. { name: 'p0', type: 'vec3' },
  15055. { name: 'p1', type: 'vec3' },
  15056. { name: 'p2', type: 'vec3' },
  15057. { name: 'p3', type: 'vec3' }
  15058. ]
  15059. } );
  15060. // Mipped Bicubic Texture Filtering by N8
  15061. // https://www.shadertoy.com/view/Dl2SDW
  15062. const bC = 1.0 / 6.0;
  15063. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  15064. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  15065. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  15066. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  15067. const g0 = ( a ) => w0( a ).add( w1( a ) );
  15068. const g1 = ( a ) => w2( a ).add( w3( a ) );
  15069. // h0 and h1 are the two offset functions
  15070. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  15071. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  15072. const bicubic = ( textureNode, texelSize, lod ) => {
  15073. const uv = textureNode.uvNode;
  15074. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  15075. const iuv = floor( uvScaled );
  15076. const fuv = fract( uvScaled );
  15077. const g0x = g0( fuv.x );
  15078. const g1x = g1( fuv.x );
  15079. const h0x = h0( fuv.x );
  15080. const h1x = h1( fuv.x );
  15081. const h0y = h0( fuv.y );
  15082. const h1y = h1( fuv.y );
  15083. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15084. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15085. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15086. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15087. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  15088. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  15089. return a.add( b );
  15090. };
  15091. /**
  15092. * Applies mipped bicubic texture filtering to the given texture node.
  15093. *
  15094. * @tsl
  15095. * @function
  15096. * @param {TextureNode} textureNode - The texture node that should be filtered.
  15097. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  15098. * @return {Node} The filtered texture sample.
  15099. */
  15100. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  15101. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  15102. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  15103. const fLodSizeInv = div( 1.0, fLodSize );
  15104. const cLodSizeInv = div( 1.0, cLodSize );
  15105. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  15106. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  15107. return fract( lodNode ).mix( fSample, cSample );
  15108. } );
  15109. //
  15110. // Transmission
  15111. //
  15112. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  15113. // Direction of refracted light.
  15114. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  15115. // Compute rotation-independent scaling of the model matrix.
  15116. const modelScale = vec3(
  15117. length( modelMatrix[ 0 ].xyz ),
  15118. length( modelMatrix[ 1 ].xyz ),
  15119. length( modelMatrix[ 2 ].xyz )
  15120. );
  15121. // The thickness is specified in local space.
  15122. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  15123. } ).setLayout( {
  15124. name: 'getVolumeTransmissionRay',
  15125. type: 'vec3',
  15126. inputs: [
  15127. { name: 'n', type: 'vec3' },
  15128. { name: 'v', type: 'vec3' },
  15129. { name: 'thickness', type: 'float' },
  15130. { name: 'ior', type: 'float' },
  15131. { name: 'modelMatrix', type: 'mat4' }
  15132. ]
  15133. } );
  15134. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  15135. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  15136. // an IOR of 1.5 results in the default amount of microfacet refraction.
  15137. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  15138. } ).setLayout( {
  15139. name: 'applyIorToRoughness',
  15140. type: 'float',
  15141. inputs: [
  15142. { name: 'roughness', type: 'float' },
  15143. { name: 'ior', type: 'float' }
  15144. ]
  15145. } );
  15146. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  15147. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  15148. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  15149. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  15150. const transmissionSample = vTexture.sample( fragCoord );
  15151. //const transmissionSample = viewportMipTexture( fragCoord );
  15152. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  15153. return textureBicubic( transmissionSample, lod );
  15154. } );
  15155. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  15156. If( attenuationDistance.notEqual( 0 ), () => {
  15157. // Compute light attenuation using Beer's law.
  15158. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  15159. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  15160. return transmittance;
  15161. } );
  15162. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  15163. return vec3( 1.0 );
  15164. } ).setLayout( {
  15165. name: 'volumeAttenuation',
  15166. type: 'vec3',
  15167. inputs: [
  15168. { name: 'transmissionDistance', type: 'float' },
  15169. { name: 'attenuationColor', type: 'vec3' },
  15170. { name: 'attenuationDistance', type: 'float' }
  15171. ]
  15172. } );
  15173. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  15174. let transmittedLight, transmittance;
  15175. if ( dispersion ) {
  15176. transmittedLight = vec4().toVar();
  15177. transmittance = vec3().toVar();
  15178. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  15179. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  15180. Loop( { start: 0, end: 3 }, ( { i } ) => {
  15181. const ior = iors.element( i );
  15182. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15183. const refractedRayExit = position.add( transmissionRay );
  15184. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15185. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15186. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15187. refractionCoords.addAssign( 1.0 );
  15188. refractionCoords.divAssign( 2.0 );
  15189. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15190. // Sample framebuffer to get pixel the refracted ray hits.
  15191. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  15192. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  15193. transmittedLight.a.addAssign( transmissionSample.a );
  15194. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  15195. } );
  15196. transmittedLight.a.divAssign( 3.0 );
  15197. } else {
  15198. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15199. const refractedRayExit = position.add( transmissionRay );
  15200. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15201. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15202. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15203. refractionCoords.addAssign( 1.0 );
  15204. refractionCoords.divAssign( 2.0 );
  15205. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15206. // Sample framebuffer to get pixel the refracted ray hits.
  15207. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  15208. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  15209. }
  15210. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  15211. const dotNV = n.dot( v ).clamp();
  15212. // Get the specular component.
  15213. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  15214. dotNV,
  15215. specularColor,
  15216. specularF90,
  15217. roughness
  15218. } ) );
  15219. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  15220. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  15221. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  15222. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  15223. } );
  15224. //
  15225. // Iridescence
  15226. //
  15227. // XYZ to linear-sRGB color space
  15228. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  15229. 3.2404542, -0.969266, 0.0556434,
  15230. -1.5371385, 1.8760108, -0.2040259,
  15231. -0.4985314, 0.0415560, 1.0572252
  15232. );
  15233. // Assume air interface for top
  15234. // Note: We don't handle the case fresnel0 == 1
  15235. const Fresnel0ToIor = ( fresnel0 ) => {
  15236. const sqrtF0 = fresnel0.sqrt();
  15237. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  15238. };
  15239. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  15240. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  15241. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  15242. };
  15243. // Fresnel equations for dielectric/dielectric interfaces.
  15244. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  15245. // Evaluation XYZ sensitivity curves in Fourier space
  15246. const evalSensitivity = ( OPD, shift ) => {
  15247. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  15248. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  15249. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  15250. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  15251. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( -45282e5 ).exp() );
  15252. let xyz = val.mul( VAR.mul( 2.0 * Math.PI ).sqrt() ).mul( pos.mul( phase ).add( shift ).cos() ).mul( phase.pow2().negate().mul( VAR ).exp() );
  15253. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  15254. const rgb = XYZ_TO_REC709.mul( xyz );
  15255. return rgb;
  15256. };
  15257. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  15258. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  15259. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  15260. // Evaluate the cosTheta on the base layer (Snell law)
  15261. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  15262. // Handle TIR:
  15263. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  15264. If( cosTheta2Sq.lessThan( 0 ), () => {
  15265. return vec3( 1.0 );
  15266. } );
  15267. const cosTheta2 = cosTheta2Sq.sqrt();
  15268. // First interface
  15269. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  15270. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  15271. //const R21 = R12;
  15272. const T121 = R12.oneMinus();
  15273. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  15274. const phi21 = float( Math.PI ).sub( phi12 );
  15275. // Second interface
  15276. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  15277. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  15278. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  15279. const phi23 = vec3(
  15280. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15281. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15282. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  15283. );
  15284. // Phase shift
  15285. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  15286. const phi = vec3( phi21 ).add( phi23 );
  15287. // Compound terms
  15288. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  15289. const r123 = R123.sqrt();
  15290. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  15291. // Reflectance term for m = 0 (DC term amplitude)
  15292. const C0 = R12.add( Rs );
  15293. const I = C0.toVar();
  15294. // Reflectance term for m > 0 (pairs of diracs)
  15295. const Cm = Rs.sub( T121 ).toVar();
  15296. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  15297. Cm.mulAssign( r123 );
  15298. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  15299. I.addAssign( Cm.mul( Sm ) );
  15300. } );
  15301. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  15302. return I.max( vec3( 0.0 ) );
  15303. } ).setLayout( {
  15304. name: 'evalIridescence',
  15305. type: 'vec3',
  15306. inputs: [
  15307. { name: 'outsideIOR', type: 'float' },
  15308. { name: 'eta2', type: 'float' },
  15309. { name: 'cosTheta1', type: 'float' },
  15310. { name: 'thinFilmThickness', type: 'float' },
  15311. { name: 'baseF0', type: 'vec3' }
  15312. ]
  15313. } );
  15314. //
  15315. // Sheen
  15316. //
  15317. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  15318. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  15319. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  15320. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  15321. const dotNV = normal.dot( viewDir ).saturate();
  15322. const r2 = roughness.pow2();
  15323. const a = select(
  15324. roughness.lessThan( 0.25 ),
  15325. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  15326. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  15327. );
  15328. const b = select(
  15329. roughness.lessThan( 0.25 ),
  15330. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  15331. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  15332. );
  15333. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  15334. return DG.mul( 1.0 / Math.PI ).saturate();
  15335. } );
  15336. const clearcoatF0 = vec3( 0.04 );
  15337. const clearcoatF90 = float( 1 );
  15338. /**
  15339. * Represents the lighting model for a PBR material.
  15340. *
  15341. * @augments LightingModel
  15342. */
  15343. class PhysicalLightingModel extends LightingModel {
  15344. /**
  15345. * Constructs a new physical lighting model.
  15346. *
  15347. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15348. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  15349. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  15350. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15351. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  15352. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  15353. */
  15354. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  15355. super();
  15356. /**
  15357. * Whether clearcoat is supported or not.
  15358. *
  15359. * @type {boolean}
  15360. * @default false
  15361. */
  15362. this.clearcoat = clearcoat;
  15363. /**
  15364. * Whether sheen is supported or not.
  15365. *
  15366. * @type {boolean}
  15367. * @default false
  15368. */
  15369. this.sheen = sheen;
  15370. /**
  15371. * Whether iridescence is supported or not.
  15372. *
  15373. * @type {boolean}
  15374. * @default false
  15375. */
  15376. this.iridescence = iridescence;
  15377. /**
  15378. * Whether anisotropy is supported or not.
  15379. *
  15380. * @type {boolean}
  15381. * @default false
  15382. */
  15383. this.anisotropy = anisotropy;
  15384. /**
  15385. * Whether transmission is supported or not.
  15386. *
  15387. * @type {boolean}
  15388. * @default false
  15389. */
  15390. this.transmission = transmission;
  15391. /**
  15392. * Whether dispersion is supported or not.
  15393. *
  15394. * @type {boolean}
  15395. * @default false
  15396. */
  15397. this.dispersion = dispersion;
  15398. /**
  15399. * The clear coat radiance.
  15400. *
  15401. * @type {?Node}
  15402. * @default null
  15403. */
  15404. this.clearcoatRadiance = null;
  15405. /**
  15406. * The clear coat specular direct.
  15407. *
  15408. * @type {?Node}
  15409. * @default null
  15410. */
  15411. this.clearcoatSpecularDirect = null;
  15412. /**
  15413. * The clear coat specular indirect.
  15414. *
  15415. * @type {?Node}
  15416. * @default null
  15417. */
  15418. this.clearcoatSpecularIndirect = null;
  15419. /**
  15420. * The sheen specular direct.
  15421. *
  15422. * @type {?Node}
  15423. * @default null
  15424. */
  15425. this.sheenSpecularDirect = null;
  15426. /**
  15427. * The sheen specular indirect.
  15428. *
  15429. * @type {?Node}
  15430. * @default null
  15431. */
  15432. this.sheenSpecularIndirect = null;
  15433. /**
  15434. * The iridescence Fresnel.
  15435. *
  15436. * @type {?Node}
  15437. * @default null
  15438. */
  15439. this.iridescenceFresnel = null;
  15440. /**
  15441. * The iridescence F0.
  15442. *
  15443. * @type {?Node}
  15444. * @default null
  15445. */
  15446. this.iridescenceF0 = null;
  15447. }
  15448. /**
  15449. * Depending on what features are requested, the method prepares certain node variables
  15450. * which are later used for lighting computations.
  15451. *
  15452. * @param {NodeBuilder} builder - The current node builder.
  15453. */
  15454. start( builder ) {
  15455. if ( this.clearcoat === true ) {
  15456. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  15457. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  15458. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  15459. }
  15460. if ( this.sheen === true ) {
  15461. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  15462. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  15463. }
  15464. if ( this.iridescence === true ) {
  15465. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  15466. this.iridescenceFresnel = evalIridescence( {
  15467. outsideIOR: float( 1.0 ),
  15468. eta2: iridescenceIOR,
  15469. cosTheta1: dotNVi,
  15470. thinFilmThickness: iridescenceThickness,
  15471. baseF0: specularColor
  15472. } );
  15473. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  15474. }
  15475. if ( this.transmission === true ) {
  15476. const position = positionWorld;
  15477. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  15478. const n = transformedNormalWorld;
  15479. const context = builder.context;
  15480. context.backdrop = getIBLVolumeRefraction(
  15481. n,
  15482. v,
  15483. roughness,
  15484. diffuseColor,
  15485. specularColor,
  15486. specularF90, // specularF90
  15487. position, // positionWorld
  15488. modelWorldMatrix, // modelMatrix
  15489. cameraViewMatrix, // viewMatrix
  15490. cameraProjectionMatrix, // projMatrix
  15491. ior,
  15492. thickness,
  15493. attenuationColor,
  15494. attenuationDistance,
  15495. this.dispersion ? dispersion : null
  15496. );
  15497. context.backdropAlpha = transmission;
  15498. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  15499. }
  15500. super.start( builder );
  15501. }
  15502. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  15503. // Approximates multi-scattering in order to preserve energy.
  15504. // http://www.jcgt.org/published/0008/01/03/
  15505. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  15506. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15507. const fab = DFGApprox( { roughness, dotNV } );
  15508. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  15509. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15510. const Ess = fab.x.add( fab.y );
  15511. const Ems = Ess.oneMinus();
  15512. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  15513. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  15514. singleScatter.addAssign( FssEss );
  15515. multiScatter.addAssign( Fms.mul( Ems ) );
  15516. }
  15517. /**
  15518. * Implements the direct light.
  15519. *
  15520. * @param {Object} lightData - The light data.
  15521. * @param {NodeBuilder} builder - The current node builder.
  15522. */
  15523. direct( { lightDirection, lightColor, reflectedLight } ) {
  15524. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  15525. const irradiance = dotNL.mul( lightColor );
  15526. if ( this.sheen === true ) {
  15527. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  15528. }
  15529. if ( this.clearcoat === true ) {
  15530. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  15531. const ccIrradiance = dotNLcc.mul( lightColor );
  15532. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  15533. }
  15534. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15535. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX( { lightDirection, f0: specularColor, f90: 1, roughness, iridescence: this.iridescence, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  15536. }
  15537. /**
  15538. * This method is intended for implementing the direct light term for
  15539. * rect area light nodes.
  15540. *
  15541. * @param {Object} input - The input data.
  15542. * @param {NodeBuilder} builder - The current node builder.
  15543. */
  15544. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  15545. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  15546. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  15547. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  15548. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  15549. const N = transformedNormalView;
  15550. const V = positionViewDirection;
  15551. const P = positionView.toVar();
  15552. const uv = LTC_Uv( { N, V, roughness } );
  15553. const t1 = ltc_1.sample( uv ).toVar();
  15554. const t2 = ltc_2.sample( uv ).toVar();
  15555. const mInv = mat3(
  15556. vec3( t1.x, 0, t1.y ),
  15557. vec3( 0, 1, 0 ),
  15558. vec3( t1.z, 0, t1.w )
  15559. ).toVar();
  15560. // LTC Fresnel Approximation by Stephen Hill
  15561. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  15562. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  15563. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  15564. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseColor ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  15565. }
  15566. /**
  15567. * Implements the indirect lighting.
  15568. *
  15569. * @param {NodeBuilder} builder - The current node builder.
  15570. */
  15571. indirect( builder ) {
  15572. this.indirectDiffuse( builder );
  15573. this.indirectSpecular( builder );
  15574. this.ambientOcclusion( builder );
  15575. }
  15576. /**
  15577. * Implements the indirect diffuse term.
  15578. *
  15579. * @param {NodeBuilder} builder - The current node builder.
  15580. */
  15581. indirectDiffuse( builder ) {
  15582. const { irradiance, reflectedLight } = builder.context;
  15583. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15584. }
  15585. /**
  15586. * Implements the indirect specular term.
  15587. *
  15588. * @param {NodeBuilder} builder - The current node builder.
  15589. */
  15590. indirectSpecular( builder ) {
  15591. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  15592. if ( this.sheen === true ) {
  15593. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  15594. sheen,
  15595. IBLSheenBRDF( {
  15596. normal: transformedNormalView,
  15597. viewDir: positionViewDirection,
  15598. roughness: sheenRoughness
  15599. } )
  15600. ) );
  15601. }
  15602. if ( this.clearcoat === true ) {
  15603. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  15604. const clearcoatEnv = EnvironmentBRDF( {
  15605. dotNV: dotNVcc,
  15606. specularColor: clearcoatF0,
  15607. specularF90: clearcoatF90,
  15608. roughness: clearcoatRoughness
  15609. } );
  15610. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  15611. }
  15612. // Both indirect specular and indirect diffuse light accumulate here
  15613. const singleScattering = vec3().toVar( 'singleScattering' );
  15614. const multiScattering = vec3().toVar( 'multiScattering' );
  15615. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  15616. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  15617. const totalScattering = singleScattering.add( multiScattering );
  15618. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  15619. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  15620. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  15621. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  15622. }
  15623. /**
  15624. * Implements the ambient occlusion term.
  15625. *
  15626. * @param {NodeBuilder} builder - The current node builder.
  15627. */
  15628. ambientOcclusion( builder ) {
  15629. const { ambientOcclusion, reflectedLight } = builder.context;
  15630. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15631. const aoNV = dotNV.add( ambientOcclusion );
  15632. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  15633. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  15634. if ( this.clearcoat === true ) {
  15635. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  15636. }
  15637. if ( this.sheen === true ) {
  15638. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  15639. }
  15640. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15641. reflectedLight.indirectSpecular.mulAssign( aoNode );
  15642. }
  15643. /**
  15644. * Used for final lighting accumulations depending on the requested features.
  15645. *
  15646. * @param {NodeBuilder} builder - The current node builder.
  15647. */
  15648. finish( { context } ) {
  15649. const { outgoingLight } = context;
  15650. if ( this.clearcoat === true ) {
  15651. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  15652. const Fcc = F_Schlick( {
  15653. dotVH: dotNVcc,
  15654. f0: clearcoatF0,
  15655. f90: clearcoatF90
  15656. } );
  15657. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  15658. outgoingLight.assign( clearcoatLight );
  15659. }
  15660. if ( this.sheen === true ) {
  15661. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  15662. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  15663. outgoingLight.assign( sheenLight );
  15664. }
  15665. }
  15666. }
  15667. // These defines must match with PMREMGenerator
  15668. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  15669. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  15670. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  15671. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  15672. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  15673. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  15674. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  15675. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  15676. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  15677. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  15678. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  15679. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  15680. // These shader functions convert between the UV coordinates of a single face of
  15681. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  15682. // sampling a textureCube (not generally normalized ).
  15683. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  15684. const absDirection = vec3( abs( direction ) ).toVar();
  15685. const face = float( -1 ).toVar();
  15686. If( absDirection.x.greaterThan( absDirection.z ), () => {
  15687. If( absDirection.x.greaterThan( absDirection.y ), () => {
  15688. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  15689. } ).Else( () => {
  15690. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  15691. } );
  15692. } ).Else( () => {
  15693. If( absDirection.z.greaterThan( absDirection.y ), () => {
  15694. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  15695. } ).Else( () => {
  15696. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  15697. } );
  15698. } );
  15699. return face;
  15700. } ).setLayout( {
  15701. name: 'getFace',
  15702. type: 'float',
  15703. inputs: [
  15704. { name: 'direction', type: 'vec3' }
  15705. ]
  15706. } );
  15707. // RH coordinate system; PMREM face-indexing convention
  15708. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  15709. const uv = vec2().toVar();
  15710. If( face.equal( 0.0 ), () => {
  15711. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  15712. } ).ElseIf( face.equal( 1.0 ), () => {
  15713. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  15714. } ).ElseIf( face.equal( 2.0 ), () => {
  15715. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  15716. } ).ElseIf( face.equal( 3.0 ), () => {
  15717. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  15718. } ).ElseIf( face.equal( 4.0 ), () => {
  15719. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  15720. } ).Else( () => {
  15721. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  15722. } );
  15723. return mul( 0.5, uv.add( 1.0 ) );
  15724. } ).setLayout( {
  15725. name: 'getUV',
  15726. type: 'vec2',
  15727. inputs: [
  15728. { name: 'direction', type: 'vec3' },
  15729. { name: 'face', type: 'float' }
  15730. ]
  15731. } );
  15732. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  15733. const mip = float( 0.0 ).toVar();
  15734. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  15735. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  15736. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  15737. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  15738. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  15739. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  15740. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  15741. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  15742. } ).Else( () => {
  15743. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  15744. } );
  15745. return mip;
  15746. } ).setLayout( {
  15747. name: 'roughnessToMip',
  15748. type: 'float',
  15749. inputs: [
  15750. { name: 'roughness', type: 'float' }
  15751. ]
  15752. } );
  15753. // RH coordinate system; PMREM face-indexing convention
  15754. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  15755. const uv = uv_immutable.toVar();
  15756. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  15757. const direction = vec3( uv, 1.0 ).toVar();
  15758. If( face.equal( 0.0 ), () => {
  15759. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  15760. } ).ElseIf( face.equal( 1.0 ), () => {
  15761. direction.assign( direction.xzy );
  15762. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  15763. } ).ElseIf( face.equal( 2.0 ), () => {
  15764. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  15765. } ).ElseIf( face.equal( 3.0 ), () => {
  15766. direction.assign( direction.zyx );
  15767. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  15768. } ).ElseIf( face.equal( 4.0 ), () => {
  15769. direction.assign( direction.xzy );
  15770. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  15771. } ).ElseIf( face.equal( 5.0 ), () => {
  15772. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  15773. } );
  15774. return direction;
  15775. } ).setLayout( {
  15776. name: 'getDirection',
  15777. type: 'vec3',
  15778. inputs: [
  15779. { name: 'uv', type: 'vec2' },
  15780. { name: 'face', type: 'float' }
  15781. ]
  15782. } );
  15783. //
  15784. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  15785. const roughness = float( roughness_immutable );
  15786. const sampleDir = vec3( sampleDir_immutable );
  15787. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  15788. const mipF = fract( mip );
  15789. const mipInt = floor( mip );
  15790. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  15791. If( mipF.notEqual( 0.0 ), () => {
  15792. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  15793. color0.assign( mix( color0, color1, mipF ) );
  15794. } );
  15795. return color0;
  15796. } );
  15797. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  15798. const mipInt = float( mipInt_immutable ).toVar();
  15799. const direction = vec3( direction_immutable );
  15800. const face = float( getFace( direction ) ).toVar();
  15801. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  15802. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  15803. const faceSize = float( exp2( mipInt ) ).toVar();
  15804. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  15805. If( face.greaterThan( 2.0 ), () => {
  15806. uv.y.addAssign( faceSize );
  15807. face.subAssign( 3.0 );
  15808. } );
  15809. uv.x.addAssign( face.mul( faceSize ) );
  15810. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  15811. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  15812. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  15813. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  15814. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  15815. } );
  15816. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  15817. const cosTheta = cos( theta );
  15818. // Rodrigues' axis-angle rotation
  15819. const sampleDirection = outputDirection.mul( cosTheta )
  15820. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  15821. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  15822. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  15823. } );
  15824. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  15825. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  15826. If( axis.equal( vec3( 0.0 ) ), () => {
  15827. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  15828. } );
  15829. axis.assign( normalize( axis ) );
  15830. const gl_FragColor = vec3().toVar();
  15831. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  15832. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  15833. If( i.greaterThanEqual( samples ), () => {
  15834. Break();
  15835. } );
  15836. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  15837. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( -1 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  15838. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  15839. } );
  15840. return vec4( gl_FragColor, 1 );
  15841. } );
  15842. const LOD_MIN = 4;
  15843. // The standard deviations (radians) associated with the extra mips. These are
  15844. // chosen to approximate a Trowbridge-Reitz distribution function times the
  15845. // geometric shadowing function. These sigma values squared must match the
  15846. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  15847. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  15848. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  15849. // samples and exit early, but not recompile the shader.
  15850. const MAX_SAMPLES = 20;
  15851. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  15852. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  15853. const _clearColor$2 = /*@__PURE__*/ new Color();
  15854. let _oldTarget = null;
  15855. let _oldActiveCubeFace = 0;
  15856. let _oldActiveMipmapLevel = 0;
  15857. // Golden Ratio
  15858. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  15859. const INV_PHI = 1 / PHI;
  15860. // Vertices of a dodecahedron (except the opposites, which represent the
  15861. // same axis), used as axis directions evenly spread on a sphere.
  15862. const _axisDirections = [
  15863. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  15864. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  15865. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  15866. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  15867. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  15868. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  15869. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  15870. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  15871. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  15872. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  15873. ];
  15874. const _origin = /*@__PURE__*/ new Vector3();
  15875. // maps blur materials to their uniforms dictionary
  15876. const _uniformsMap = new WeakMap();
  15877. // WebGPU Face indices
  15878. const _faceLib = [
  15879. 3, 1, 5,
  15880. 0, 4, 2
  15881. ];
  15882. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  15883. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  15884. /**
  15885. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  15886. * (PMREM) from a cubeMap environment texture. This allows different levels of
  15887. * blur to be quickly accessed based on material roughness. It is packed into a
  15888. * special CubeUV format that allows us to perform custom interpolation so that
  15889. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  15890. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  15891. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  15892. * higher roughness levels. In this way we maintain resolution to smoothly
  15893. * interpolate diffuse lighting while limiting sampling computation.
  15894. *
  15895. * Paper: Fast, Accurate Image-Based Lighting:
  15896. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  15897. */
  15898. class PMREMGenerator {
  15899. /**
  15900. * Constructs a new PMREM generator.
  15901. *
  15902. * @param {Renderer} renderer - The renderer.
  15903. */
  15904. constructor( renderer ) {
  15905. this._renderer = renderer;
  15906. this._pingPongRenderTarget = null;
  15907. this._lodMax = 0;
  15908. this._cubeSize = 0;
  15909. this._lodPlanes = [];
  15910. this._sizeLods = [];
  15911. this._sigmas = [];
  15912. this._lodMeshes = [];
  15913. this._blurMaterial = null;
  15914. this._cubemapMaterial = null;
  15915. this._equirectMaterial = null;
  15916. this._backgroundBox = null;
  15917. }
  15918. get _hasInitialized() {
  15919. return this._renderer.hasInitialized();
  15920. }
  15921. /**
  15922. * Generates a PMREM from a supplied Scene, which can be faster than using an
  15923. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  15924. * in radians to be applied to the scene before PMREM generation. Optional near
  15925. * and far planes ensure the scene is rendered in its entirety.
  15926. *
  15927. * @param {Scene} scene - The scene to be captured.
  15928. * @param {number} [sigma=0] - The blur radius in radians.
  15929. * @param {number} [near=0.1] - The near plane distance.
  15930. * @param {number} [far=100] - The far plane distance.
  15931. * @param {Object} [options={}] - The configuration options.
  15932. * @param {number} [options.size=256] - The texture size of the PMREM.
  15933. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  15934. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  15935. * @return {RenderTarget} The resulting PMREM.
  15936. * @see {@link PMREMGenerator#fromSceneAsync}
  15937. */
  15938. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  15939. const {
  15940. size = 256,
  15941. position = _origin,
  15942. renderTarget = null,
  15943. } = options;
  15944. this._setSize( size );
  15945. if ( this._hasInitialized === false ) {
  15946. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  15947. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  15948. options.renderTarget = cubeUVRenderTarget;
  15949. this.fromSceneAsync( scene, sigma, near, far, options );
  15950. return cubeUVRenderTarget;
  15951. }
  15952. _oldTarget = this._renderer.getRenderTarget();
  15953. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  15954. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  15955. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  15956. cubeUVRenderTarget.depthBuffer = true;
  15957. this._init( cubeUVRenderTarget );
  15958. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  15959. if ( sigma > 0 ) {
  15960. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  15961. }
  15962. this._applyPMREM( cubeUVRenderTarget );
  15963. this._cleanup( cubeUVRenderTarget );
  15964. return cubeUVRenderTarget;
  15965. }
  15966. /**
  15967. * Generates a PMREM from a supplied Scene, which can be faster than using an
  15968. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  15969. * in radians to be applied to the scene before PMREM generation. Optional near
  15970. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  15971. * is placed at the origin).
  15972. *
  15973. * @param {Scene} scene - The scene to be captured.
  15974. * @param {number} [sigma=0] - The blur radius in radians.
  15975. * @param {number} [near=0.1] - The near plane distance.
  15976. * @param {number} [far=100] - The far plane distance.
  15977. * @param {Object} [options={}] - The configuration options.
  15978. * @param {number} [options.size=256] - The texture size of the PMREM.
  15979. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  15980. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  15981. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  15982. * @see {@link PMREMGenerator#fromScene}
  15983. */
  15984. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  15985. if ( this._hasInitialized === false ) await this._renderer.init();
  15986. return this.fromScene( scene, sigma, near, far, options );
  15987. }
  15988. /**
  15989. * Generates a PMREM from an equirectangular texture, which can be either LDR
  15990. * or HDR. The ideal input image size is 1k (1024 x 512),
  15991. * as this matches best with the 256 x 256 cubemap output.
  15992. *
  15993. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  15994. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  15995. * @return {RenderTarget} The resulting PMREM.
  15996. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  15997. */
  15998. fromEquirectangular( equirectangular, renderTarget = null ) {
  15999. if ( this._hasInitialized === false ) {
  16000. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  16001. this._setSizeFromTexture( equirectangular );
  16002. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16003. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  16004. return cubeUVRenderTarget;
  16005. }
  16006. return this._fromTexture( equirectangular, renderTarget );
  16007. }
  16008. /**
  16009. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16010. * or HDR. The ideal input image size is 1k (1024 x 512),
  16011. * as this matches best with the 256 x 256 cubemap output.
  16012. *
  16013. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16014. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16015. * @return {Promise<RenderTarget>} The resulting PMREM.
  16016. * @see {@link PMREMGenerator#fromEquirectangular}
  16017. */
  16018. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  16019. if ( this._hasInitialized === false ) await this._renderer.init();
  16020. return this._fromTexture( equirectangular, renderTarget );
  16021. }
  16022. /**
  16023. * Generates a PMREM from an cubemap texture, which can be either LDR
  16024. * or HDR. The ideal input cube size is 256 x 256,
  16025. * as this matches best with the 256 x 256 cubemap output.
  16026. *
  16027. * @param {Texture} cubemap - The cubemap texture to be converted.
  16028. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16029. * @return {RenderTarget} The resulting PMREM.
  16030. * @see {@link PMREMGenerator#fromCubemapAsync}
  16031. */
  16032. fromCubemap( cubemap, renderTarget = null ) {
  16033. if ( this._hasInitialized === false ) {
  16034. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  16035. this._setSizeFromTexture( cubemap );
  16036. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16037. this.fromCubemapAsync( cubemap, renderTarget );
  16038. return cubeUVRenderTarget;
  16039. }
  16040. return this._fromTexture( cubemap, renderTarget );
  16041. }
  16042. /**
  16043. * Generates a PMREM from an cubemap texture, which can be either LDR
  16044. * or HDR. The ideal input cube size is 256 x 256,
  16045. * with the 256 x 256 cubemap output.
  16046. *
  16047. * @param {Texture} cubemap - The cubemap texture to be converted.
  16048. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16049. * @return {Promise<RenderTarget>} The resulting PMREM.
  16050. * @see {@link PMREMGenerator#fromCubemap}
  16051. */
  16052. async fromCubemapAsync( cubemap, renderTarget = null ) {
  16053. if ( this._hasInitialized === false ) await this._renderer.init();
  16054. return this._fromTexture( cubemap, renderTarget );
  16055. }
  16056. /**
  16057. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  16058. * your texture's network fetch for increased concurrency.
  16059. *
  16060. * @returns {Promise}
  16061. */
  16062. async compileCubemapShader() {
  16063. if ( this._cubemapMaterial === null ) {
  16064. this._cubemapMaterial = _getCubemapMaterial();
  16065. await this._compileMaterial( this._cubemapMaterial );
  16066. }
  16067. }
  16068. /**
  16069. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  16070. * your texture's network fetch for increased concurrency.
  16071. *
  16072. * @returns {Promise}
  16073. */
  16074. async compileEquirectangularShader() {
  16075. if ( this._equirectMaterial === null ) {
  16076. this._equirectMaterial = _getEquirectMaterial();
  16077. await this._compileMaterial( this._equirectMaterial );
  16078. }
  16079. }
  16080. /**
  16081. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  16082. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  16083. * one of them will cause any others to also become unusable.
  16084. */
  16085. dispose() {
  16086. this._dispose();
  16087. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  16088. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  16089. if ( this._backgroundBox !== null ) {
  16090. this._backgroundBox.geometry.dispose();
  16091. this._backgroundBox.material.dispose();
  16092. }
  16093. }
  16094. // private interface
  16095. _setSizeFromTexture( texture ) {
  16096. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  16097. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  16098. } else { // Equirectangular
  16099. this._setSize( texture.image.width / 4 );
  16100. }
  16101. }
  16102. _setSize( cubeSize ) {
  16103. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  16104. this._cubeSize = Math.pow( 2, this._lodMax );
  16105. }
  16106. _dispose() {
  16107. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  16108. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  16109. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  16110. this._lodPlanes[ i ].dispose();
  16111. }
  16112. }
  16113. _cleanup( outputTarget ) {
  16114. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  16115. outputTarget.scissorTest = false;
  16116. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  16117. }
  16118. _fromTexture( texture, renderTarget ) {
  16119. this._setSizeFromTexture( texture );
  16120. _oldTarget = this._renderer.getRenderTarget();
  16121. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16122. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16123. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16124. this._init( cubeUVRenderTarget );
  16125. this._textureToCubeUV( texture, cubeUVRenderTarget );
  16126. this._applyPMREM( cubeUVRenderTarget );
  16127. this._cleanup( cubeUVRenderTarget );
  16128. return cubeUVRenderTarget;
  16129. }
  16130. _allocateTarget() {
  16131. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  16132. const height = 4 * this._cubeSize;
  16133. const cubeUVRenderTarget = _createRenderTarget( width, height );
  16134. return cubeUVRenderTarget;
  16135. }
  16136. _init( renderTarget ) {
  16137. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  16138. if ( this._pingPongRenderTarget !== null ) {
  16139. this._dispose();
  16140. }
  16141. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  16142. const { _lodMax } = this;
  16143. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  16144. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  16145. }
  16146. }
  16147. async _compileMaterial( material ) {
  16148. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  16149. await this._renderer.compile( tmpMesh, _flatCamera );
  16150. }
  16151. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  16152. const cubeCamera = _cubeCamera;
  16153. cubeCamera.near = near;
  16154. cubeCamera.far = far;
  16155. // px, py, pz, nx, ny, nz
  16156. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  16157. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  16158. const renderer = this._renderer;
  16159. const originalAutoClear = renderer.autoClear;
  16160. renderer.getClearColor( _clearColor$2 );
  16161. renderer.autoClear = false;
  16162. let backgroundBox = this._backgroundBox;
  16163. if ( backgroundBox === null ) {
  16164. const backgroundMaterial = new MeshBasicMaterial( {
  16165. name: 'PMREM.Background',
  16166. side: BackSide,
  16167. depthWrite: false,
  16168. depthTest: false
  16169. } );
  16170. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  16171. }
  16172. let useSolidColor = false;
  16173. const background = scene.background;
  16174. if ( background ) {
  16175. if ( background.isColor ) {
  16176. backgroundBox.material.color.copy( background );
  16177. scene.background = null;
  16178. useSolidColor = true;
  16179. }
  16180. } else {
  16181. backgroundBox.material.color.copy( _clearColor$2 );
  16182. useSolidColor = true;
  16183. }
  16184. renderer.setRenderTarget( cubeUVRenderTarget );
  16185. renderer.clear();
  16186. if ( useSolidColor ) {
  16187. renderer.render( backgroundBox, cubeCamera );
  16188. }
  16189. for ( let i = 0; i < 6; i ++ ) {
  16190. const col = i % 3;
  16191. if ( col === 0 ) {
  16192. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16193. cubeCamera.position.set( position.x, position.y, position.z );
  16194. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  16195. } else if ( col === 1 ) {
  16196. cubeCamera.up.set( 0, 0, upSign[ i ] );
  16197. cubeCamera.position.set( position.x, position.y, position.z );
  16198. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  16199. } else {
  16200. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16201. cubeCamera.position.set( position.x, position.y, position.z );
  16202. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  16203. }
  16204. const size = this._cubeSize;
  16205. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  16206. renderer.render( scene, cubeCamera );
  16207. }
  16208. renderer.autoClear = originalAutoClear;
  16209. scene.background = background;
  16210. }
  16211. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  16212. const renderer = this._renderer;
  16213. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  16214. if ( isCubeTexture ) {
  16215. if ( this._cubemapMaterial === null ) {
  16216. this._cubemapMaterial = _getCubemapMaterial( texture );
  16217. }
  16218. } else {
  16219. if ( this._equirectMaterial === null ) {
  16220. this._equirectMaterial = _getEquirectMaterial( texture );
  16221. }
  16222. }
  16223. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  16224. material.fragmentNode.value = texture;
  16225. const mesh = this._lodMeshes[ 0 ];
  16226. mesh.material = material;
  16227. const size = this._cubeSize;
  16228. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  16229. renderer.setRenderTarget( cubeUVRenderTarget );
  16230. renderer.render( mesh, _flatCamera );
  16231. }
  16232. _applyPMREM( cubeUVRenderTarget ) {
  16233. const renderer = this._renderer;
  16234. const autoClear = renderer.autoClear;
  16235. renderer.autoClear = false;
  16236. const n = this._lodPlanes.length;
  16237. for ( let i = 1; i < n; i ++ ) {
  16238. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  16239. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  16240. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  16241. }
  16242. renderer.autoClear = autoClear;
  16243. }
  16244. /**
  16245. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  16246. * vertically and horizontally, but this breaks down on a cube. Here we apply
  16247. * the blur latitudinally (around the poles), and then longitudinally (towards
  16248. * the poles) to approximate the orthogonally-separable blur. It is least
  16249. * accurate at the poles, but still does a decent job.
  16250. *
  16251. * @private
  16252. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  16253. * @param {number} lodIn - The input level-of-detail.
  16254. * @param {number} lodOut - The output level-of-detail.
  16255. * @param {number} sigma - The blur radius in radians.
  16256. * @param {Vector3} [poleAxis] - The pole axis.
  16257. */
  16258. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  16259. const pingPongRenderTarget = this._pingPongRenderTarget;
  16260. this._halfBlur(
  16261. cubeUVRenderTarget,
  16262. pingPongRenderTarget,
  16263. lodIn,
  16264. lodOut,
  16265. sigma,
  16266. 'latitudinal',
  16267. poleAxis );
  16268. this._halfBlur(
  16269. pingPongRenderTarget,
  16270. cubeUVRenderTarget,
  16271. lodOut,
  16272. lodOut,
  16273. sigma,
  16274. 'longitudinal',
  16275. poleAxis );
  16276. }
  16277. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  16278. const renderer = this._renderer;
  16279. const blurMaterial = this._blurMaterial;
  16280. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  16281. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  16282. }
  16283. // Number of standard deviations at which to cut off the discrete approximation.
  16284. const STANDARD_DEVIATIONS = 3;
  16285. const blurMesh = this._lodMeshes[ lodOut ];
  16286. blurMesh.material = blurMaterial;
  16287. const blurUniforms = _uniformsMap.get( blurMaterial );
  16288. const pixels = this._sizeLods[ lodIn ] - 1;
  16289. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  16290. const sigmaPixels = sigmaRadians / radiansPerPixel;
  16291. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  16292. if ( samples > MAX_SAMPLES ) {
  16293. console.warn( `sigmaRadians, ${
  16294. sigmaRadians}, is too large and will clip, as it requested ${
  16295. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  16296. }
  16297. const weights = [];
  16298. let sum = 0;
  16299. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  16300. const x = i / sigmaPixels;
  16301. const weight = Math.exp( - x * x / 2 );
  16302. weights.push( weight );
  16303. if ( i === 0 ) {
  16304. sum += weight;
  16305. } else if ( i < samples ) {
  16306. sum += 2 * weight;
  16307. }
  16308. }
  16309. for ( let i = 0; i < weights.length; i ++ ) {
  16310. weights[ i ] = weights[ i ] / sum;
  16311. }
  16312. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  16313. blurUniforms.envMap.value = targetIn.texture;
  16314. blurUniforms.samples.value = samples;
  16315. blurUniforms.weights.array = weights;
  16316. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  16317. if ( poleAxis ) {
  16318. blurUniforms.poleAxis.value = poleAxis;
  16319. }
  16320. const { _lodMax } = this;
  16321. blurUniforms.dTheta.value = radiansPerPixel;
  16322. blurUniforms.mipInt.value = _lodMax - lodIn;
  16323. const outputSize = this._sizeLods[ lodOut ];
  16324. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  16325. const y = 4 * ( this._cubeSize - outputSize );
  16326. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  16327. renderer.setRenderTarget( targetOut );
  16328. renderer.render( blurMesh, _flatCamera );
  16329. }
  16330. }
  16331. function _createPlanes( lodMax ) {
  16332. const lodPlanes = [];
  16333. const sizeLods = [];
  16334. const sigmas = [];
  16335. const lodMeshes = [];
  16336. let lod = lodMax;
  16337. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  16338. for ( let i = 0; i < totalLods; i ++ ) {
  16339. const sizeLod = Math.pow( 2, lod );
  16340. sizeLods.push( sizeLod );
  16341. let sigma = 1.0 / sizeLod;
  16342. if ( i > lodMax - LOD_MIN ) {
  16343. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  16344. } else if ( i === 0 ) {
  16345. sigma = 0;
  16346. }
  16347. sigmas.push( sigma );
  16348. const texelSize = 1.0 / ( sizeLod - 2 );
  16349. const min = - texelSize;
  16350. const max = 1 + texelSize;
  16351. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  16352. const cubeFaces = 6;
  16353. const vertices = 6;
  16354. const positionSize = 3;
  16355. const uvSize = 2;
  16356. const faceIndexSize = 1;
  16357. const position = new Float32Array( positionSize * vertices * cubeFaces );
  16358. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  16359. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  16360. for ( let face = 0; face < cubeFaces; face ++ ) {
  16361. const x = ( face % 3 ) * 2 / 3 - 1;
  16362. const y = face > 2 ? 0 : -1;
  16363. const coordinates = [
  16364. x, y, 0,
  16365. x + 2 / 3, y, 0,
  16366. x + 2 / 3, y + 1, 0,
  16367. x, y, 0,
  16368. x + 2 / 3, y + 1, 0,
  16369. x, y + 1, 0
  16370. ];
  16371. const faceIdx = _faceLib[ face ];
  16372. position.set( coordinates, positionSize * vertices * faceIdx );
  16373. uv.set( uv1, uvSize * vertices * faceIdx );
  16374. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  16375. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  16376. }
  16377. const planes = new BufferGeometry();
  16378. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  16379. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  16380. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  16381. lodPlanes.push( planes );
  16382. lodMeshes.push( new Mesh( planes, null ) );
  16383. if ( lod > LOD_MIN ) {
  16384. lod --;
  16385. }
  16386. }
  16387. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  16388. }
  16389. function _createRenderTarget( width, height ) {
  16390. const params = {
  16391. magFilter: LinearFilter,
  16392. minFilter: LinearFilter,
  16393. generateMipmaps: false,
  16394. type: HalfFloatType,
  16395. format: RGBAFormat,
  16396. colorSpace: LinearSRGBColorSpace,
  16397. //depthBuffer: false
  16398. };
  16399. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  16400. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  16401. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  16402. cubeUVRenderTarget.texture.isPMREMTexture = true;
  16403. cubeUVRenderTarget.scissorTest = true;
  16404. return cubeUVRenderTarget;
  16405. }
  16406. function _setViewport( target, x, y, width, height ) {
  16407. target.viewport.set( x, y, width, height );
  16408. target.scissor.set( x, y, width, height );
  16409. }
  16410. function _getMaterial( type ) {
  16411. const material = new NodeMaterial();
  16412. material.depthTest = false;
  16413. material.depthWrite = false;
  16414. material.blending = NoBlending;
  16415. material.name = `PMREM_${ type }`;
  16416. return material;
  16417. }
  16418. function _getBlurShader( lodMax, width, height ) {
  16419. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  16420. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  16421. const dTheta = uniform( 0 );
  16422. const n = float( MAX_SAMPLES );
  16423. const latitudinal = uniform( 0 ); // false, bool
  16424. const samples = uniform( 1 ); // int
  16425. const envMap = texture( null );
  16426. const mipInt = uniform( 0 ); // int
  16427. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  16428. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  16429. const CUBEUV_MAX_MIP = float( lodMax );
  16430. const materialUniforms = {
  16431. n,
  16432. latitudinal,
  16433. weights,
  16434. poleAxis,
  16435. outputDirection: _outputDirection,
  16436. dTheta,
  16437. samples,
  16438. envMap,
  16439. mipInt,
  16440. CUBEUV_TEXEL_WIDTH,
  16441. CUBEUV_TEXEL_HEIGHT,
  16442. CUBEUV_MAX_MIP
  16443. };
  16444. const material = _getMaterial( 'blur' );
  16445. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  16446. _uniformsMap.set( material, materialUniforms );
  16447. return material;
  16448. }
  16449. function _getCubemapMaterial( envTexture ) {
  16450. const material = _getMaterial( 'cubemap' );
  16451. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  16452. return material;
  16453. }
  16454. function _getEquirectMaterial( envTexture ) {
  16455. const material = _getMaterial( 'equirect' );
  16456. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  16457. return material;
  16458. }
  16459. const _cache = new WeakMap();
  16460. /**
  16461. * Generates the cubeUV size based on the given image height.
  16462. *
  16463. * @private
  16464. * @param {number} imageHeight - The image height.
  16465. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  16466. */
  16467. function _generateCubeUVSize( imageHeight ) {
  16468. const maxMip = Math.log2( imageHeight ) - 2;
  16469. const texelHeight = 1.0 / imageHeight;
  16470. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  16471. return { texelWidth, texelHeight, maxMip };
  16472. }
  16473. /**
  16474. * Generates a PMREM from the given texture.
  16475. *
  16476. * @private
  16477. * @param {Texture} texture - The texture to create the PMREM for.
  16478. * @param {Renderer} renderer - The renderer.
  16479. * @param {PMREMGenerator} generator - The PMREM generator.
  16480. * @return {?Texture} The PMREM.
  16481. */
  16482. function _getPMREMFromTexture( texture, renderer, generator ) {
  16483. const cache = _getCache( renderer );
  16484. let cacheTexture = cache.get( texture );
  16485. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  16486. if ( pmremVersion !== texture.pmremVersion ) {
  16487. const image = texture.image;
  16488. if ( texture.isCubeTexture ) {
  16489. if ( isCubeMapReady( image ) ) {
  16490. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  16491. } else {
  16492. return null;
  16493. }
  16494. } else {
  16495. if ( isEquirectangularMapReady( image ) ) {
  16496. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  16497. } else {
  16498. return null;
  16499. }
  16500. }
  16501. cacheTexture.pmremVersion = texture.pmremVersion;
  16502. cache.set( texture, cacheTexture );
  16503. }
  16504. return cacheTexture.texture;
  16505. }
  16506. /**
  16507. * Returns a cache that stores generated PMREMs for the respective textures.
  16508. * A cache must be maintained per renderer since PMREMs are render target textures
  16509. * which can't be shared across render contexts.
  16510. *
  16511. * @private
  16512. * @param {Renderer} renderer - The renderer.
  16513. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  16514. */
  16515. function _getCache( renderer ) {
  16516. let rendererCache = _cache.get( renderer );
  16517. if ( rendererCache === undefined ) {
  16518. rendererCache = new WeakMap();
  16519. _cache.set( renderer, rendererCache );
  16520. }
  16521. return rendererCache;
  16522. }
  16523. /**
  16524. * This node represents a PMREM which is a special type of preprocessed
  16525. * environment map intended for PBR materials.
  16526. *
  16527. * ```js
  16528. * const material = new MeshStandardNodeMaterial();
  16529. * material.envNode = pmremTexture( envMap );
  16530. * ```
  16531. *
  16532. * @augments TempNode
  16533. */
  16534. class PMREMNode extends TempNode {
  16535. static get type() {
  16536. return 'PMREMNode';
  16537. }
  16538. /**
  16539. * Constructs a new function overloading node.
  16540. *
  16541. * @param {Texture} value - The input texture.
  16542. * @param {Node<vec2>} [uvNode=null] - The uv node.
  16543. * @param {Node<float>} [levelNode=null] - The level node.
  16544. */
  16545. constructor( value, uvNode = null, levelNode = null ) {
  16546. super( 'vec3' );
  16547. /**
  16548. * Reference to the input texture.
  16549. *
  16550. * @private
  16551. * @type {Texture}
  16552. */
  16553. this._value = value;
  16554. /**
  16555. * Reference to the generated PMREM.
  16556. *
  16557. * @private
  16558. * @type {Texture | null}
  16559. * @default null
  16560. */
  16561. this._pmrem = null;
  16562. /**
  16563. * The uv node.
  16564. *
  16565. * @type {Node<vec2>}
  16566. */
  16567. this.uvNode = uvNode;
  16568. /**
  16569. * The level node.
  16570. *
  16571. * @type {Node<float>}
  16572. */
  16573. this.levelNode = levelNode;
  16574. /**
  16575. * Reference to a PMREM generator.
  16576. *
  16577. * @private
  16578. * @type {?PMREMGenerator}
  16579. * @default null
  16580. */
  16581. this._generator = null;
  16582. const defaultTexture = new Texture();
  16583. defaultTexture.isRenderTargetTexture = true;
  16584. /**
  16585. * The texture node holding the generated PMREM.
  16586. *
  16587. * @private
  16588. * @type {TextureNode}
  16589. */
  16590. this._texture = texture( defaultTexture );
  16591. /**
  16592. * A uniform representing the PMREM's width.
  16593. *
  16594. * @private
  16595. * @type {UniformNode<float>}
  16596. */
  16597. this._width = uniform( 0 );
  16598. /**
  16599. * A uniform representing the PMREM's height.
  16600. *
  16601. * @private
  16602. * @type {UniformNode<float>}
  16603. */
  16604. this._height = uniform( 0 );
  16605. /**
  16606. * A uniform representing the PMREM's max Mip.
  16607. *
  16608. * @private
  16609. * @type {UniformNode<float>}
  16610. */
  16611. this._maxMip = uniform( 0 );
  16612. /**
  16613. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  16614. *
  16615. * @type {string}
  16616. * @default 'render'
  16617. */
  16618. this.updateBeforeType = NodeUpdateType.RENDER;
  16619. }
  16620. set value( value ) {
  16621. this._value = value;
  16622. this._pmrem = null;
  16623. }
  16624. /**
  16625. * The node's texture value.
  16626. *
  16627. * @type {Texture}
  16628. */
  16629. get value() {
  16630. return this._value;
  16631. }
  16632. /**
  16633. * Uses the given PMREM texture to update internal values.
  16634. *
  16635. * @param {Texture} texture - The PMREM texture.
  16636. */
  16637. updateFromTexture( texture ) {
  16638. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  16639. this._texture.value = texture;
  16640. this._width.value = cubeUVSize.texelWidth;
  16641. this._height.value = cubeUVSize.texelHeight;
  16642. this._maxMip.value = cubeUVSize.maxMip;
  16643. }
  16644. updateBefore( frame ) {
  16645. let pmrem = this._pmrem;
  16646. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  16647. const texture = this._value;
  16648. if ( pmremVersion !== texture.pmremVersion ) {
  16649. if ( texture.isPMREMTexture === true ) {
  16650. pmrem = texture;
  16651. } else {
  16652. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  16653. }
  16654. if ( pmrem !== null ) {
  16655. this._pmrem = pmrem;
  16656. this.updateFromTexture( pmrem );
  16657. }
  16658. }
  16659. }
  16660. setup( builder ) {
  16661. if ( this._generator === null ) {
  16662. this._generator = new PMREMGenerator( builder.renderer );
  16663. }
  16664. this.updateBefore( builder );
  16665. //
  16666. let uvNode = this.uvNode;
  16667. if ( uvNode === null && builder.context.getUV ) {
  16668. uvNode = builder.context.getUV( this );
  16669. }
  16670. //
  16671. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  16672. //
  16673. let levelNode = this.levelNode;
  16674. if ( levelNode === null && builder.context.getTextureLevel ) {
  16675. levelNode = builder.context.getTextureLevel( this );
  16676. }
  16677. //
  16678. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  16679. }
  16680. dispose() {
  16681. super.dispose();
  16682. if ( this._generator !== null ) this._generator.dispose();
  16683. }
  16684. }
  16685. /**
  16686. * Returns `true` if the given cube map image has been fully loaded.
  16687. *
  16688. * @private
  16689. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  16690. * @return {boolean} Whether the given cube map is ready or not.
  16691. */
  16692. function isCubeMapReady( image ) {
  16693. if ( image === null || image === undefined ) return false;
  16694. let count = 0;
  16695. const length = 6;
  16696. for ( let i = 0; i < length; i ++ ) {
  16697. if ( image[ i ] !== undefined ) count ++;
  16698. }
  16699. return count === length;
  16700. }
  16701. /**
  16702. * Returns `true` if the given equirectangular image has been fully loaded.
  16703. *
  16704. * @private
  16705. * @param {(Image|Object)} image - The equirectangular image.
  16706. * @return {boolean} Whether the given cube map is ready or not.
  16707. */
  16708. function isEquirectangularMapReady( image ) {
  16709. if ( image === null || image === undefined ) return false;
  16710. return image.height > 0;
  16711. }
  16712. /**
  16713. * TSL function for creating a PMREM node.
  16714. *
  16715. * @tsl
  16716. * @function
  16717. * @param {Texture} value - The input texture.
  16718. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  16719. * @param {?Node<float>} [levelNode=null] - The level node.
  16720. * @returns {PMREMNode}
  16721. */
  16722. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  16723. const _envNodeCache = new WeakMap();
  16724. /**
  16725. * Represents a physical model for Image-based lighting (IBL). The environment
  16726. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  16727. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  16728. *
  16729. * @augments LightingNode
  16730. */
  16731. class EnvironmentNode extends LightingNode {
  16732. static get type() {
  16733. return 'EnvironmentNode';
  16734. }
  16735. /**
  16736. * Constructs a new environment node.
  16737. *
  16738. * @param {Node} [envNode=null] - A node representing the environment.
  16739. */
  16740. constructor( envNode = null ) {
  16741. super();
  16742. /**
  16743. * A node representing the environment.
  16744. *
  16745. * @type {?Node}
  16746. * @default null
  16747. */
  16748. this.envNode = envNode;
  16749. }
  16750. setup( builder ) {
  16751. const { material } = builder;
  16752. let envNode = this.envNode;
  16753. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  16754. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  16755. let cacheEnvNode = _envNodeCache.get( value );
  16756. if ( cacheEnvNode === undefined ) {
  16757. cacheEnvNode = pmremTexture( value );
  16758. _envNodeCache.set( value, cacheEnvNode );
  16759. }
  16760. envNode = cacheEnvNode;
  16761. }
  16762. //
  16763. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  16764. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  16765. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  16766. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  16767. const isolateRadiance = cache( radiance );
  16768. const isolateIrradiance = cache( irradiance );
  16769. //
  16770. builder.context.radiance.addAssign( isolateRadiance );
  16771. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  16772. //
  16773. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  16774. if ( clearcoatRadiance ) {
  16775. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( materialEnvIntensity );
  16776. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  16777. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  16778. }
  16779. }
  16780. }
  16781. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  16782. let reflectVec = null;
  16783. return {
  16784. getUV: () => {
  16785. if ( reflectVec === null ) {
  16786. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  16787. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  16788. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  16789. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  16790. }
  16791. return reflectVec;
  16792. },
  16793. getTextureLevel: () => {
  16794. return roughnessNode;
  16795. }
  16796. };
  16797. };
  16798. const createIrradianceContext = ( normalWorldNode ) => {
  16799. return {
  16800. getUV: () => {
  16801. return normalWorldNode;
  16802. },
  16803. getTextureLevel: () => {
  16804. return float( 1.0 );
  16805. }
  16806. };
  16807. };
  16808. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  16809. /**
  16810. * Node material version of {@link MeshStandardMaterial}.
  16811. *
  16812. * @augments NodeMaterial
  16813. */
  16814. class MeshStandardNodeMaterial extends NodeMaterial {
  16815. static get type() {
  16816. return 'MeshStandardNodeMaterial';
  16817. }
  16818. /**
  16819. * Constructs a new mesh standard node material.
  16820. *
  16821. * @param {Object} [parameters] - The configuration parameter.
  16822. */
  16823. constructor( parameters ) {
  16824. super();
  16825. /**
  16826. * This flag can be used for type testing.
  16827. *
  16828. * @type {boolean}
  16829. * @readonly
  16830. * @default true
  16831. */
  16832. this.isMeshStandardNodeMaterial = true;
  16833. /**
  16834. * Set to `true` because standard materials react on lights.
  16835. *
  16836. * @type {boolean}
  16837. * @default true
  16838. */
  16839. this.lights = true;
  16840. /**
  16841. * The emissive color of standard materials is by default inferred from the `emissive`,
  16842. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  16843. * overwrite the default and define the emissive color with a node instead.
  16844. *
  16845. * If you don't want to overwrite the emissive color but modify the existing
  16846. * value instead, use {@link materialEmissive}.
  16847. *
  16848. * @type {?Node<vec3>}
  16849. * @default null
  16850. */
  16851. this.emissiveNode = null;
  16852. /**
  16853. * The metalness of standard materials is by default inferred from the `metalness`,
  16854. * and `metalnessMap` properties. This node property allows to
  16855. * overwrite the default and define the metalness with a node instead.
  16856. *
  16857. * If you don't want to overwrite the metalness but modify the existing
  16858. * value instead, use {@link materialMetalness}.
  16859. *
  16860. * @type {?Node<float>}
  16861. * @default null
  16862. */
  16863. this.metalnessNode = null;
  16864. /**
  16865. * The roughness of standard materials is by default inferred from the `roughness`,
  16866. * and `roughnessMap` properties. This node property allows to
  16867. * overwrite the default and define the roughness with a node instead.
  16868. *
  16869. * If you don't want to overwrite the roughness but modify the existing
  16870. * value instead, use {@link materialRoughness}.
  16871. *
  16872. * @type {?Node<float>}
  16873. * @default null
  16874. */
  16875. this.roughnessNode = null;
  16876. this.setDefaultValues( _defaultValues$6 );
  16877. this.setValues( parameters );
  16878. }
  16879. /**
  16880. * Overwritten since this type of material uses {@link EnvironmentNode}
  16881. * to implement the PBR (PMREM based) environment mapping. Besides, the
  16882. * method honors `Scene.environment`.
  16883. *
  16884. * @param {NodeBuilder} builder - The current node builder.
  16885. * @return {?EnvironmentNode<vec3>} The environment node.
  16886. */
  16887. setupEnvironment( builder ) {
  16888. let envNode = super.setupEnvironment( builder );
  16889. if ( envNode === null && builder.environmentNode ) {
  16890. envNode = builder.environmentNode;
  16891. }
  16892. return envNode ? new EnvironmentNode( envNode ) : null;
  16893. }
  16894. /**
  16895. * Setups the lighting model.
  16896. *
  16897. * @return {PhysicalLightingModel} The lighting model.
  16898. */
  16899. setupLightingModel( /*builder*/ ) {
  16900. return new PhysicalLightingModel();
  16901. }
  16902. /**
  16903. * Setups the specular related node variables.
  16904. */
  16905. setupSpecular() {
  16906. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  16907. specularColor.assign( specularColorNode );
  16908. specularF90.assign( 1.0 );
  16909. }
  16910. /**
  16911. * Setups the standard specific node variables.
  16912. *
  16913. * @param {NodeBuilder} builder - The current node builder.
  16914. */
  16915. setupVariants() {
  16916. // METALNESS
  16917. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  16918. metalness.assign( metalnessNode );
  16919. // ROUGHNESS
  16920. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  16921. roughnessNode = getRoughness( { roughness: roughnessNode } );
  16922. roughness.assign( roughnessNode );
  16923. // SPECULAR COLOR
  16924. this.setupSpecular();
  16925. // DIFFUSE COLOR
  16926. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  16927. }
  16928. copy( source ) {
  16929. this.emissiveNode = source.emissiveNode;
  16930. this.metalnessNode = source.metalnessNode;
  16931. this.roughnessNode = source.roughnessNode;
  16932. return super.copy( source );
  16933. }
  16934. }
  16935. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  16936. /**
  16937. * Node material version of {@link MeshPhysicalMaterial}.
  16938. *
  16939. * @augments MeshStandardNodeMaterial
  16940. */
  16941. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  16942. static get type() {
  16943. return 'MeshPhysicalNodeMaterial';
  16944. }
  16945. /**
  16946. * Constructs a new mesh physical node material.
  16947. *
  16948. * @param {Object} [parameters] - The configuration parameter.
  16949. */
  16950. constructor( parameters ) {
  16951. super();
  16952. /**
  16953. * This flag can be used for type testing.
  16954. *
  16955. * @type {boolean}
  16956. * @readonly
  16957. * @default true
  16958. */
  16959. this.isMeshPhysicalNodeMaterial = true;
  16960. /**
  16961. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  16962. * and `clearcoatMap` properties. This node property allows to overwrite the default
  16963. * and define the clearcoat with a node instead.
  16964. *
  16965. * If you don't want to overwrite the clearcoat but modify the existing
  16966. * value instead, use {@link materialClearcoat}.
  16967. *
  16968. * @type {?Node<float>}
  16969. * @default null
  16970. */
  16971. this.clearcoatNode = null;
  16972. /**
  16973. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  16974. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  16975. * and define the clearcoat roughness with a node instead.
  16976. *
  16977. * If you don't want to overwrite the clearcoat roughness but modify the existing
  16978. * value instead, use {@link materialClearcoatRoughness}.
  16979. *
  16980. * @type {?Node<float>}
  16981. * @default null
  16982. */
  16983. this.clearcoatRoughnessNode = null;
  16984. /**
  16985. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  16986. * property. This node property allows to overwrite the default
  16987. * and define the clearcoat normal with a node instead.
  16988. *
  16989. * If you don't want to overwrite the clearcoat normal but modify the existing
  16990. * value instead, use {@link materialClearcoatNormal}.
  16991. *
  16992. * @type {?Node<vec3>}
  16993. * @default null
  16994. */
  16995. this.clearcoatNormalNode = null;
  16996. /**
  16997. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  16998. * and `sheenColorMap` properties. This node property allows to overwrite the default
  16999. * and define the sheen with a node instead.
  17000. *
  17001. * If you don't want to overwrite the sheen but modify the existing
  17002. * value instead, use {@link materialSheen}.
  17003. *
  17004. * @type {?Node<vec3>}
  17005. * @default null
  17006. */
  17007. this.sheenNode = null;
  17008. /**
  17009. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  17010. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  17011. * and define the sheen roughness with a node instead.
  17012. *
  17013. * If you don't want to overwrite the sheen roughness but modify the existing
  17014. * value instead, use {@link materialSheenRoughness}.
  17015. *
  17016. * @type {?Node<float>}
  17017. * @default null
  17018. */
  17019. this.sheenRoughnessNode = null;
  17020. /**
  17021. * The iridescence of physical materials is by default inferred from the `iridescence`
  17022. * property. This node property allows to overwrite the default
  17023. * and define the iridescence with a node instead.
  17024. *
  17025. * If you don't want to overwrite the iridescence but modify the existing
  17026. * value instead, use {@link materialIridescence}.
  17027. *
  17028. * @type {?Node<float>}
  17029. * @default null
  17030. */
  17031. this.iridescenceNode = null;
  17032. /**
  17033. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  17034. * property. This node property allows to overwrite the default
  17035. * and define the iridescence IOR with a node instead.
  17036. *
  17037. * If you don't want to overwrite the iridescence IOR but modify the existing
  17038. * value instead, use {@link materialIridescenceIOR}.
  17039. *
  17040. * @type {?Node<float>}
  17041. * @default null
  17042. */
  17043. this.iridescenceIORNode = null;
  17044. /**
  17045. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  17046. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  17047. * and define the iridescence thickness with a node instead.
  17048. *
  17049. * If you don't want to overwrite the iridescence thickness but modify the existing
  17050. * value instead, use {@link materialIridescenceThickness}.
  17051. *
  17052. * @type {?Node<float>}
  17053. * @default null
  17054. */
  17055. this.iridescenceThicknessNode = null;
  17056. /**
  17057. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  17058. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  17059. * and define the specular intensity with a node instead.
  17060. *
  17061. * If you don't want to overwrite the specular intensity but modify the existing
  17062. * value instead, use {@link materialSpecularIntensity}.
  17063. *
  17064. * @type {?Node<float>}
  17065. * @default null
  17066. */
  17067. this.specularIntensityNode = null;
  17068. /**
  17069. * The specular color of physical materials is by default inferred from the `specularColor`
  17070. * and `specularColorMap` properties. This node property allows to overwrite the default
  17071. * and define the specular color with a node instead.
  17072. *
  17073. * If you don't want to overwrite the specular color but modify the existing
  17074. * value instead, use {@link materialSpecularColor}.
  17075. *
  17076. * @type {?Node<vec3>}
  17077. * @default null
  17078. */
  17079. this.specularColorNode = null;
  17080. /**
  17081. * The ior of physical materials is by default inferred from the `ior`
  17082. * property. This node property allows to overwrite the default
  17083. * and define the ior with a node instead.
  17084. *
  17085. * If you don't want to overwrite the ior but modify the existing
  17086. * value instead, use {@link materialIOR}.
  17087. *
  17088. * @type {?Node<float>}
  17089. * @default null
  17090. */
  17091. this.iorNode = null;
  17092. /**
  17093. * The transmission of physical materials is by default inferred from the `transmission` and
  17094. * `transmissionMap` properties. This node property allows to overwrite the default
  17095. * and define the transmission with a node instead.
  17096. *
  17097. * If you don't want to overwrite the transmission but modify the existing
  17098. * value instead, use {@link materialTransmission}.
  17099. *
  17100. * @type {?Node<float>}
  17101. * @default null
  17102. */
  17103. this.transmissionNode = null;
  17104. /**
  17105. * The thickness of physical materials is by default inferred from the `thickness` and
  17106. * `thicknessMap` properties. This node property allows to overwrite the default
  17107. * and define the thickness with a node instead.
  17108. *
  17109. * If you don't want to overwrite the thickness but modify the existing
  17110. * value instead, use {@link materialThickness}.
  17111. *
  17112. * @type {?Node<float>}
  17113. * @default null
  17114. */
  17115. this.thicknessNode = null;
  17116. /**
  17117. * The attenuation distance of physical materials is by default inferred from the
  17118. * `attenuationDistance` property. This node property allows to overwrite the default
  17119. * and define the attenuation distance with a node instead.
  17120. *
  17121. * If you don't want to overwrite the attenuation distance but modify the existing
  17122. * value instead, use {@link materialAttenuationDistance}.
  17123. *
  17124. * @type {?Node<float>}
  17125. * @default null
  17126. */
  17127. this.attenuationDistanceNode = null;
  17128. /**
  17129. * The attenuation color of physical materials is by default inferred from the
  17130. * `attenuationColor` property. This node property allows to overwrite the default
  17131. * and define the attenuation color with a node instead.
  17132. *
  17133. * If you don't want to overwrite the attenuation color but modify the existing
  17134. * value instead, use {@link materialAttenuationColor}.
  17135. *
  17136. * @type {?Node<vec3>}
  17137. * @default null
  17138. */
  17139. this.attenuationColorNode = null;
  17140. /**
  17141. * The dispersion of physical materials is by default inferred from the
  17142. * `dispersion` property. This node property allows to overwrite the default
  17143. * and define the dispersion with a node instead.
  17144. *
  17145. * If you don't want to overwrite the dispersion but modify the existing
  17146. * value instead, use {@link materialDispersion}.
  17147. *
  17148. * @type {?Node<float>}
  17149. * @default null
  17150. */
  17151. this.dispersionNode = null;
  17152. /**
  17153. * The anisotropy of physical materials is by default inferred from the
  17154. * `anisotropy` property. This node property allows to overwrite the default
  17155. * and define the anisotropy with a node instead.
  17156. *
  17157. * If you don't want to overwrite the anisotropy but modify the existing
  17158. * value instead, use {@link materialAnisotropy}.
  17159. *
  17160. * @type {?Node<float>}
  17161. * @default null
  17162. */
  17163. this.anisotropyNode = null;
  17164. this.setDefaultValues( _defaultValues$5 );
  17165. this.setValues( parameters );
  17166. }
  17167. /**
  17168. * Whether the lighting model should use clearcoat or not.
  17169. *
  17170. * @type {boolean}
  17171. * @default true
  17172. */
  17173. get useClearcoat() {
  17174. return this.clearcoat > 0 || this.clearcoatNode !== null;
  17175. }
  17176. /**
  17177. * Whether the lighting model should use iridescence or not.
  17178. *
  17179. * @type {boolean}
  17180. * @default true
  17181. */
  17182. get useIridescence() {
  17183. return this.iridescence > 0 || this.iridescenceNode !== null;
  17184. }
  17185. /**
  17186. * Whether the lighting model should use sheen or not.
  17187. *
  17188. * @type {boolean}
  17189. * @default true
  17190. */
  17191. get useSheen() {
  17192. return this.sheen > 0 || this.sheenNode !== null;
  17193. }
  17194. /**
  17195. * Whether the lighting model should use anisotropy or not.
  17196. *
  17197. * @type {boolean}
  17198. * @default true
  17199. */
  17200. get useAnisotropy() {
  17201. return this.anisotropy > 0 || this.anisotropyNode !== null;
  17202. }
  17203. /**
  17204. * Whether the lighting model should use transmission or not.
  17205. *
  17206. * @type {boolean}
  17207. * @default true
  17208. */
  17209. get useTransmission() {
  17210. return this.transmission > 0 || this.transmissionNode !== null;
  17211. }
  17212. /**
  17213. * Whether the lighting model should use dispersion or not.
  17214. *
  17215. * @type {boolean}
  17216. * @default true
  17217. */
  17218. get useDispersion() {
  17219. return this.dispersion > 0 || this.dispersionNode !== null;
  17220. }
  17221. /**
  17222. * Setups the specular related node variables.
  17223. */
  17224. setupSpecular() {
  17225. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  17226. ior.assign( iorNode );
  17227. specularColor.assign( mix( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ), diffuseColor.rgb, metalness ) );
  17228. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  17229. }
  17230. /**
  17231. * Setups the lighting model.
  17232. *
  17233. * @return {PhysicalLightingModel} The lighting model.
  17234. */
  17235. setupLightingModel( /*builder*/ ) {
  17236. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  17237. }
  17238. /**
  17239. * Setups the physical specific node variables.
  17240. *
  17241. * @param {NodeBuilder} builder - The current node builder.
  17242. */
  17243. setupVariants( builder ) {
  17244. super.setupVariants( builder );
  17245. // CLEARCOAT
  17246. if ( this.useClearcoat ) {
  17247. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  17248. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  17249. clearcoat.assign( clearcoatNode );
  17250. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  17251. }
  17252. // SHEEN
  17253. if ( this.useSheen ) {
  17254. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  17255. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  17256. sheen.assign( sheenNode );
  17257. sheenRoughness.assign( sheenRoughnessNode );
  17258. }
  17259. // IRIDESCENCE
  17260. if ( this.useIridescence ) {
  17261. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  17262. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  17263. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  17264. iridescence.assign( iridescenceNode );
  17265. iridescenceIOR.assign( iridescenceIORNode );
  17266. iridescenceThickness.assign( iridescenceThicknessNode );
  17267. }
  17268. // ANISOTROPY
  17269. if ( this.useAnisotropy ) {
  17270. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  17271. anisotropy.assign( anisotropyV.length() );
  17272. If( anisotropy.equal( 0.0 ), () => {
  17273. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  17274. } ).Else( () => {
  17275. anisotropyV.divAssign( vec2( anisotropy ) );
  17276. anisotropy.assign( anisotropy.saturate() );
  17277. } );
  17278. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  17279. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  17280. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  17281. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  17282. }
  17283. // TRANSMISSION
  17284. if ( this.useTransmission ) {
  17285. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  17286. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  17287. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  17288. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  17289. transmission.assign( transmissionNode );
  17290. thickness.assign( thicknessNode );
  17291. attenuationDistance.assign( attenuationDistanceNode );
  17292. attenuationColor.assign( attenuationColorNode );
  17293. if ( this.useDispersion ) {
  17294. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  17295. dispersion.assign( dispersionNode );
  17296. }
  17297. }
  17298. }
  17299. /**
  17300. * Setups the clearcoat normal node.
  17301. *
  17302. * @return {Node<vec3>} The clearcoat normal.
  17303. */
  17304. setupClearcoatNormal() {
  17305. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  17306. }
  17307. setup( builder ) {
  17308. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  17309. super.setup( builder );
  17310. }
  17311. copy( source ) {
  17312. this.clearcoatNode = source.clearcoatNode;
  17313. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  17314. this.clearcoatNormalNode = source.clearcoatNormalNode;
  17315. this.sheenNode = source.sheenNode;
  17316. this.sheenRoughnessNode = source.sheenRoughnessNode;
  17317. this.iridescenceNode = source.iridescenceNode;
  17318. this.iridescenceIORNode = source.iridescenceIORNode;
  17319. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  17320. this.specularIntensityNode = source.specularIntensityNode;
  17321. this.specularColorNode = source.specularColorNode;
  17322. this.transmissionNode = source.transmissionNode;
  17323. this.thicknessNode = source.thicknessNode;
  17324. this.attenuationDistanceNode = source.attenuationDistanceNode;
  17325. this.attenuationColorNode = source.attenuationColorNode;
  17326. this.dispersionNode = source.dispersionNode;
  17327. this.anisotropyNode = source.anisotropyNode;
  17328. return super.copy( source );
  17329. }
  17330. }
  17331. /**
  17332. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  17333. *
  17334. * @augments PhysicalLightingModel
  17335. */
  17336. class SSSLightingModel extends PhysicalLightingModel {
  17337. /**
  17338. * Constructs a new physical lighting model.
  17339. *
  17340. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17341. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17342. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17343. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17344. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17345. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17346. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  17347. */
  17348. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  17349. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  17350. /**
  17351. * Whether the lighting model should use SSS or not.
  17352. *
  17353. * @type {boolean}
  17354. * @default false
  17355. */
  17356. this.useSSS = sss;
  17357. }
  17358. /**
  17359. * Extends the default implementation with a SSS term.
  17360. *
  17361. * Reference: [Approximating Translucency for a Fast, Cheap and Convincing Subsurface Scattering Look]{@link https://colinbarrebrisebois.com/2011/03/07/gdc-2011-approximating-translucency-for-a-fast-cheap-and-convincing-subsurface-scattering-look/}
  17362. *
  17363. * @param {Object} input - The input data.
  17364. * @param {NodeBuilder} builder - The current node builder.
  17365. */
  17366. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  17367. if ( this.useSSS === true ) {
  17368. const material = builder.material;
  17369. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  17370. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  17371. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  17372. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  17373. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  17374. }
  17375. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  17376. }
  17377. }
  17378. /**
  17379. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  17380. * that implements a Subsurface scattering (SSS) term.
  17381. *
  17382. * @augments MeshPhysicalNodeMaterial
  17383. */
  17384. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  17385. static get type() {
  17386. return 'MeshSSSNodeMaterial';
  17387. }
  17388. /**
  17389. * Constructs a new mesh SSS node material.
  17390. *
  17391. * @param {Object} [parameters] - The configuration parameter.
  17392. */
  17393. constructor( parameters ) {
  17394. super( parameters );
  17395. /**
  17396. * Represents the thickness color.
  17397. *
  17398. * @type {?Node<vec3>}
  17399. * @default null
  17400. */
  17401. this.thicknessColorNode = null;
  17402. /**
  17403. * Represents the distortion factor.
  17404. *
  17405. * @type {?Node<float>}
  17406. */
  17407. this.thicknessDistortionNode = float( 0.1 );
  17408. /**
  17409. * Represents the thickness ambient factor.
  17410. *
  17411. * @type {?Node<float>}
  17412. */
  17413. this.thicknessAmbientNode = float( 0.0 );
  17414. /**
  17415. * Represents the thickness attenuation.
  17416. *
  17417. * @type {?Node<float>}
  17418. */
  17419. this.thicknessAttenuationNode = float( .1 );
  17420. /**
  17421. * Represents the thickness power.
  17422. *
  17423. * @type {?Node<float>}
  17424. */
  17425. this.thicknessPowerNode = float( 2.0 );
  17426. /**
  17427. * Represents the thickness scale.
  17428. *
  17429. * @type {?Node<float>}
  17430. */
  17431. this.thicknessScaleNode = float( 10.0 );
  17432. }
  17433. /**
  17434. * Whether the lighting model should use SSS or not.
  17435. *
  17436. * @type {boolean}
  17437. * @default true
  17438. */
  17439. get useSSS() {
  17440. return this.thicknessColorNode !== null;
  17441. }
  17442. /**
  17443. * Setups the lighting model.
  17444. *
  17445. * @return {SSSLightingModel} The lighting model.
  17446. */
  17447. setupLightingModel( /*builder*/ ) {
  17448. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  17449. }
  17450. copy( source ) {
  17451. this.thicknessColorNode = source.thicknessColorNode;
  17452. this.thicknessDistortionNode = source.thicknessDistortionNode;
  17453. this.thicknessAmbientNode = source.thicknessAmbientNode;
  17454. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  17455. this.thicknessPowerNode = source.thicknessPowerNode;
  17456. this.thicknessScaleNode = source.thicknessScaleNode;
  17457. return super.copy( source );
  17458. }
  17459. }
  17460. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  17461. // dotNL will be from -1.0 to 1.0
  17462. const dotNL = normal.dot( lightDirection );
  17463. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  17464. if ( builder.material.gradientMap ) {
  17465. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  17466. return vec3( gradientMap.r );
  17467. } else {
  17468. const fw = coord.fwidth().mul( 0.5 );
  17469. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  17470. }
  17471. } );
  17472. /**
  17473. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  17474. *
  17475. * @augments LightingModel
  17476. */
  17477. class ToonLightingModel extends LightingModel {
  17478. /**
  17479. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  17480. * reduced to a small number of discrete shades to create a comic-like, flat look.
  17481. *
  17482. * @param {Object} lightData - The light data.
  17483. * @param {NodeBuilder} builder - The current node builder.
  17484. */
  17485. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  17486. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  17487. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  17488. }
  17489. /**
  17490. * Implements the indirect lighting.
  17491. *
  17492. * @param {NodeBuilder} builder - The current node builder.
  17493. */
  17494. indirect( builder ) {
  17495. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  17496. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  17497. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17498. }
  17499. }
  17500. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  17501. /**
  17502. * Node material version of {@link MeshToonMaterial}.
  17503. *
  17504. * @augments NodeMaterial
  17505. */
  17506. class MeshToonNodeMaterial extends NodeMaterial {
  17507. static get type() {
  17508. return 'MeshToonNodeMaterial';
  17509. }
  17510. /**
  17511. * Constructs a new mesh toon node material.
  17512. *
  17513. * @param {Object} [parameters] - The configuration parameter.
  17514. */
  17515. constructor( parameters ) {
  17516. super();
  17517. /**
  17518. * This flag can be used for type testing.
  17519. *
  17520. * @type {boolean}
  17521. * @readonly
  17522. * @default true
  17523. */
  17524. this.isMeshToonNodeMaterial = true;
  17525. /**
  17526. * Set to `true` because toon materials react on lights.
  17527. *
  17528. * @type {boolean}
  17529. * @default true
  17530. */
  17531. this.lights = true;
  17532. this.setDefaultValues( _defaultValues$4 );
  17533. this.setValues( parameters );
  17534. }
  17535. /**
  17536. * Setups the lighting model.
  17537. *
  17538. * @return {ToonLightingModel} The lighting model.
  17539. */
  17540. setupLightingModel( /*builder*/ ) {
  17541. return new ToonLightingModel();
  17542. }
  17543. }
  17544. /**
  17545. * Can be used to compute texture coordinates for projecting a
  17546. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  17547. *
  17548. * @augments TempNode
  17549. */
  17550. class MatcapUVNode extends TempNode {
  17551. static get type() {
  17552. return 'MatcapUVNode';
  17553. }
  17554. /**
  17555. * Constructs a new matcap uv node.
  17556. */
  17557. constructor() {
  17558. super( 'vec2' );
  17559. }
  17560. setup() {
  17561. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  17562. const y = positionViewDirection.cross( x );
  17563. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  17564. }
  17565. }
  17566. /**
  17567. * TSL function for creating a matcap uv node.
  17568. *
  17569. * @tsl
  17570. * @function
  17571. * @returns {MatcapUVNode}
  17572. */
  17573. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  17574. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  17575. /**
  17576. * Node material version of {@link MeshMatcapMaterial}.
  17577. *
  17578. * @augments NodeMaterial
  17579. */
  17580. class MeshMatcapNodeMaterial extends NodeMaterial {
  17581. static get type() {
  17582. return 'MeshMatcapNodeMaterial';
  17583. }
  17584. /**
  17585. * Constructs a new mesh normal node material.
  17586. *
  17587. * @param {Object} [parameters] - The configuration parameter.
  17588. */
  17589. constructor( parameters ) {
  17590. super();
  17591. /**
  17592. * This flag can be used for type testing.
  17593. *
  17594. * @type {boolean}
  17595. * @readonly
  17596. * @default true
  17597. */
  17598. this.isMeshMatcapNodeMaterial = true;
  17599. this.setDefaultValues( _defaultValues$3 );
  17600. this.setValues( parameters );
  17601. }
  17602. /**
  17603. * Setups the matcap specific node variables.
  17604. *
  17605. * @param {NodeBuilder} builder - The current node builder.
  17606. */
  17607. setupVariants( builder ) {
  17608. const uv = matcapUV;
  17609. let matcapColor;
  17610. if ( builder.material.matcap ) {
  17611. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  17612. } else {
  17613. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  17614. }
  17615. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  17616. }
  17617. }
  17618. /**
  17619. * Applies a rotation to the given position node.
  17620. *
  17621. * @augments TempNode
  17622. */
  17623. class RotateNode extends TempNode {
  17624. static get type() {
  17625. return 'RotateNode';
  17626. }
  17627. /**
  17628. * Constructs a new rotate node.
  17629. *
  17630. * @param {Node} positionNode - The position node.
  17631. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  17632. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17633. */
  17634. constructor( positionNode, rotationNode ) {
  17635. super();
  17636. /**
  17637. * The position node.
  17638. *
  17639. * @type {Node}
  17640. */
  17641. this.positionNode = positionNode;
  17642. /**
  17643. * Represents the rotation that is applied to the position node.
  17644. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17645. *
  17646. * @type {Node}
  17647. */
  17648. this.rotationNode = rotationNode;
  17649. }
  17650. /**
  17651. * The type of the {@link RotateNode#positionNode} defines the node's type.
  17652. *
  17653. * @param {NodeBuilder} builder - The current node builder.
  17654. * @return {string} The node's type.
  17655. */
  17656. getNodeType( builder ) {
  17657. return this.positionNode.getNodeType( builder );
  17658. }
  17659. setup( builder ) {
  17660. const { rotationNode, positionNode } = this;
  17661. const nodeType = this.getNodeType( builder );
  17662. if ( nodeType === 'vec2' ) {
  17663. const cosAngle = rotationNode.cos();
  17664. const sinAngle = rotationNode.sin();
  17665. const rotationMatrix = mat2(
  17666. cosAngle, sinAngle,
  17667. sinAngle.negate(), cosAngle
  17668. );
  17669. return rotationMatrix.mul( positionNode );
  17670. } else {
  17671. const rotation = rotationNode;
  17672. const rotationXMatrix = mat4( vec4( 1.0, 0.0, 0.0, 0.0 ), vec4( 0.0, cos( rotation.x ), sin( rotation.x ).negate(), 0.0 ), vec4( 0.0, sin( rotation.x ), cos( rotation.x ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  17673. const rotationYMatrix = mat4( vec4( cos( rotation.y ), 0.0, sin( rotation.y ), 0.0 ), vec4( 0.0, 1.0, 0.0, 0.0 ), vec4( sin( rotation.y ).negate(), 0.0, cos( rotation.y ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  17674. const rotationZMatrix = mat4( vec4( cos( rotation.z ), sin( rotation.z ).negate(), 0.0, 0.0 ), vec4( sin( rotation.z ), cos( rotation.z ), 0.0, 0.0 ), vec4( 0.0, 0.0, 1.0, 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  17675. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  17676. }
  17677. }
  17678. }
  17679. /**
  17680. * TSL function for creating a rotate node.
  17681. *
  17682. * @tsl
  17683. * @function
  17684. * @param {Node} positionNode - The position node.
  17685. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  17686. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17687. * @returns {RotateNode}
  17688. */
  17689. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  17690. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  17691. /**
  17692. * Node material version of {@link SpriteMaterial}.
  17693. *
  17694. * @augments NodeMaterial
  17695. */
  17696. class SpriteNodeMaterial extends NodeMaterial {
  17697. static get type() {
  17698. return 'SpriteNodeMaterial';
  17699. }
  17700. /**
  17701. * Constructs a new sprite node material.
  17702. *
  17703. * @param {Object} [parameters] - The configuration parameter.
  17704. */
  17705. constructor( parameters ) {
  17706. super();
  17707. /**
  17708. * This flag can be used for type testing.
  17709. *
  17710. * @type {boolean}
  17711. * @readonly
  17712. * @default true
  17713. */
  17714. this.isSpriteNodeMaterial = true;
  17715. this._useSizeAttenuation = true;
  17716. /**
  17717. * This property makes it possible to define the position of the sprite with a
  17718. * node. That can be useful when the material is used with instanced rendering
  17719. * and node data are defined with an instanced attribute node:
  17720. * ```js
  17721. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  17722. * material.positionNode = instancedBufferAttribute( positionAttribute );
  17723. * ```
  17724. * Another possibility is to compute the instanced data with a compute shader:
  17725. * ```js
  17726. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  17727. * particleMaterial.positionNode = positionBuffer.toAttribute();
  17728. * ```
  17729. *
  17730. * @type {?Node<vec2>}
  17731. * @default null
  17732. */
  17733. this.positionNode = null;
  17734. /**
  17735. * The rotation of sprite materials is by default inferred from the `rotation`,
  17736. * property. This node property allows to overwrite the default and define
  17737. * the rotation with a node instead.
  17738. *
  17739. * If you don't want to overwrite the rotation but modify the existing
  17740. * value instead, use {@link materialRotation}.
  17741. *
  17742. * @type {?Node<float>}
  17743. * @default null
  17744. */
  17745. this.rotationNode = null;
  17746. /**
  17747. * This node property provides an additional way to scale sprites next to
  17748. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  17749. * is multiplied with the scale value of this node in the vertex shader.
  17750. *
  17751. * @type {?Node<vec2>}
  17752. * @default null
  17753. */
  17754. this.scaleNode = null;
  17755. /**
  17756. * In Sprites, the transparent property is enabled by default.
  17757. *
  17758. * @type {boolean}
  17759. * @default true
  17760. */
  17761. this.transparent = true;
  17762. this.setDefaultValues( _defaultValues$2 );
  17763. this.setValues( parameters );
  17764. }
  17765. /**
  17766. * Setups the position node in view space. This method implements
  17767. * the sprite specific vertex shader.
  17768. *
  17769. * @param {NodeBuilder} builder - The current node builder.
  17770. * @return {Node<vec3>} The position in view space.
  17771. */
  17772. setupPositionView( builder ) {
  17773. const { object, camera } = builder;
  17774. const sizeAttenuation = this.sizeAttenuation;
  17775. const { positionNode, rotationNode, scaleNode } = this;
  17776. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  17777. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  17778. if ( scaleNode !== null ) {
  17779. scale = scale.mul( vec2( scaleNode ) );
  17780. }
  17781. if ( sizeAttenuation === false ) {
  17782. if ( camera.isPerspectiveCamera ) {
  17783. scale = scale.mul( mvPosition.z.negate() );
  17784. } else {
  17785. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  17786. scale = scale.mul( orthoScale.mul( 2 ) );
  17787. }
  17788. }
  17789. let alignedPosition = positionGeometry.xy;
  17790. if ( object.center && object.center.isVector2 === true ) {
  17791. const center = reference$1( 'center', 'vec2', object );
  17792. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  17793. }
  17794. alignedPosition = alignedPosition.mul( scale );
  17795. const rotation = float( rotationNode || materialRotation );
  17796. const rotatedPosition = rotate( alignedPosition, rotation );
  17797. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  17798. }
  17799. copy( source ) {
  17800. this.positionNode = source.positionNode;
  17801. this.rotationNode = source.rotationNode;
  17802. this.scaleNode = source.scaleNode;
  17803. return super.copy( source );
  17804. }
  17805. /**
  17806. * Whether to use size attenuation or not.
  17807. *
  17808. * @type {boolean}
  17809. * @default true
  17810. */
  17811. get sizeAttenuation() {
  17812. return this._useSizeAttenuation;
  17813. }
  17814. set sizeAttenuation( value ) {
  17815. if ( this._useSizeAttenuation !== value ) {
  17816. this._useSizeAttenuation = value;
  17817. this.needsUpdate = true;
  17818. }
  17819. }
  17820. }
  17821. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  17822. /**
  17823. * Node material version of {@link PointsMaterial}.
  17824. *
  17825. * @augments SpriteNodeMaterial
  17826. */
  17827. class PointsNodeMaterial extends SpriteNodeMaterial {
  17828. static get type() {
  17829. return 'PointsNodeMaterial';
  17830. }
  17831. /**
  17832. * Constructs a new points node material.
  17833. *
  17834. * @param {Object} [parameters] - The configuration parameter.
  17835. */
  17836. constructor( parameters ) {
  17837. super();
  17838. /**
  17839. * This node property provides an additional way to set the point size.
  17840. *
  17841. * @type {?Node<vec2>}
  17842. * @default null
  17843. */
  17844. this.sizeNode = null;
  17845. /**
  17846. * This flag can be used for type testing.
  17847. *
  17848. * @type {boolean}
  17849. * @readonly
  17850. * @default true
  17851. */
  17852. this.isPointsNodeMaterial = true;
  17853. this.setDefaultValues( _defaultValues$1 );
  17854. this.setValues( parameters );
  17855. }
  17856. setupPositionView() {
  17857. const { positionNode } = this;
  17858. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  17859. }
  17860. setupVertex( builder ) {
  17861. const mvp = super.setupVertex( builder );
  17862. // skip further processing if the material is not a node material
  17863. if ( builder.material.isNodeMaterial !== true ) {
  17864. return mvp;
  17865. }
  17866. // ndc space
  17867. const { rotationNode, scaleNode, sizeNode } = this;
  17868. const alignedPosition = positionGeometry.xy.toVar();
  17869. const aspect = viewport.z.div( viewport.w );
  17870. // rotation
  17871. if ( rotationNode && rotationNode.isNode ) {
  17872. const rotation = float( rotationNode );
  17873. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  17874. }
  17875. // point size
  17876. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  17877. if ( this.sizeAttenuation === true ) {
  17878. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  17879. }
  17880. // scale
  17881. if ( scaleNode && scaleNode.isNode ) {
  17882. pointSize = pointSize.mul( vec2( scaleNode ) );
  17883. }
  17884. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  17885. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  17886. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  17887. // back to clip space
  17888. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  17889. //clipPos.xy += offset;
  17890. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  17891. return mvp;
  17892. }
  17893. /**
  17894. * Whether alpha to coverage should be used or not.
  17895. *
  17896. * @type {boolean}
  17897. * @default true
  17898. */
  17899. get alphaToCoverage() {
  17900. return this._useAlphaToCoverage;
  17901. }
  17902. set alphaToCoverage( value ) {
  17903. if ( this._useAlphaToCoverage !== value ) {
  17904. this._useAlphaToCoverage = value;
  17905. this.needsUpdate = true;
  17906. }
  17907. }
  17908. }
  17909. /**
  17910. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  17911. *
  17912. * @augments LightingModel
  17913. */
  17914. class ShadowMaskModel extends LightingModel {
  17915. /**
  17916. * Constructs a new shadow mask model.
  17917. */
  17918. constructor() {
  17919. super();
  17920. /**
  17921. * The shadow mask node.
  17922. *
  17923. * @type {Node}
  17924. */
  17925. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  17926. }
  17927. /**
  17928. * Only used to save the shadow mask.
  17929. *
  17930. * @param {Object} input - The input data.
  17931. */
  17932. direct( { lightNode } ) {
  17933. if ( lightNode.shadowNode !== null ) {
  17934. this.shadowNode.mulAssign( lightNode.shadowNode );
  17935. }
  17936. }
  17937. /**
  17938. * Uses the shadow mask to produce the final color.
  17939. *
  17940. * @param {NodeBuilder} builder - The current node builder.
  17941. */
  17942. finish( { context } ) {
  17943. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  17944. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  17945. }
  17946. }
  17947. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  17948. /**
  17949. * Node material version of {@link ShadowMaterial}.
  17950. *
  17951. * @augments NodeMaterial
  17952. */
  17953. class ShadowNodeMaterial extends NodeMaterial {
  17954. static get type() {
  17955. return 'ShadowNodeMaterial';
  17956. }
  17957. /**
  17958. * Constructs a new shadow node material.
  17959. *
  17960. * @param {Object} [parameters] - The configuration parameter.
  17961. */
  17962. constructor( parameters ) {
  17963. super();
  17964. /**
  17965. * This flag can be used for type testing.
  17966. *
  17967. * @type {boolean}
  17968. * @readonly
  17969. * @default true
  17970. */
  17971. this.isShadowNodeMaterial = true;
  17972. /**
  17973. * Set to `true` because so it's possible to implement
  17974. * the shadow mask effect.
  17975. *
  17976. * @type {boolean}
  17977. * @default true
  17978. */
  17979. this.lights = true;
  17980. /**
  17981. * Overwritten since shadow materials are transparent
  17982. * by default.
  17983. *
  17984. * @type {boolean}
  17985. * @default true
  17986. */
  17987. this.transparent = true;
  17988. this.setDefaultValues( _defaultValues );
  17989. this.setValues( parameters );
  17990. }
  17991. /**
  17992. * Setups the lighting model.
  17993. *
  17994. * @return {ShadowMaskModel} The lighting model.
  17995. */
  17996. setupLightingModel( /*builder*/ ) {
  17997. return new ShadowMaskModel();
  17998. }
  17999. }
  18000. const scatteringDensity = property( 'vec3' );
  18001. const linearDepthRay = property( 'vec3' );
  18002. const outgoingRayLight = property( 'vec3' );
  18003. /**
  18004. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  18005. * This model calculates the scattering and transmittance of light through a volumetric medium.
  18006. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  18007. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  18008. *
  18009. * @augments LightingModel
  18010. */
  18011. class VolumetricLightingModel extends LightingModel {
  18012. constructor() {
  18013. super();
  18014. }
  18015. start( builder ) {
  18016. const { material, context } = builder;
  18017. const startPos = property( 'vec3' );
  18018. const endPos = property( 'vec3' );
  18019. // This approach dynamically changes the direction of the ray,
  18020. // prioritizing the ray from the camera to the object if it is inside the mesh, and from the object to the camera if it is far away.
  18021. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  18022. startPos.assign( cameraPosition );
  18023. endPos.assign( positionWorld );
  18024. } ).Else( () => {
  18025. startPos.assign( positionWorld );
  18026. endPos.assign( cameraPosition );
  18027. } );
  18028. //
  18029. const viewVector = endPos.sub( startPos );
  18030. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  18031. const stepSize = viewVector.length().div( steps ).toVar();
  18032. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  18033. const distTravelled = float( 0.0 ).toVar();
  18034. const transmittance = vec3( 1 ).toVar();
  18035. if ( material.offsetNode ) {
  18036. // reduce banding
  18037. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  18038. }
  18039. Loop( steps, () => {
  18040. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  18041. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  18042. if ( material.depthNode !== null ) {
  18043. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  18044. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  18045. }
  18046. context.positionWorld = positionRay;
  18047. context.shadowPositionWorld = positionRay;
  18048. context.positionView = positionViewRay;
  18049. scatteringDensity.assign( 0 );
  18050. let scatteringNode;
  18051. if ( material.scatteringNode ) {
  18052. scatteringNode = material.scatteringNode( {
  18053. positionRay
  18054. } );
  18055. }
  18056. super.start( builder );
  18057. if ( scatteringNode ) {
  18058. scatteringDensity.mulAssign( scatteringNode );
  18059. }
  18060. // beer's law
  18061. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  18062. transmittance.mulAssign( falloff );
  18063. // move along the ray
  18064. distTravelled.addAssign( stepSize );
  18065. } );
  18066. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  18067. }
  18068. scatteringLight( lightColor, builder ) {
  18069. const sceneDepthNode = builder.context.sceneDepthNode;
  18070. if ( sceneDepthNode ) {
  18071. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  18072. scatteringDensity.addAssign( lightColor );
  18073. } );
  18074. } else {
  18075. scatteringDensity.addAssign( lightColor );
  18076. }
  18077. }
  18078. direct( { lightNode, lightColor }, builder ) {
  18079. // Ignore lights with infinite distance
  18080. if ( lightNode.light.distance === undefined ) return;
  18081. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  18082. const directLight = lightColor.xyz.toVar();
  18083. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  18084. this.scatteringLight( directLight, builder );
  18085. }
  18086. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  18087. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  18088. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  18089. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  18090. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  18091. const P = builder.context.positionView;
  18092. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  18093. this.scatteringLight( directLight, builder );
  18094. }
  18095. finish( builder ) {
  18096. builder.context.outgoingLight.assign( outgoingRayLight );
  18097. }
  18098. }
  18099. /**
  18100. * Volume node material.
  18101. *
  18102. * @augments NodeMaterial
  18103. */
  18104. class VolumeNodeMaterial extends NodeMaterial {
  18105. static get type() {
  18106. return 'VolumeNodeMaterial';
  18107. }
  18108. /**
  18109. * Constructs a new volume node material.
  18110. *
  18111. * @param {Object} [parameters] - The configuration parameter.
  18112. */
  18113. constructor( parameters ) {
  18114. super();
  18115. /**
  18116. * This flag can be used for type testing.
  18117. *
  18118. * @type {boolean}
  18119. * @readonly
  18120. * @default true
  18121. */
  18122. this.isVolumeNodeMaterial = true;
  18123. /**
  18124. * Number of steps used for raymarching.
  18125. *
  18126. * @type {number}
  18127. * @default 25
  18128. */
  18129. this.steps = 25;
  18130. /**
  18131. * Offsets the distance a ray has been traveled through a volume.
  18132. * Can be used to implement dithering to reduce banding.
  18133. *
  18134. * @type {Node<float>}
  18135. * @default null
  18136. */
  18137. this.offsetNode = null;
  18138. /**
  18139. * Node used for scattering calculations.
  18140. *
  18141. * @type {Function|FunctionNode<vec4>}
  18142. * @default null
  18143. */
  18144. this.scatteringNode = null;
  18145. this.lights = true;
  18146. this.transparent = true;
  18147. this.side = BackSide;
  18148. this.depthTest = false;
  18149. this.depthWrite = false;
  18150. this.setValues( parameters );
  18151. }
  18152. setupLightingModel() {
  18153. return new VolumetricLightingModel();
  18154. }
  18155. }
  18156. /**
  18157. * This module manages the internal animation loop of the renderer.
  18158. *
  18159. * @private
  18160. */
  18161. class Animation {
  18162. /**
  18163. * Constructs a new animation loop management component.
  18164. *
  18165. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18166. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18167. */
  18168. constructor( nodes, info ) {
  18169. /**
  18170. * Renderer component for managing nodes related logic.
  18171. *
  18172. * @type {Nodes}
  18173. */
  18174. this.nodes = nodes;
  18175. /**
  18176. * Renderer component for managing metrics and monitoring data.
  18177. *
  18178. * @type {Info}
  18179. */
  18180. this.info = info;
  18181. /**
  18182. * A reference to the context from `requestAnimationFrame()` can
  18183. * be called (usually `window`).
  18184. *
  18185. * @type {?(Window|XRSession)}
  18186. */
  18187. this._context = typeof self !== 'undefined' ? self : null;
  18188. /**
  18189. * The user-defined animation loop.
  18190. *
  18191. * @type {?Function}
  18192. * @default null
  18193. */
  18194. this._animationLoop = null;
  18195. /**
  18196. * The requestId which is returned from the `requestAnimationFrame()` call.
  18197. * Can be used to cancel the stop the animation loop.
  18198. *
  18199. * @type {?number}
  18200. * @default null
  18201. */
  18202. this._requestId = null;
  18203. }
  18204. /**
  18205. * Starts the internal animation loop.
  18206. */
  18207. start() {
  18208. const update = ( time, xrFrame ) => {
  18209. this._requestId = this._context.requestAnimationFrame( update );
  18210. if ( this.info.autoReset === true ) this.info.reset();
  18211. this.nodes.nodeFrame.update();
  18212. this.info.frame = this.nodes.nodeFrame.frameId;
  18213. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  18214. };
  18215. update();
  18216. }
  18217. /**
  18218. * Stops the internal animation loop.
  18219. */
  18220. stop() {
  18221. this._context.cancelAnimationFrame( this._requestId );
  18222. this._requestId = null;
  18223. }
  18224. /**
  18225. * Returns the user-level animation loop.
  18226. *
  18227. * @return {?Function} The animation loop.
  18228. */
  18229. getAnimationLoop() {
  18230. return this._animationLoop;
  18231. }
  18232. /**
  18233. * Defines the user-level animation loop.
  18234. *
  18235. * @param {?Function} callback - The animation loop.
  18236. */
  18237. setAnimationLoop( callback ) {
  18238. this._animationLoop = callback;
  18239. }
  18240. /**
  18241. * Returns the animation context.
  18242. *
  18243. * @return {Window|XRSession} The animation context.
  18244. */
  18245. getContext() {
  18246. return this._context;
  18247. }
  18248. /**
  18249. * Defines the context in which `requestAnimationFrame()` is executed.
  18250. *
  18251. * @param {Window|XRSession} context - The context to set.
  18252. */
  18253. setContext( context ) {
  18254. this._context = context;
  18255. }
  18256. /**
  18257. * Frees all internal resources and stops the animation loop.
  18258. */
  18259. dispose() {
  18260. this.stop();
  18261. }
  18262. }
  18263. /**
  18264. * Data structure for the renderer. It allows defining values
  18265. * with chained, hierarchical keys. Keys are meant to be
  18266. * objects since the module internally works with Weak Maps
  18267. * for performance reasons.
  18268. *
  18269. * @private
  18270. */
  18271. class ChainMap {
  18272. /**
  18273. * Constructs a new Chain Map.
  18274. */
  18275. constructor() {
  18276. /**
  18277. * The root Weak Map.
  18278. *
  18279. * @type {WeakMap}
  18280. */
  18281. this.weakMap = new WeakMap();
  18282. }
  18283. /**
  18284. * Returns the value for the given array of keys.
  18285. *
  18286. * @param {Array<Object>} keys - List of keys.
  18287. * @return {any} The value. Returns `undefined` if no value was found.
  18288. */
  18289. get( keys ) {
  18290. let map = this.weakMap;
  18291. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18292. map = map.get( keys[ i ] );
  18293. if ( map === undefined ) return undefined;
  18294. }
  18295. return map.get( keys[ keys.length - 1 ] );
  18296. }
  18297. /**
  18298. * Sets the value for the given keys.
  18299. *
  18300. * @param {Array<Object>} keys - List of keys.
  18301. * @param {any} value - The value to set.
  18302. * @return {ChainMap} A reference to this Chain Map.
  18303. */
  18304. set( keys, value ) {
  18305. let map = this.weakMap;
  18306. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18307. const key = keys[ i ];
  18308. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  18309. map = map.get( key );
  18310. }
  18311. map.set( keys[ keys.length - 1 ], value );
  18312. return this;
  18313. }
  18314. /**
  18315. * Deletes a value for the given keys.
  18316. *
  18317. * @param {Array<Object>} keys - The keys.
  18318. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  18319. */
  18320. delete( keys ) {
  18321. let map = this.weakMap;
  18322. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18323. map = map.get( keys[ i ] );
  18324. if ( map === undefined ) return false;
  18325. }
  18326. return map.delete( keys[ keys.length - 1 ] );
  18327. }
  18328. }
  18329. let _id$9 = 0;
  18330. function getKeys( obj ) {
  18331. const keys = Object.keys( obj );
  18332. let proto = Object.getPrototypeOf( obj );
  18333. while ( proto ) {
  18334. const descriptors = Object.getOwnPropertyDescriptors( proto );
  18335. for ( const key in descriptors ) {
  18336. if ( descriptors[ key ] !== undefined ) {
  18337. const descriptor = descriptors[ key ];
  18338. if ( descriptor && typeof descriptor.get === 'function' ) {
  18339. keys.push( key );
  18340. }
  18341. }
  18342. }
  18343. proto = Object.getPrototypeOf( proto );
  18344. }
  18345. return keys;
  18346. }
  18347. /**
  18348. * A render object is the renderer's representation of single entity that gets drawn
  18349. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  18350. * scene since render objects also depend from the used material, the current render context
  18351. * and the current scene's lighting.
  18352. *
  18353. * In general, the basic process of the renderer is:
  18354. *
  18355. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  18356. * - Process the render lists by calling one or more render commands for each render item.
  18357. * - For each render command, request a render object and perform the draw.
  18358. *
  18359. * The module provides an interface to get data required for the draw command like the actual
  18360. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  18361. * creating render objects should only be done when necessary.
  18362. *
  18363. * @private
  18364. */
  18365. class RenderObject {
  18366. /**
  18367. * Constructs a new render object.
  18368. *
  18369. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18370. * @param {Geometries} geometries - Renderer component for managing geometries.
  18371. * @param {Renderer} renderer - The renderer.
  18372. * @param {Object3D} object - The 3D object.
  18373. * @param {Material} material - The 3D object's material.
  18374. * @param {Scene} scene - The scene the 3D object belongs to.
  18375. * @param {Camera} camera - The camera the object should be rendered with.
  18376. * @param {LightsNode} lightsNode - The lights node.
  18377. * @param {RenderContext} renderContext - The render context.
  18378. * @param {ClippingContext} clippingContext - The clipping context.
  18379. */
  18380. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  18381. this.id = _id$9 ++;
  18382. /**
  18383. * Renderer component for managing nodes related logic.
  18384. *
  18385. * @type {Nodes}
  18386. * @private
  18387. */
  18388. this._nodes = nodes;
  18389. /**
  18390. * Renderer component for managing geometries.
  18391. *
  18392. * @type {Geometries}
  18393. * @private
  18394. */
  18395. this._geometries = geometries;
  18396. /**
  18397. * The renderer.
  18398. *
  18399. * @type {Renderer}
  18400. */
  18401. this.renderer = renderer;
  18402. /**
  18403. * The 3D object.
  18404. *
  18405. * @type {Object3D}
  18406. */
  18407. this.object = object;
  18408. /**
  18409. * The 3D object's material.
  18410. *
  18411. * @type {Material}
  18412. */
  18413. this.material = material;
  18414. /**
  18415. * The scene the 3D object belongs to.
  18416. *
  18417. * @type {Scene}
  18418. */
  18419. this.scene = scene;
  18420. /**
  18421. * The camera the 3D object should be rendered with.
  18422. *
  18423. * @type {Camera}
  18424. */
  18425. this.camera = camera;
  18426. /**
  18427. * The lights node.
  18428. *
  18429. * @type {LightsNode}
  18430. */
  18431. this.lightsNode = lightsNode;
  18432. /**
  18433. * The render context.
  18434. *
  18435. * @type {RenderContext}
  18436. */
  18437. this.context = renderContext;
  18438. /**
  18439. * The 3D object's geometry.
  18440. *
  18441. * @type {BufferGeometry}
  18442. */
  18443. this.geometry = object.geometry;
  18444. /**
  18445. * The render object's version.
  18446. *
  18447. * @type {number}
  18448. */
  18449. this.version = material.version;
  18450. /**
  18451. * The draw range of the geometry.
  18452. *
  18453. * @type {?Object}
  18454. * @default null
  18455. */
  18456. this.drawRange = null;
  18457. /**
  18458. * An array holding the buffer attributes
  18459. * of the render object. This entails attribute
  18460. * definitions on geometry and node level.
  18461. *
  18462. * @type {?Array<BufferAttribute>}
  18463. * @default null
  18464. */
  18465. this.attributes = null;
  18466. /**
  18467. * A reference to a render pipeline the render
  18468. * object is processed with.
  18469. *
  18470. * @type {RenderPipeline}
  18471. * @default null
  18472. */
  18473. this.pipeline = null;
  18474. /**
  18475. * Only relevant for objects using
  18476. * multiple materials. This represents a group entry
  18477. * from the respective `BufferGeometry`.
  18478. *
  18479. * @type {?{start: number, count: number}}
  18480. * @default null
  18481. */
  18482. this.group = null;
  18483. /**
  18484. * An array holding the vertex buffers which can
  18485. * be buffer attributes but also interleaved buffers.
  18486. *
  18487. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  18488. * @default null
  18489. */
  18490. this.vertexBuffers = null;
  18491. /**
  18492. * The parameters for the draw command.
  18493. *
  18494. * @type {?Object}
  18495. * @default null
  18496. */
  18497. this.drawParams = null;
  18498. /**
  18499. * If this render object is used inside a render bundle,
  18500. * this property points to the respective bundle group.
  18501. *
  18502. * @type {?BundleGroup}
  18503. * @default null
  18504. */
  18505. this.bundle = null;
  18506. /**
  18507. * The clipping context.
  18508. *
  18509. * @type {ClippingContext}
  18510. */
  18511. this.clippingContext = clippingContext;
  18512. /**
  18513. * The clipping context's cache key.
  18514. *
  18515. * @type {string}
  18516. */
  18517. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  18518. /**
  18519. * The initial node cache key.
  18520. *
  18521. * @type {number}
  18522. */
  18523. this.initialNodesCacheKey = this.getDynamicCacheKey();
  18524. /**
  18525. * The initial cache key.
  18526. *
  18527. * @type {number}
  18528. */
  18529. this.initialCacheKey = this.getCacheKey();
  18530. /**
  18531. * The node builder state.
  18532. *
  18533. * @type {?NodeBuilderState}
  18534. * @private
  18535. * @default null
  18536. */
  18537. this._nodeBuilderState = null;
  18538. /**
  18539. * An array of bindings.
  18540. *
  18541. * @type {?Array<BindGroup>}
  18542. * @private
  18543. * @default null
  18544. */
  18545. this._bindings = null;
  18546. /**
  18547. * Reference to the node material observer.
  18548. *
  18549. * @type {?NodeMaterialObserver}
  18550. * @private
  18551. * @default null
  18552. */
  18553. this._monitor = null;
  18554. /**
  18555. * An event listener which is defined by `RenderObjects`. It performs
  18556. * clean up tasks when `dispose()` on this render object.
  18557. *
  18558. * @method
  18559. */
  18560. this.onDispose = null;
  18561. /**
  18562. * This flag can be used for type testing.
  18563. *
  18564. * @type {boolean}
  18565. * @readonly
  18566. * @default true
  18567. */
  18568. this.isRenderObject = true;
  18569. /**
  18570. * An event listener which is executed when `dispose()` is called on
  18571. * the render object's material.
  18572. *
  18573. * @method
  18574. */
  18575. this.onMaterialDispose = () => {
  18576. this.dispose();
  18577. };
  18578. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  18579. }
  18580. /**
  18581. * Updates the clipping context.
  18582. *
  18583. * @param {ClippingContext} context - The clipping context to set.
  18584. */
  18585. updateClipping( context ) {
  18586. this.clippingContext = context;
  18587. }
  18588. /**
  18589. * Whether the clipping requires an update or not.
  18590. *
  18591. * @type {boolean}
  18592. * @readonly
  18593. */
  18594. get clippingNeedsUpdate() {
  18595. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  18596. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  18597. return true;
  18598. }
  18599. /**
  18600. * The number of clipping planes defined in context of hardware clipping.
  18601. *
  18602. * @type {number}
  18603. * @readonly
  18604. */
  18605. get hardwareClippingPlanes() {
  18606. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  18607. }
  18608. /**
  18609. * Returns the node builder state of this render object.
  18610. *
  18611. * @return {NodeBuilderState} The node builder state.
  18612. */
  18613. getNodeBuilderState() {
  18614. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  18615. }
  18616. /**
  18617. * Returns the node material observer of this render object.
  18618. *
  18619. * @return {NodeMaterialObserver} The node material observer.
  18620. */
  18621. getMonitor() {
  18622. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  18623. }
  18624. /**
  18625. * Returns an array of bind groups of this render object.
  18626. *
  18627. * @return {Array<BindGroup>} The bindings.
  18628. */
  18629. getBindings() {
  18630. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  18631. }
  18632. /**
  18633. * Returns a binding group by group name of this render object.
  18634. *
  18635. * @param {string} name - The name of the binding group.
  18636. * @return {?BindGroup} The bindings.
  18637. */
  18638. getBindingGroup( name ) {
  18639. for ( const bindingGroup of this.getBindings() ) {
  18640. if ( bindingGroup.name === name ) {
  18641. return bindingGroup;
  18642. }
  18643. }
  18644. }
  18645. /**
  18646. * Returns the index of the render object's geometry.
  18647. *
  18648. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  18649. */
  18650. getIndex() {
  18651. return this._geometries.getIndex( this );
  18652. }
  18653. /**
  18654. * Returns the indirect buffer attribute.
  18655. *
  18656. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  18657. */
  18658. getIndirect() {
  18659. return this._geometries.getIndirect( this );
  18660. }
  18661. /**
  18662. * Returns an array that acts as a key for identifying the render object in a chain map.
  18663. *
  18664. * @return {Array<Object>} An array with object references.
  18665. */
  18666. getChainArray() {
  18667. return [ this.object, this.material, this.context, this.lightsNode ];
  18668. }
  18669. /**
  18670. * This method is used when the geometry of a 3D object has been exchanged and the
  18671. * respective render object now requires an update.
  18672. *
  18673. * @param {BufferGeometry} geometry - The geometry to set.
  18674. */
  18675. setGeometry( geometry ) {
  18676. this.geometry = geometry;
  18677. this.attributes = null;
  18678. }
  18679. /**
  18680. * Returns the buffer attributes of the render object. The returned array holds
  18681. * attribute definitions on geometry and node level.
  18682. *
  18683. * @return {Array<BufferAttribute>} An array with buffer attributes.
  18684. */
  18685. getAttributes() {
  18686. if ( this.attributes !== null ) return this.attributes;
  18687. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  18688. const geometry = this.geometry;
  18689. const attributes = [];
  18690. const vertexBuffers = new Set();
  18691. for ( const nodeAttribute of nodeAttributes ) {
  18692. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  18693. if ( attribute === undefined ) continue;
  18694. attributes.push( attribute );
  18695. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18696. vertexBuffers.add( bufferAttribute );
  18697. }
  18698. this.attributes = attributes;
  18699. this.vertexBuffers = Array.from( vertexBuffers.values() );
  18700. return attributes;
  18701. }
  18702. /**
  18703. * Returns the vertex buffers of the render object.
  18704. *
  18705. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  18706. */
  18707. getVertexBuffers() {
  18708. if ( this.vertexBuffers === null ) this.getAttributes();
  18709. return this.vertexBuffers;
  18710. }
  18711. /**
  18712. * Returns the draw parameters for the render object.
  18713. *
  18714. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  18715. */
  18716. getDrawParameters() {
  18717. const { object, material, geometry, group, drawRange } = this;
  18718. const drawParams = this.drawParams || ( this.drawParams = {
  18719. vertexCount: 0,
  18720. firstVertex: 0,
  18721. instanceCount: 0,
  18722. firstInstance: 0
  18723. } );
  18724. const index = this.getIndex();
  18725. const hasIndex = ( index !== null );
  18726. let instanceCount = 1;
  18727. if ( geometry.isInstancedBufferGeometry === true ) {
  18728. instanceCount = geometry.instanceCount;
  18729. } else if ( object.count !== undefined ) {
  18730. instanceCount = Math.max( 0, object.count );
  18731. }
  18732. if ( instanceCount === 0 ) return null;
  18733. drawParams.instanceCount = instanceCount;
  18734. if ( object.isBatchedMesh === true ) return drawParams;
  18735. let rangeFactor = 1;
  18736. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  18737. rangeFactor = 2;
  18738. }
  18739. let firstVertex = drawRange.start * rangeFactor;
  18740. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  18741. if ( group !== null ) {
  18742. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  18743. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  18744. }
  18745. const position = geometry.attributes.position;
  18746. let itemCount = Infinity;
  18747. if ( hasIndex ) {
  18748. itemCount = index.count;
  18749. } else if ( position !== undefined && position !== null ) {
  18750. itemCount = position.count;
  18751. }
  18752. firstVertex = Math.max( firstVertex, 0 );
  18753. lastVertex = Math.min( lastVertex, itemCount );
  18754. const count = lastVertex - firstVertex;
  18755. if ( count < 0 || count === Infinity ) return null;
  18756. drawParams.vertexCount = count;
  18757. drawParams.firstVertex = firstVertex;
  18758. return drawParams;
  18759. }
  18760. /**
  18761. * Returns the render object's geometry cache key.
  18762. *
  18763. * The geometry cache key is part of the material cache key.
  18764. *
  18765. * @return {string} The geometry cache key.
  18766. */
  18767. getGeometryCacheKey() {
  18768. const { geometry } = this;
  18769. let cacheKey = '';
  18770. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  18771. const attribute = geometry.attributes[ name ];
  18772. cacheKey += name + ',';
  18773. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  18774. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  18775. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  18776. if ( attribute.normalized ) cacheKey += 'n,';
  18777. }
  18778. // structural equality isn't sufficient for morph targets since the
  18779. // data are maintained in textures. only if the targets are all equal
  18780. // the texture and thus the instance of `MorphNode` can be shared.
  18781. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  18782. const targets = geometry.morphAttributes[ name ];
  18783. cacheKey += 'morph-' + name + ',';
  18784. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  18785. const attribute = targets[ i ];
  18786. cacheKey += attribute.id + ',';
  18787. }
  18788. }
  18789. if ( geometry.index ) {
  18790. cacheKey += 'index,';
  18791. }
  18792. return cacheKey;
  18793. }
  18794. /**
  18795. * Returns the render object's material cache key.
  18796. *
  18797. * The material cache key is part of the render object cache key.
  18798. *
  18799. * @return {number} The material cache key.
  18800. */
  18801. getMaterialCacheKey() {
  18802. const { object, material } = this;
  18803. let cacheKey = material.customProgramCacheKey();
  18804. for ( const property of getKeys( material ) ) {
  18805. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  18806. const value = material[ property ];
  18807. let valueKey;
  18808. if ( value !== null ) {
  18809. // some material values require a formatting
  18810. const type = typeof value;
  18811. if ( type === 'number' ) {
  18812. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  18813. } else if ( type === 'object' ) {
  18814. valueKey = '{';
  18815. if ( value.isTexture ) {
  18816. valueKey += value.mapping;
  18817. }
  18818. valueKey += '}';
  18819. } else {
  18820. valueKey = String( value );
  18821. }
  18822. } else {
  18823. valueKey = String( value );
  18824. }
  18825. cacheKey += /*property + ':' +*/ valueKey + ',';
  18826. }
  18827. cacheKey += this.clippingContextCacheKey + ',';
  18828. if ( object.geometry ) {
  18829. cacheKey += this.getGeometryCacheKey();
  18830. }
  18831. if ( object.skeleton ) {
  18832. cacheKey += object.skeleton.bones.length + ',';
  18833. }
  18834. if ( object.isBatchedMesh ) {
  18835. cacheKey += object._matricesTexture.uuid + ',';
  18836. if ( object._colorsTexture !== null ) {
  18837. cacheKey += object._colorsTexture.uuid + ',';
  18838. }
  18839. }
  18840. if ( object.count > 1 ) {
  18841. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  18842. cacheKey += object.uuid + ',';
  18843. }
  18844. cacheKey += object.receiveShadow + ',';
  18845. return hashString( cacheKey );
  18846. }
  18847. /**
  18848. * Whether the geometry requires an update or not.
  18849. *
  18850. * @type {boolean}
  18851. * @readonly
  18852. */
  18853. get needsGeometryUpdate() {
  18854. return this.geometry.id !== this.object.geometry.id;
  18855. }
  18856. /**
  18857. * Whether the render object requires an update or not.
  18858. *
  18859. * Note: There are two distinct places where render objects are checked for an update.
  18860. *
  18861. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  18862. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  18863. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  18864. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  18865. * a need for a refresh due to material, geometry or object related value changes.
  18866. *
  18867. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  18868. * that performs the 'needsUpdate' check.
  18869. *
  18870. * @type {boolean}
  18871. * @readonly
  18872. */
  18873. get needsUpdate() {
  18874. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  18875. }
  18876. /**
  18877. * Returns the dynamic cache key which represents a key that is computed per draw command.
  18878. *
  18879. * @return {number} The cache key.
  18880. */
  18881. getDynamicCacheKey() {
  18882. let cacheKey = 0;
  18883. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  18884. // the renderer is inside a shadow pass.
  18885. if ( this.material.isShadowPassMaterial !== true ) {
  18886. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  18887. }
  18888. if ( this.camera.isArrayCamera ) {
  18889. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  18890. }
  18891. if ( this.object.receiveShadow ) {
  18892. cacheKey = hash$1( cacheKey, 1 );
  18893. }
  18894. return cacheKey;
  18895. }
  18896. /**
  18897. * Returns the render object's cache key.
  18898. *
  18899. * @return {number} The cache key.
  18900. */
  18901. getCacheKey() {
  18902. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  18903. }
  18904. /**
  18905. * Frees internal resources.
  18906. */
  18907. dispose() {
  18908. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  18909. this.onDispose();
  18910. }
  18911. }
  18912. const _chainKeys$5 = [];
  18913. /**
  18914. * This module manages the render objects of the renderer.
  18915. *
  18916. * @private
  18917. */
  18918. class RenderObjects {
  18919. /**
  18920. * Constructs a new render object management component.
  18921. *
  18922. * @param {Renderer} renderer - The renderer.
  18923. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18924. * @param {Geometries} geometries - Renderer component for managing geometries.
  18925. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  18926. * @param {Bindings} bindings - Renderer component for managing bindings.
  18927. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18928. */
  18929. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  18930. /**
  18931. * The renderer.
  18932. *
  18933. * @type {Renderer}
  18934. */
  18935. this.renderer = renderer;
  18936. /**
  18937. * Renderer component for managing nodes related logic.
  18938. *
  18939. * @type {Nodes}
  18940. */
  18941. this.nodes = nodes;
  18942. /**
  18943. * Renderer component for managing geometries.
  18944. *
  18945. * @type {Geometries}
  18946. */
  18947. this.geometries = geometries;
  18948. /**
  18949. * Renderer component for managing pipelines.
  18950. *
  18951. * @type {Pipelines}
  18952. */
  18953. this.pipelines = pipelines;
  18954. /**
  18955. * Renderer component for managing bindings.
  18956. *
  18957. * @type {Bindings}
  18958. */
  18959. this.bindings = bindings;
  18960. /**
  18961. * Renderer component for managing metrics and monitoring data.
  18962. *
  18963. * @type {Info}
  18964. */
  18965. this.info = info;
  18966. /**
  18967. * A dictionary that manages render contexts in chain maps
  18968. * for each pass ID.
  18969. *
  18970. * @type {Object<string,ChainMap>}
  18971. */
  18972. this.chainMaps = {};
  18973. }
  18974. /**
  18975. * Returns a render object for the given object and state data.
  18976. *
  18977. * @param {Object3D} object - The 3D object.
  18978. * @param {Material} material - The 3D object's material.
  18979. * @param {Scene} scene - The scene the 3D object belongs to.
  18980. * @param {Camera} camera - The camera the 3D object should be rendered with.
  18981. * @param {LightsNode} lightsNode - The lights node.
  18982. * @param {RenderContext} renderContext - The render context.
  18983. * @param {ClippingContext} clippingContext - The clipping context.
  18984. * @param {string} [passId] - An optional ID for identifying the pass.
  18985. * @return {RenderObject} The render object.
  18986. */
  18987. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  18988. const chainMap = this.getChainMap( passId );
  18989. // reuse chainArray
  18990. _chainKeys$5[ 0 ] = object;
  18991. _chainKeys$5[ 1 ] = material;
  18992. _chainKeys$5[ 2 ] = renderContext;
  18993. _chainKeys$5[ 3 ] = lightsNode;
  18994. let renderObject = chainMap.get( _chainKeys$5 );
  18995. if ( renderObject === undefined ) {
  18996. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  18997. chainMap.set( _chainKeys$5, renderObject );
  18998. } else {
  18999. renderObject.updateClipping( clippingContext );
  19000. if ( renderObject.needsGeometryUpdate ) {
  19001. renderObject.setGeometry( object.geometry );
  19002. }
  19003. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  19004. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  19005. renderObject.dispose();
  19006. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19007. } else {
  19008. renderObject.version = material.version;
  19009. }
  19010. }
  19011. }
  19012. _chainKeys$5.length = 0;
  19013. return renderObject;
  19014. }
  19015. /**
  19016. * Returns a chain map for the given pass ID.
  19017. *
  19018. * @param {string} [passId='default'] - The pass ID.
  19019. * @return {ChainMap} The chain map.
  19020. */
  19021. getChainMap( passId = 'default' ) {
  19022. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  19023. }
  19024. /**
  19025. * Frees internal resources.
  19026. */
  19027. dispose() {
  19028. this.chainMaps = {};
  19029. }
  19030. /**
  19031. * Factory method for creating render objects with the given list of parameters.
  19032. *
  19033. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19034. * @param {Geometries} geometries - Renderer component for managing geometries.
  19035. * @param {Renderer} renderer - The renderer.
  19036. * @param {Object3D} object - The 3D object.
  19037. * @param {Material} material - The object's material.
  19038. * @param {Scene} scene - The scene the 3D object belongs to.
  19039. * @param {Camera} camera - The camera the object should be rendered with.
  19040. * @param {LightsNode} lightsNode - The lights node.
  19041. * @param {RenderContext} renderContext - The render context.
  19042. * @param {ClippingContext} clippingContext - The clipping context.
  19043. * @param {string} [passId] - An optional ID for identifying the pass.
  19044. * @return {RenderObject} The render object.
  19045. */
  19046. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19047. const chainMap = this.getChainMap( passId );
  19048. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  19049. renderObject.onDispose = () => {
  19050. this.pipelines.delete( renderObject );
  19051. this.bindings.delete( renderObject );
  19052. this.nodes.delete( renderObject );
  19053. chainMap.delete( renderObject.getChainArray() );
  19054. };
  19055. return renderObject;
  19056. }
  19057. }
  19058. /**
  19059. * Data structure for the renderer. It is intended to manage
  19060. * data of objects in dictionaries.
  19061. *
  19062. * @private
  19063. */
  19064. class DataMap {
  19065. /**
  19066. * Constructs a new data map.
  19067. */
  19068. constructor() {
  19069. /**
  19070. * `DataMap` internally uses a weak map
  19071. * to manage its data.
  19072. *
  19073. * @type {WeakMap}
  19074. */
  19075. this.data = new WeakMap();
  19076. }
  19077. /**
  19078. * Returns the dictionary for the given object.
  19079. *
  19080. * @param {Object} object - The object.
  19081. * @return {Object} The dictionary.
  19082. */
  19083. get( object ) {
  19084. let map = this.data.get( object );
  19085. if ( map === undefined ) {
  19086. map = {};
  19087. this.data.set( object, map );
  19088. }
  19089. return map;
  19090. }
  19091. /**
  19092. * Deletes the dictionary for the given object.
  19093. *
  19094. * @param {Object} object - The object.
  19095. * @return {?Object} The deleted dictionary.
  19096. */
  19097. delete( object ) {
  19098. let map = null;
  19099. if ( this.data.has( object ) ) {
  19100. map = this.data.get( object );
  19101. this.data.delete( object );
  19102. }
  19103. return map;
  19104. }
  19105. /**
  19106. * Returns `true` if the given object has a dictionary defined.
  19107. *
  19108. * @param {Object} object - The object to test.
  19109. * @return {boolean} Whether a dictionary is defined or not.
  19110. */
  19111. has( object ) {
  19112. return this.data.has( object );
  19113. }
  19114. /**
  19115. * Frees internal resources.
  19116. */
  19117. dispose() {
  19118. this.data = new WeakMap();
  19119. }
  19120. }
  19121. const AttributeType = {
  19122. VERTEX: 1,
  19123. INDEX: 2,
  19124. STORAGE: 3,
  19125. INDIRECT: 4
  19126. };
  19127. // size of a chunk in bytes (STD140 layout)
  19128. const GPU_CHUNK_BYTES = 16;
  19129. // @TODO: Move to src/constants.js
  19130. const BlendColorFactor = 211;
  19131. const OneMinusBlendColorFactor = 212;
  19132. /**
  19133. * This renderer module manages geometry attributes.
  19134. *
  19135. * @private
  19136. * @augments DataMap
  19137. */
  19138. class Attributes extends DataMap {
  19139. /**
  19140. * Constructs a new attribute management component.
  19141. *
  19142. * @param {Backend} backend - The renderer's backend.
  19143. */
  19144. constructor( backend ) {
  19145. super();
  19146. /**
  19147. * The renderer's backend.
  19148. *
  19149. * @type {Backend}
  19150. */
  19151. this.backend = backend;
  19152. }
  19153. /**
  19154. * Deletes the data for the given attribute.
  19155. *
  19156. * @param {BufferAttribute} attribute - The attribute.
  19157. * @return {Object|null} The deleted attribute data.
  19158. */
  19159. delete( attribute ) {
  19160. const attributeData = super.delete( attribute );
  19161. if ( attributeData !== null ) {
  19162. this.backend.destroyAttribute( attribute );
  19163. }
  19164. return attributeData;
  19165. }
  19166. /**
  19167. * Updates the given attribute. This method creates attribute buffers
  19168. * for new attributes and updates data for existing ones.
  19169. *
  19170. * @param {BufferAttribute} attribute - The attribute to update.
  19171. * @param {number} type - The attribute type.
  19172. */
  19173. update( attribute, type ) {
  19174. const data = this.get( attribute );
  19175. if ( data.version === undefined ) {
  19176. if ( type === AttributeType.VERTEX ) {
  19177. this.backend.createAttribute( attribute );
  19178. } else if ( type === AttributeType.INDEX ) {
  19179. this.backend.createIndexAttribute( attribute );
  19180. } else if ( type === AttributeType.STORAGE ) {
  19181. this.backend.createStorageAttribute( attribute );
  19182. } else if ( type === AttributeType.INDIRECT ) {
  19183. this.backend.createIndirectStorageAttribute( attribute );
  19184. }
  19185. data.version = this._getBufferAttribute( attribute ).version;
  19186. } else {
  19187. const bufferAttribute = this._getBufferAttribute( attribute );
  19188. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  19189. this.backend.updateAttribute( attribute );
  19190. data.version = bufferAttribute.version;
  19191. }
  19192. }
  19193. }
  19194. /**
  19195. * Utility method for handling interleaved buffer attributes correctly.
  19196. * To process them, their `InterleavedBuffer` is returned.
  19197. *
  19198. * @param {BufferAttribute} attribute - The attribute.
  19199. * @return {BufferAttribute|InterleavedBuffer}
  19200. */
  19201. _getBufferAttribute( attribute ) {
  19202. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  19203. return attribute;
  19204. }
  19205. }
  19206. /**
  19207. * Returns the wireframe version for the given geometry.
  19208. *
  19209. * @private
  19210. * @function
  19211. * @param {BufferGeometry} geometry - The geometry.
  19212. * @return {number} The version.
  19213. */
  19214. function getWireframeVersion( geometry ) {
  19215. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  19216. }
  19217. /**
  19218. * Returns a wireframe index attribute for the given geometry.
  19219. *
  19220. * @private
  19221. * @function
  19222. * @param {BufferGeometry} geometry - The geometry.
  19223. * @return {BufferAttribute} The wireframe index attribute.
  19224. */
  19225. function getWireframeIndex( geometry ) {
  19226. const indices = [];
  19227. const geometryIndex = geometry.index;
  19228. const geometryPosition = geometry.attributes.position;
  19229. if ( geometryIndex !== null ) {
  19230. const array = geometryIndex.array;
  19231. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  19232. const a = array[ i + 0 ];
  19233. const b = array[ i + 1 ];
  19234. const c = array[ i + 2 ];
  19235. indices.push( a, b, b, c, c, a );
  19236. }
  19237. } else {
  19238. const array = geometryPosition.array;
  19239. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  19240. const a = i + 0;
  19241. const b = i + 1;
  19242. const c = i + 2;
  19243. indices.push( a, b, b, c, c, a );
  19244. }
  19245. }
  19246. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  19247. attribute.version = getWireframeVersion( geometry );
  19248. return attribute;
  19249. }
  19250. /**
  19251. * This renderer module manages geometries.
  19252. *
  19253. * @private
  19254. * @augments DataMap
  19255. */
  19256. class Geometries extends DataMap {
  19257. /**
  19258. * Constructs a new geometry management component.
  19259. *
  19260. * @param {Attributes} attributes - Renderer component for managing attributes.
  19261. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19262. */
  19263. constructor( attributes, info ) {
  19264. super();
  19265. /**
  19266. * Renderer component for managing attributes.
  19267. *
  19268. * @type {Attributes}
  19269. */
  19270. this.attributes = attributes;
  19271. /**
  19272. * Renderer component for managing metrics and monitoring data.
  19273. *
  19274. * @type {Info}
  19275. */
  19276. this.info = info;
  19277. /**
  19278. * Weak Map for managing attributes for wireframe rendering.
  19279. *
  19280. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  19281. */
  19282. this.wireframes = new WeakMap();
  19283. /**
  19284. * This Weak Map is used to make sure buffer attributes are
  19285. * updated only once per render call.
  19286. *
  19287. * @type {WeakMap<BufferAttribute,number>}
  19288. */
  19289. this.attributeCall = new WeakMap();
  19290. }
  19291. /**
  19292. * Returns `true` if the given render object has an initialized geometry.
  19293. *
  19294. * @param {RenderObject} renderObject - The render object.
  19295. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  19296. */
  19297. has( renderObject ) {
  19298. const geometry = renderObject.geometry;
  19299. return super.has( geometry ) && this.get( geometry ).initialized === true;
  19300. }
  19301. /**
  19302. * Prepares the geometry of the given render object for rendering.
  19303. *
  19304. * @param {RenderObject} renderObject - The render object.
  19305. */
  19306. updateForRender( renderObject ) {
  19307. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  19308. this.updateAttributes( renderObject );
  19309. }
  19310. /**
  19311. * Initializes the geometry of the given render object.
  19312. *
  19313. * @param {RenderObject} renderObject - The render object.
  19314. */
  19315. initGeometry( renderObject ) {
  19316. const geometry = renderObject.geometry;
  19317. const geometryData = this.get( geometry );
  19318. geometryData.initialized = true;
  19319. this.info.memory.geometries ++;
  19320. const onDispose = () => {
  19321. this.info.memory.geometries --;
  19322. const index = geometry.index;
  19323. const geometryAttributes = renderObject.getAttributes();
  19324. if ( index !== null ) {
  19325. this.attributes.delete( index );
  19326. }
  19327. for ( const geometryAttribute of geometryAttributes ) {
  19328. this.attributes.delete( geometryAttribute );
  19329. }
  19330. const wireframeAttribute = this.wireframes.get( geometry );
  19331. if ( wireframeAttribute !== undefined ) {
  19332. this.attributes.delete( wireframeAttribute );
  19333. }
  19334. geometry.removeEventListener( 'dispose', onDispose );
  19335. };
  19336. geometry.addEventListener( 'dispose', onDispose );
  19337. }
  19338. /**
  19339. * Updates the geometry attributes of the given render object.
  19340. *
  19341. * @param {RenderObject} renderObject - The render object.
  19342. */
  19343. updateAttributes( renderObject ) {
  19344. // attributes
  19345. const attributes = renderObject.getAttributes();
  19346. for ( const attribute of attributes ) {
  19347. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  19348. this.updateAttribute( attribute, AttributeType.STORAGE );
  19349. } else {
  19350. this.updateAttribute( attribute, AttributeType.VERTEX );
  19351. }
  19352. }
  19353. // indexes
  19354. const index = this.getIndex( renderObject );
  19355. if ( index !== null ) {
  19356. this.updateAttribute( index, AttributeType.INDEX );
  19357. }
  19358. // indirect
  19359. const indirect = renderObject.geometry.indirect;
  19360. if ( indirect !== null ) {
  19361. this.updateAttribute( indirect, AttributeType.INDIRECT );
  19362. }
  19363. }
  19364. /**
  19365. * Updates the given attribute.
  19366. *
  19367. * @param {BufferAttribute} attribute - The attribute to update.
  19368. * @param {number} type - The attribute type.
  19369. */
  19370. updateAttribute( attribute, type ) {
  19371. const callId = this.info.render.calls;
  19372. if ( ! attribute.isInterleavedBufferAttribute ) {
  19373. if ( this.attributeCall.get( attribute ) !== callId ) {
  19374. this.attributes.update( attribute, type );
  19375. this.attributeCall.set( attribute, callId );
  19376. }
  19377. } else {
  19378. if ( this.attributeCall.get( attribute ) === undefined ) {
  19379. this.attributes.update( attribute, type );
  19380. this.attributeCall.set( attribute, callId );
  19381. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  19382. this.attributes.update( attribute, type );
  19383. this.attributeCall.set( attribute.data, callId );
  19384. this.attributeCall.set( attribute, callId );
  19385. }
  19386. }
  19387. }
  19388. /**
  19389. * Returns the indirect buffer attribute of the given render object.
  19390. *
  19391. * @param {RenderObject} renderObject - The render object.
  19392. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19393. */
  19394. getIndirect( renderObject ) {
  19395. return renderObject.geometry.indirect;
  19396. }
  19397. /**
  19398. * Returns the index of the given render object's geometry. This is implemented
  19399. * in a method to return a wireframe index if necessary.
  19400. *
  19401. * @param {RenderObject} renderObject - The render object.
  19402. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19403. */
  19404. getIndex( renderObject ) {
  19405. const { geometry, material } = renderObject;
  19406. let index = geometry.index;
  19407. if ( material.wireframe === true ) {
  19408. const wireframes = this.wireframes;
  19409. let wireframeAttribute = wireframes.get( geometry );
  19410. if ( wireframeAttribute === undefined ) {
  19411. wireframeAttribute = getWireframeIndex( geometry );
  19412. wireframes.set( geometry, wireframeAttribute );
  19413. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  19414. this.attributes.delete( wireframeAttribute );
  19415. wireframeAttribute = getWireframeIndex( geometry );
  19416. wireframes.set( geometry, wireframeAttribute );
  19417. }
  19418. index = wireframeAttribute;
  19419. }
  19420. return index;
  19421. }
  19422. }
  19423. /**
  19424. * This renderer module provides a series of statistical information
  19425. * about the GPU memory and the rendering process. Useful for debugging
  19426. * and monitoring.
  19427. */
  19428. class Info {
  19429. /**
  19430. * Constructs a new info component.
  19431. */
  19432. constructor() {
  19433. /**
  19434. * Whether frame related metrics should automatically
  19435. * be resetted or not. This property should be set to `false`
  19436. * by apps which manage their own animation loop. They must
  19437. * then call `renderer.info.reset()` once per frame manually.
  19438. *
  19439. * @type {boolean}
  19440. * @default true
  19441. */
  19442. this.autoReset = true;
  19443. /**
  19444. * The current frame ID. This ID is managed
  19445. * by `NodeFrame`.
  19446. *
  19447. * @type {number}
  19448. * @readonly
  19449. * @default 0
  19450. */
  19451. this.frame = 0;
  19452. /**
  19453. * The number of render calls since the
  19454. * app has been started.
  19455. *
  19456. * @type {number}
  19457. * @readonly
  19458. * @default 0
  19459. */
  19460. this.calls = 0;
  19461. /**
  19462. * Render related metrics.
  19463. *
  19464. * @type {Object}
  19465. * @readonly
  19466. * @property {number} calls - The number of render calls since the app has been started.
  19467. * @property {number} frameCalls - The number of render calls of the current frame.
  19468. * @property {number} drawCalls - The number of draw calls of the current frame.
  19469. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  19470. * @property {number} points - The number of rendered point primitives of the current frame.
  19471. * @property {number} lines - The number of rendered line primitives of the current frame.
  19472. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  19473. */
  19474. this.render = {
  19475. calls: 0,
  19476. frameCalls: 0,
  19477. drawCalls: 0,
  19478. triangles: 0,
  19479. points: 0,
  19480. lines: 0,
  19481. timestamp: 0,
  19482. };
  19483. /**
  19484. * Compute related metrics.
  19485. *
  19486. * @type {Object}
  19487. * @readonly
  19488. * @property {number} calls - The number of compute calls since the app has been started.
  19489. * @property {number} frameCalls - The number of compute calls of the current frame.
  19490. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  19491. */
  19492. this.compute = {
  19493. calls: 0,
  19494. frameCalls: 0,
  19495. timestamp: 0
  19496. };
  19497. /**
  19498. * Memory related metrics.
  19499. *
  19500. * @type {Object}
  19501. * @readonly
  19502. * @property {number} geometries - The number of active geometries.
  19503. * @property {number} frameCalls - The number of active textures.
  19504. */
  19505. this.memory = {
  19506. geometries: 0,
  19507. textures: 0
  19508. };
  19509. }
  19510. /**
  19511. * This method should be executed per draw call and updates the corresponding metrics.
  19512. *
  19513. * @param {Object3D} object - The 3D object that is going to be rendered.
  19514. * @param {number} count - The vertex or index count.
  19515. * @param {number} instanceCount - The instance count.
  19516. */
  19517. update( object, count, instanceCount ) {
  19518. this.render.drawCalls ++;
  19519. if ( object.isMesh || object.isSprite ) {
  19520. this.render.triangles += instanceCount * ( count / 3 );
  19521. } else if ( object.isPoints ) {
  19522. this.render.points += instanceCount * count;
  19523. } else if ( object.isLineSegments ) {
  19524. this.render.lines += instanceCount * ( count / 2 );
  19525. } else if ( object.isLine ) {
  19526. this.render.lines += instanceCount * ( count - 1 );
  19527. } else {
  19528. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  19529. }
  19530. }
  19531. /**
  19532. * Resets frame related metrics.
  19533. */
  19534. reset() {
  19535. this.render.drawCalls = 0;
  19536. this.render.frameCalls = 0;
  19537. this.compute.frameCalls = 0;
  19538. this.render.triangles = 0;
  19539. this.render.points = 0;
  19540. this.render.lines = 0;
  19541. }
  19542. /**
  19543. * Performs a complete reset of the object.
  19544. */
  19545. dispose() {
  19546. this.reset();
  19547. this.calls = 0;
  19548. this.render.calls = 0;
  19549. this.compute.calls = 0;
  19550. this.render.timestamp = 0;
  19551. this.compute.timestamp = 0;
  19552. this.memory.geometries = 0;
  19553. this.memory.textures = 0;
  19554. }
  19555. }
  19556. /**
  19557. * Abstract class for representing pipelines.
  19558. *
  19559. * @private
  19560. * @abstract
  19561. */
  19562. class Pipeline {
  19563. /**
  19564. * Constructs a new pipeline.
  19565. *
  19566. * @param {string} cacheKey - The pipeline's cache key.
  19567. */
  19568. constructor( cacheKey ) {
  19569. /**
  19570. * The pipeline's cache key.
  19571. *
  19572. * @type {string}
  19573. */
  19574. this.cacheKey = cacheKey;
  19575. /**
  19576. * How often the pipeline is currently in use.
  19577. *
  19578. * @type {number}
  19579. * @default 0
  19580. */
  19581. this.usedTimes = 0;
  19582. }
  19583. }
  19584. /**
  19585. * Class for representing render pipelines.
  19586. *
  19587. * @private
  19588. * @augments Pipeline
  19589. */
  19590. class RenderPipeline extends Pipeline {
  19591. /**
  19592. * Constructs a new render pipeline.
  19593. *
  19594. * @param {string} cacheKey - The pipeline's cache key.
  19595. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  19596. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  19597. */
  19598. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  19599. super( cacheKey );
  19600. /**
  19601. * The pipeline's vertex shader.
  19602. *
  19603. * @type {ProgrammableStage}
  19604. */
  19605. this.vertexProgram = vertexProgram;
  19606. /**
  19607. * The pipeline's fragment shader.
  19608. *
  19609. * @type {ProgrammableStage}
  19610. */
  19611. this.fragmentProgram = fragmentProgram;
  19612. }
  19613. }
  19614. /**
  19615. * Class for representing compute pipelines.
  19616. *
  19617. * @private
  19618. * @augments Pipeline
  19619. */
  19620. class ComputePipeline extends Pipeline {
  19621. /**
  19622. * Constructs a new render pipeline.
  19623. *
  19624. * @param {string} cacheKey - The pipeline's cache key.
  19625. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  19626. */
  19627. constructor( cacheKey, computeProgram ) {
  19628. super( cacheKey );
  19629. /**
  19630. * The pipeline's compute shader.
  19631. *
  19632. * @type {ProgrammableStage}
  19633. */
  19634. this.computeProgram = computeProgram;
  19635. /**
  19636. * This flag can be used for type testing.
  19637. *
  19638. * @type {boolean}
  19639. * @readonly
  19640. * @default true
  19641. */
  19642. this.isComputePipeline = true;
  19643. }
  19644. }
  19645. let _id$8 = 0;
  19646. /**
  19647. * Class for representing programmable stages which are vertex,
  19648. * fragment or compute shaders. Unlike fixed-function states (like blending),
  19649. * they represent the programmable part of a pipeline.
  19650. *
  19651. * @private
  19652. */
  19653. class ProgrammableStage {
  19654. /**
  19655. * Constructs a new programmable stage.
  19656. *
  19657. * @param {string} code - The shader code.
  19658. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  19659. * @param {string} name - The name of the shader.
  19660. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19661. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19662. */
  19663. constructor( code, stage, name, transforms = null, attributes = null ) {
  19664. /**
  19665. * The id of the programmable stage.
  19666. *
  19667. * @type {number}
  19668. */
  19669. this.id = _id$8 ++;
  19670. /**
  19671. * The shader code.
  19672. *
  19673. * @type {string}
  19674. */
  19675. this.code = code;
  19676. /**
  19677. * The type of stage.
  19678. *
  19679. * @type {string}
  19680. */
  19681. this.stage = stage;
  19682. /**
  19683. * The name of the stage.
  19684. * This is used for debugging purposes.
  19685. *
  19686. * @type {string}
  19687. */
  19688. this.name = name;
  19689. /**
  19690. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19691. *
  19692. * @type {?Array<Object>}
  19693. */
  19694. this.transforms = transforms;
  19695. /**
  19696. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19697. *
  19698. * @type {?Array<Object>}
  19699. */
  19700. this.attributes = attributes;
  19701. /**
  19702. * How often the programmable stage is currently in use.
  19703. *
  19704. * @type {number}
  19705. * @default 0
  19706. */
  19707. this.usedTimes = 0;
  19708. }
  19709. }
  19710. /**
  19711. * This renderer module manages the pipelines of the renderer.
  19712. *
  19713. * @private
  19714. * @augments DataMap
  19715. */
  19716. class Pipelines extends DataMap {
  19717. /**
  19718. * Constructs a new pipeline management component.
  19719. *
  19720. * @param {Backend} backend - The renderer's backend.
  19721. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19722. */
  19723. constructor( backend, nodes ) {
  19724. super();
  19725. /**
  19726. * The renderer's backend.
  19727. *
  19728. * @type {Backend}
  19729. */
  19730. this.backend = backend;
  19731. /**
  19732. * Renderer component for managing nodes related logic.
  19733. *
  19734. * @type {Nodes}
  19735. */
  19736. this.nodes = nodes;
  19737. /**
  19738. * A references to the bindings management component.
  19739. * This reference will be set inside the `Bindings`
  19740. * constructor.
  19741. *
  19742. * @type {?Bindings}
  19743. * @default null
  19744. */
  19745. this.bindings = null;
  19746. /**
  19747. * Internal cache for maintaining pipelines.
  19748. * The key of the map is a cache key, the value the pipeline.
  19749. *
  19750. * @type {Map<string,Pipeline>}
  19751. */
  19752. this.caches = new Map();
  19753. /**
  19754. * This dictionary maintains for each shader stage type (vertex,
  19755. * fragment and compute) the programmable stage objects which
  19756. * represent the actual shader code.
  19757. *
  19758. * @type {Object<string,Map>}
  19759. */
  19760. this.programs = {
  19761. vertex: new Map(),
  19762. fragment: new Map(),
  19763. compute: new Map()
  19764. };
  19765. }
  19766. /**
  19767. * Returns a compute pipeline for the given compute node.
  19768. *
  19769. * @param {Node} computeNode - The compute node.
  19770. * @param {Array<BindGroup>} bindings - The bindings.
  19771. * @return {ComputePipeline} The compute pipeline.
  19772. */
  19773. getForCompute( computeNode, bindings ) {
  19774. const { backend } = this;
  19775. const data = this.get( computeNode );
  19776. if ( this._needsComputeUpdate( computeNode ) ) {
  19777. const previousPipeline = data.pipeline;
  19778. if ( previousPipeline ) {
  19779. previousPipeline.usedTimes --;
  19780. previousPipeline.computeProgram.usedTimes --;
  19781. }
  19782. // get shader
  19783. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  19784. // programmable stage
  19785. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  19786. if ( stageCompute === undefined ) {
  19787. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  19788. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  19789. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  19790. backend.createProgram( stageCompute );
  19791. }
  19792. // determine compute pipeline
  19793. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  19794. let pipeline = this.caches.get( cacheKey );
  19795. if ( pipeline === undefined ) {
  19796. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  19797. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  19798. }
  19799. // keep track of all used times
  19800. pipeline.usedTimes ++;
  19801. stageCompute.usedTimes ++;
  19802. //
  19803. data.version = computeNode.version;
  19804. data.pipeline = pipeline;
  19805. }
  19806. return data.pipeline;
  19807. }
  19808. /**
  19809. * Returns a render pipeline for the given render object.
  19810. *
  19811. * @param {RenderObject} renderObject - The render object.
  19812. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  19813. * @return {RenderPipeline} The render pipeline.
  19814. */
  19815. getForRender( renderObject, promises = null ) {
  19816. const { backend } = this;
  19817. const data = this.get( renderObject );
  19818. if ( this._needsRenderUpdate( renderObject ) ) {
  19819. const previousPipeline = data.pipeline;
  19820. if ( previousPipeline ) {
  19821. previousPipeline.usedTimes --;
  19822. previousPipeline.vertexProgram.usedTimes --;
  19823. previousPipeline.fragmentProgram.usedTimes --;
  19824. }
  19825. // get shader
  19826. const nodeBuilderState = renderObject.getNodeBuilderState();
  19827. const name = renderObject.material ? renderObject.material.name : '';
  19828. // programmable stages
  19829. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  19830. if ( stageVertex === undefined ) {
  19831. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  19832. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  19833. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  19834. backend.createProgram( stageVertex );
  19835. }
  19836. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  19837. if ( stageFragment === undefined ) {
  19838. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  19839. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  19840. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  19841. backend.createProgram( stageFragment );
  19842. }
  19843. // determine render pipeline
  19844. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  19845. let pipeline = this.caches.get( cacheKey );
  19846. if ( pipeline === undefined ) {
  19847. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  19848. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  19849. } else {
  19850. renderObject.pipeline = pipeline;
  19851. }
  19852. // keep track of all used times
  19853. pipeline.usedTimes ++;
  19854. stageVertex.usedTimes ++;
  19855. stageFragment.usedTimes ++;
  19856. //
  19857. data.pipeline = pipeline;
  19858. }
  19859. return data.pipeline;
  19860. }
  19861. /**
  19862. * Deletes the pipeline for the given render object.
  19863. *
  19864. * @param {RenderObject} object - The render object.
  19865. * @return {?Object} The deleted dictionary.
  19866. */
  19867. delete( object ) {
  19868. const pipeline = this.get( object ).pipeline;
  19869. if ( pipeline ) {
  19870. // pipeline
  19871. pipeline.usedTimes --;
  19872. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  19873. // programs
  19874. if ( pipeline.isComputePipeline ) {
  19875. pipeline.computeProgram.usedTimes --;
  19876. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  19877. } else {
  19878. pipeline.fragmentProgram.usedTimes --;
  19879. pipeline.vertexProgram.usedTimes --;
  19880. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  19881. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  19882. }
  19883. }
  19884. return super.delete( object );
  19885. }
  19886. /**
  19887. * Frees internal resources.
  19888. */
  19889. dispose() {
  19890. super.dispose();
  19891. this.caches = new Map();
  19892. this.programs = {
  19893. vertex: new Map(),
  19894. fragment: new Map(),
  19895. compute: new Map()
  19896. };
  19897. }
  19898. /**
  19899. * Updates the pipeline for the given render object.
  19900. *
  19901. * @param {RenderObject} renderObject - The render object.
  19902. */
  19903. updateForRender( renderObject ) {
  19904. this.getForRender( renderObject );
  19905. }
  19906. /**
  19907. * Returns a compute pipeline for the given parameters.
  19908. *
  19909. * @private
  19910. * @param {Node} computeNode - The compute node.
  19911. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  19912. * @param {string} cacheKey - The cache key.
  19913. * @param {Array<BindGroup>} bindings - The bindings.
  19914. * @return {ComputePipeline} The compute pipeline.
  19915. */
  19916. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  19917. // check for existing pipeline
  19918. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  19919. let pipeline = this.caches.get( cacheKey );
  19920. if ( pipeline === undefined ) {
  19921. pipeline = new ComputePipeline( cacheKey, stageCompute );
  19922. this.caches.set( cacheKey, pipeline );
  19923. this.backend.createComputePipeline( pipeline, bindings );
  19924. }
  19925. return pipeline;
  19926. }
  19927. /**
  19928. * Returns a render pipeline for the given parameters.
  19929. *
  19930. * @private
  19931. * @param {RenderObject} renderObject - The render object.
  19932. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  19933. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  19934. * @param {string} cacheKey - The cache key.
  19935. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  19936. * @return {ComputePipeline} The compute pipeline.
  19937. */
  19938. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  19939. // check for existing pipeline
  19940. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  19941. let pipeline = this.caches.get( cacheKey );
  19942. if ( pipeline === undefined ) {
  19943. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  19944. this.caches.set( cacheKey, pipeline );
  19945. renderObject.pipeline = pipeline;
  19946. // The `promises` array is `null` by default and only set to an empty array when
  19947. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  19948. // pending promises that resolve when the render pipelines are ready for rendering.
  19949. this.backend.createRenderPipeline( renderObject, promises );
  19950. }
  19951. return pipeline;
  19952. }
  19953. /**
  19954. * Computes a cache key representing a compute pipeline.
  19955. *
  19956. * @private
  19957. * @param {Node} computeNode - The compute node.
  19958. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  19959. * @return {string} The cache key.
  19960. */
  19961. _getComputeCacheKey( computeNode, stageCompute ) {
  19962. return computeNode.id + ',' + stageCompute.id;
  19963. }
  19964. /**
  19965. * Computes a cache key representing a render pipeline.
  19966. *
  19967. * @private
  19968. * @param {RenderObject} renderObject - The render object.
  19969. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  19970. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  19971. * @return {string} The cache key.
  19972. */
  19973. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  19974. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  19975. }
  19976. /**
  19977. * Releases the given pipeline.
  19978. *
  19979. * @private
  19980. * @param {Pipeline} pipeline - The pipeline to release.
  19981. */
  19982. _releasePipeline( pipeline ) {
  19983. this.caches.delete( pipeline.cacheKey );
  19984. }
  19985. /**
  19986. * Releases the shader program.
  19987. *
  19988. * @private
  19989. * @param {Object} program - The shader program to release.
  19990. */
  19991. _releaseProgram( program ) {
  19992. const code = program.code;
  19993. const stage = program.stage;
  19994. this.programs[ stage ].delete( code );
  19995. }
  19996. /**
  19997. * Returns `true` if the compute pipeline for the given compute node requires an update.
  19998. *
  19999. * @private
  20000. * @param {Node} computeNode - The compute node.
  20001. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  20002. */
  20003. _needsComputeUpdate( computeNode ) {
  20004. const data = this.get( computeNode );
  20005. return data.pipeline === undefined || data.version !== computeNode.version;
  20006. }
  20007. /**
  20008. * Returns `true` if the render pipeline for the given render object requires an update.
  20009. *
  20010. * @private
  20011. * @param {RenderObject} renderObject - The render object.
  20012. * @return {boolean} Whether the render object for the given render object requires an update or not.
  20013. */
  20014. _needsRenderUpdate( renderObject ) {
  20015. const data = this.get( renderObject );
  20016. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  20017. }
  20018. }
  20019. /**
  20020. * This renderer module manages the bindings of the renderer.
  20021. *
  20022. * @private
  20023. * @augments DataMap
  20024. */
  20025. class Bindings extends DataMap {
  20026. /**
  20027. * Constructs a new bindings management component.
  20028. *
  20029. * @param {Backend} backend - The renderer's backend.
  20030. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20031. * @param {Textures} textures - Renderer component for managing textures.
  20032. * @param {Attributes} attributes - Renderer component for managing attributes.
  20033. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20034. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20035. */
  20036. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  20037. super();
  20038. /**
  20039. * The renderer's backend.
  20040. *
  20041. * @type {Backend}
  20042. */
  20043. this.backend = backend;
  20044. /**
  20045. * Renderer component for managing textures.
  20046. *
  20047. * @type {Textures}
  20048. */
  20049. this.textures = textures;
  20050. /**
  20051. * Renderer component for managing pipelines.
  20052. *
  20053. * @type {Pipelines}
  20054. */
  20055. this.pipelines = pipelines;
  20056. /**
  20057. * Renderer component for managing attributes.
  20058. *
  20059. * @type {Attributes}
  20060. */
  20061. this.attributes = attributes;
  20062. /**
  20063. * Renderer component for managing nodes related logic.
  20064. *
  20065. * @type {Nodes}
  20066. */
  20067. this.nodes = nodes;
  20068. /**
  20069. * Renderer component for managing metrics and monitoring data.
  20070. *
  20071. * @type {Info}
  20072. */
  20073. this.info = info;
  20074. this.pipelines.bindings = this; // assign bindings to pipelines
  20075. }
  20076. /**
  20077. * Returns the bind groups for the given render object.
  20078. *
  20079. * @param {RenderObject} renderObject - The render object.
  20080. * @return {Array<BindGroup>} The bind groups.
  20081. */
  20082. getForRender( renderObject ) {
  20083. const bindings = renderObject.getBindings();
  20084. for ( const bindGroup of bindings ) {
  20085. const groupData = this.get( bindGroup );
  20086. if ( groupData.bindGroup === undefined ) {
  20087. // each object defines an array of bindings (ubos, textures, samplers etc.)
  20088. this._init( bindGroup );
  20089. this.backend.createBindings( bindGroup, bindings, 0 );
  20090. groupData.bindGroup = bindGroup;
  20091. }
  20092. }
  20093. return bindings;
  20094. }
  20095. /**
  20096. * Returns the bind groups for the given compute node.
  20097. *
  20098. * @param {Node} computeNode - The compute node.
  20099. * @return {Array<BindGroup>} The bind groups.
  20100. */
  20101. getForCompute( computeNode ) {
  20102. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  20103. for ( const bindGroup of bindings ) {
  20104. const groupData = this.get( bindGroup );
  20105. if ( groupData.bindGroup === undefined ) {
  20106. this._init( bindGroup );
  20107. this.backend.createBindings( bindGroup, bindings, 0 );
  20108. groupData.bindGroup = bindGroup;
  20109. }
  20110. }
  20111. return bindings;
  20112. }
  20113. /**
  20114. * Updates the bindings for the given compute node.
  20115. *
  20116. * @param {Node} computeNode - The compute node.
  20117. */
  20118. updateForCompute( computeNode ) {
  20119. this._updateBindings( this.getForCompute( computeNode ) );
  20120. }
  20121. /**
  20122. * Updates the bindings for the given render object.
  20123. *
  20124. * @param {RenderObject} renderObject - The render object.
  20125. */
  20126. updateForRender( renderObject ) {
  20127. this._updateBindings( this.getForRender( renderObject ) );
  20128. }
  20129. /**
  20130. * Updates the given array of bindings.
  20131. *
  20132. * @param {Array<BindGroup>} bindings - The bind groups.
  20133. */
  20134. _updateBindings( bindings ) {
  20135. for ( const bindGroup of bindings ) {
  20136. this._update( bindGroup, bindings );
  20137. }
  20138. }
  20139. /**
  20140. * Initializes the given bind group.
  20141. *
  20142. * @param {BindGroup} bindGroup - The bind group to initialize.
  20143. */
  20144. _init( bindGroup ) {
  20145. for ( const binding of bindGroup.bindings ) {
  20146. if ( binding.isSampledTexture ) {
  20147. this.textures.updateTexture( binding.texture );
  20148. } else if ( binding.isStorageBuffer ) {
  20149. const attribute = binding.attribute;
  20150. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20151. this.attributes.update( attribute, attributeType );
  20152. }
  20153. }
  20154. }
  20155. /**
  20156. * Updates the given bind group.
  20157. *
  20158. * @param {BindGroup} bindGroup - The bind group to update.
  20159. * @param {Array<BindGroup>} bindings - The bind groups.
  20160. */
  20161. _update( bindGroup, bindings ) {
  20162. const { backend } = this;
  20163. let needsBindingsUpdate = false;
  20164. let cacheBindings = true;
  20165. let cacheIndex = 0;
  20166. let version = 0;
  20167. // iterate over all bindings and check if buffer updates or a new binding group is required
  20168. for ( const binding of bindGroup.bindings ) {
  20169. if ( binding.isNodeUniformsGroup ) {
  20170. const updated = this.nodes.updateGroup( binding );
  20171. // every uniforms group is a uniform buffer. So if no update is required,
  20172. // we move one with the next binding. Otherwise the next if block will update the group.
  20173. if ( updated === false ) continue;
  20174. }
  20175. if ( binding.isStorageBuffer ) {
  20176. const attribute = binding.attribute;
  20177. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20178. this.attributes.update( attribute, attributeType );
  20179. }
  20180. if ( binding.isUniformBuffer ) {
  20181. const updated = binding.update();
  20182. if ( updated ) {
  20183. backend.updateBinding( binding );
  20184. }
  20185. } else if ( binding.isSampler ) {
  20186. binding.update();
  20187. } else if ( binding.isSampledTexture ) {
  20188. const texturesTextureData = this.textures.get( binding.texture );
  20189. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  20190. const updated = binding.update();
  20191. const texture = binding.texture;
  20192. if ( updated ) {
  20193. this.textures.updateTexture( texture );
  20194. }
  20195. const textureData = backend.get( texture );
  20196. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  20197. cacheBindings = false;
  20198. } else {
  20199. cacheIndex = cacheIndex * 10 + texture.id;
  20200. version += texture.version;
  20201. }
  20202. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  20203. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  20204. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  20205. this.textures.updateTexture( texture );
  20206. needsBindingsUpdate = true;
  20207. }
  20208. if ( texture.isStorageTexture === true ) {
  20209. const textureData = this.get( texture );
  20210. if ( binding.store === true ) {
  20211. textureData.needsMipmap = true;
  20212. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  20213. this.backend.generateMipmaps( texture );
  20214. textureData.needsMipmap = false;
  20215. }
  20216. }
  20217. }
  20218. }
  20219. if ( needsBindingsUpdate === true ) {
  20220. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  20221. }
  20222. }
  20223. }
  20224. /**
  20225. * Default sorting function for opaque render items.
  20226. *
  20227. * @private
  20228. * @function
  20229. * @param {Object} a - The first render item.
  20230. * @param {Object} b - The second render item.
  20231. * @return {number} A numeric value which defines the sort order.
  20232. */
  20233. function painterSortStable( a, b ) {
  20234. if ( a.groupOrder !== b.groupOrder ) {
  20235. return a.groupOrder - b.groupOrder;
  20236. } else if ( a.renderOrder !== b.renderOrder ) {
  20237. return a.renderOrder - b.renderOrder;
  20238. } else if ( a.z !== b.z ) {
  20239. return a.z - b.z;
  20240. } else {
  20241. return a.id - b.id;
  20242. }
  20243. }
  20244. /**
  20245. * Default sorting function for transparent render items.
  20246. *
  20247. * @private
  20248. * @function
  20249. * @param {Object} a - The first render item.
  20250. * @param {Object} b - The second render item.
  20251. * @return {number} A numeric value which defines the sort order.
  20252. */
  20253. function reversePainterSortStable( a, b ) {
  20254. if ( a.groupOrder !== b.groupOrder ) {
  20255. return a.groupOrder - b.groupOrder;
  20256. } else if ( a.renderOrder !== b.renderOrder ) {
  20257. return a.renderOrder - b.renderOrder;
  20258. } else if ( a.z !== b.z ) {
  20259. return b.z - a.z;
  20260. } else {
  20261. return a.id - b.id;
  20262. }
  20263. }
  20264. /**
  20265. * Returns `true` if the given transparent material requires a double pass.
  20266. *
  20267. * @private
  20268. * @function
  20269. * @param {Material} material - The transparent material.
  20270. * @return {boolean} Whether the given material requires a double pass or not.
  20271. */
  20272. function needsDoublePass( material ) {
  20273. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  20274. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  20275. }
  20276. /**
  20277. * When the renderer analyzes the scene at the beginning of a render call,
  20278. * it stores 3D object for further processing in render lists. Depending on the
  20279. * properties of a 3D objects (like their transformation or material state), the
  20280. * objects are maintained in ordered lists for the actual rendering.
  20281. *
  20282. * Render lists are unique per scene and camera combination.
  20283. *
  20284. * @private
  20285. * @augments Pipeline
  20286. */
  20287. class RenderList {
  20288. /**
  20289. * Constructs a render list.
  20290. *
  20291. * @param {Lighting} lighting - The lighting management component.
  20292. * @param {Scene} scene - The scene.
  20293. * @param {Camera} camera - The camera the scene is rendered with.
  20294. */
  20295. constructor( lighting, scene, camera ) {
  20296. /**
  20297. * 3D objects are transformed into render items and stored in this array.
  20298. *
  20299. * @type {Array<Object>}
  20300. */
  20301. this.renderItems = [];
  20302. /**
  20303. * The current render items index.
  20304. *
  20305. * @type {number}
  20306. * @default 0
  20307. */
  20308. this.renderItemsIndex = 0;
  20309. /**
  20310. * A list with opaque render items.
  20311. *
  20312. * @type {Array<Object>}
  20313. */
  20314. this.opaque = [];
  20315. /**
  20316. * A list with transparent render items which require
  20317. * double pass rendering (e.g. transmissive objects).
  20318. *
  20319. * @type {Array<Object>}
  20320. */
  20321. this.transparentDoublePass = [];
  20322. /**
  20323. * A list with transparent render items.
  20324. *
  20325. * @type {Array<Object>}
  20326. */
  20327. this.transparent = [];
  20328. /**
  20329. * A list with transparent render bundle data.
  20330. *
  20331. * @type {Array<Object>}
  20332. */
  20333. this.bundles = [];
  20334. /**
  20335. * The render list's lights node. This node is later
  20336. * relevant for the actual analytical light nodes which
  20337. * compute the scene's lighting in the shader.
  20338. *
  20339. * @type {LightsNode}
  20340. */
  20341. this.lightsNode = lighting.getNode( scene, camera );
  20342. /**
  20343. * The scene's lights stored in an array. This array
  20344. * is used to setup the lights node.
  20345. *
  20346. * @type {Array<Light>}
  20347. */
  20348. this.lightsArray = [];
  20349. /**
  20350. * The scene.
  20351. *
  20352. * @type {Scene}
  20353. */
  20354. this.scene = scene;
  20355. /**
  20356. * The camera the scene is rendered with.
  20357. *
  20358. * @type {Camera}
  20359. */
  20360. this.camera = camera;
  20361. /**
  20362. * How many objects perform occlusion query tests.
  20363. *
  20364. * @type {number}
  20365. * @default 0
  20366. */
  20367. this.occlusionQueryCount = 0;
  20368. }
  20369. /**
  20370. * This method is called right at the beginning of a render call
  20371. * before the scene is analyzed. It prepares the internal data
  20372. * structures for the upcoming render lists generation.
  20373. *
  20374. * @return {RenderList} A reference to this render list.
  20375. */
  20376. begin() {
  20377. this.renderItemsIndex = 0;
  20378. this.opaque.length = 0;
  20379. this.transparentDoublePass.length = 0;
  20380. this.transparent.length = 0;
  20381. this.bundles.length = 0;
  20382. this.lightsArray.length = 0;
  20383. this.occlusionQueryCount = 0;
  20384. return this;
  20385. }
  20386. /**
  20387. * Returns a render item for the giving render item state. The state is defined
  20388. * by a series of object-related parameters.
  20389. *
  20390. * The method avoids object creation by holding render items and reusing them in
  20391. * subsequent render calls (just with different property values).
  20392. *
  20393. * @param {Object3D} object - The 3D object.
  20394. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20395. * @param {Material} material - The 3D object's material.
  20396. * @param {number} groupOrder - The current group order.
  20397. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20398. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20399. * @param {ClippingContext} clippingContext - The current clipping context.
  20400. * @return {Object} The render item.
  20401. */
  20402. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20403. let renderItem = this.renderItems[ this.renderItemsIndex ];
  20404. if ( renderItem === undefined ) {
  20405. renderItem = {
  20406. id: object.id,
  20407. object: object,
  20408. geometry: geometry,
  20409. material: material,
  20410. groupOrder: groupOrder,
  20411. renderOrder: object.renderOrder,
  20412. z: z,
  20413. group: group,
  20414. clippingContext: clippingContext
  20415. };
  20416. this.renderItems[ this.renderItemsIndex ] = renderItem;
  20417. } else {
  20418. renderItem.id = object.id;
  20419. renderItem.object = object;
  20420. renderItem.geometry = geometry;
  20421. renderItem.material = material;
  20422. renderItem.groupOrder = groupOrder;
  20423. renderItem.renderOrder = object.renderOrder;
  20424. renderItem.z = z;
  20425. renderItem.group = group;
  20426. renderItem.clippingContext = clippingContext;
  20427. }
  20428. this.renderItemsIndex ++;
  20429. return renderItem;
  20430. }
  20431. /**
  20432. * Pushes the given object as a render item to the internal render lists.
  20433. * The selected lists depend on the object properties.
  20434. *
  20435. * @param {Object3D} object - The 3D object.
  20436. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20437. * @param {Material} material - The 3D object's material.
  20438. * @param {number} groupOrder - The current group order.
  20439. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20440. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20441. * @param {ClippingContext} clippingContext - The current clipping context.
  20442. */
  20443. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20444. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  20445. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  20446. if ( material.transparent === true || material.transmission > 0 ) {
  20447. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  20448. this.transparent.push( renderItem );
  20449. } else {
  20450. this.opaque.push( renderItem );
  20451. }
  20452. }
  20453. /**
  20454. * Inserts the given object as a render item at the start of the internal render lists.
  20455. * The selected lists depend on the object properties.
  20456. *
  20457. * @param {Object3D} object - The 3D object.
  20458. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20459. * @param {Material} material - The 3D object's material.
  20460. * @param {number} groupOrder - The current group order.
  20461. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20462. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20463. * @param {ClippingContext} clippingContext - The current clipping context.
  20464. */
  20465. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20466. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  20467. if ( material.transparent === true || material.transmission > 0 ) {
  20468. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  20469. this.transparent.unshift( renderItem );
  20470. } else {
  20471. this.opaque.unshift( renderItem );
  20472. }
  20473. }
  20474. /**
  20475. * Pushes render bundle group data into the render list.
  20476. *
  20477. * @param {Object} group - Bundle group data.
  20478. */
  20479. pushBundle( group ) {
  20480. this.bundles.push( group );
  20481. }
  20482. /**
  20483. * Pushes a light into the render list.
  20484. *
  20485. * @param {Light} light - The light.
  20486. */
  20487. pushLight( light ) {
  20488. this.lightsArray.push( light );
  20489. }
  20490. /**
  20491. * Sorts the internal render lists.
  20492. *
  20493. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  20494. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  20495. */
  20496. sort( customOpaqueSort, customTransparentSort ) {
  20497. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  20498. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  20499. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  20500. }
  20501. /**
  20502. * This method performs finalizing tasks right after the render lists
  20503. * have been generated.
  20504. */
  20505. finish() {
  20506. // update lights
  20507. this.lightsNode.setLights( this.lightsArray );
  20508. // Clear references from inactive renderItems in the list
  20509. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  20510. const renderItem = this.renderItems[ i ];
  20511. if ( renderItem.id === null ) break;
  20512. renderItem.id = null;
  20513. renderItem.object = null;
  20514. renderItem.geometry = null;
  20515. renderItem.material = null;
  20516. renderItem.groupOrder = null;
  20517. renderItem.renderOrder = null;
  20518. renderItem.z = null;
  20519. renderItem.group = null;
  20520. renderItem.clippingContext = null;
  20521. }
  20522. }
  20523. }
  20524. const _chainKeys$4 = [];
  20525. /**
  20526. * This renderer module manages the render lists which are unique
  20527. * per scene and camera combination.
  20528. *
  20529. * @private
  20530. */
  20531. class RenderLists {
  20532. /**
  20533. * Constructs a render lists management component.
  20534. *
  20535. * @param {Lighting} lighting - The lighting management component.
  20536. */
  20537. constructor( lighting ) {
  20538. /**
  20539. * The lighting management component.
  20540. *
  20541. * @type {Lighting}
  20542. */
  20543. this.lighting = lighting;
  20544. /**
  20545. * The internal chain map which holds the render lists.
  20546. *
  20547. * @type {ChainMap}
  20548. */
  20549. this.lists = new ChainMap();
  20550. }
  20551. /**
  20552. * Returns a render list for the given scene and camera.
  20553. *
  20554. * @param {Scene} scene - The scene.
  20555. * @param {Camera} camera - The camera.
  20556. * @return {RenderList} The render list.
  20557. */
  20558. get( scene, camera ) {
  20559. const lists = this.lists;
  20560. _chainKeys$4[ 0 ] = scene;
  20561. _chainKeys$4[ 1 ] = camera;
  20562. let list = lists.get( _chainKeys$4 );
  20563. if ( list === undefined ) {
  20564. list = new RenderList( this.lighting, scene, camera );
  20565. lists.set( _chainKeys$4, list );
  20566. }
  20567. _chainKeys$4.length = 0;
  20568. return list;
  20569. }
  20570. /**
  20571. * Frees all internal resources.
  20572. */
  20573. dispose() {
  20574. this.lists = new ChainMap();
  20575. }
  20576. }
  20577. let _id$7 = 0;
  20578. /**
  20579. * Any render or compute command is executed in a specific context that defines
  20580. * the state of the renderer and its backend. Typical examples for such context
  20581. * data are the current clear values or data from the active framebuffer. This
  20582. * module is used to represent these contexts as objects.
  20583. *
  20584. * @private
  20585. */
  20586. class RenderContext {
  20587. /**
  20588. * Constructs a new render context.
  20589. */
  20590. constructor() {
  20591. /**
  20592. * The context's ID.
  20593. *
  20594. * @type {number}
  20595. */
  20596. this.id = _id$7 ++;
  20597. /**
  20598. * Whether the current active framebuffer has a color attachment.
  20599. *
  20600. * @type {boolean}
  20601. * @default true
  20602. */
  20603. this.color = true;
  20604. /**
  20605. * Whether the color attachment should be cleared or not.
  20606. *
  20607. * @type {boolean}
  20608. * @default true
  20609. */
  20610. this.clearColor = true;
  20611. /**
  20612. * The clear color value.
  20613. *
  20614. * @type {Object}
  20615. * @default true
  20616. */
  20617. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  20618. /**
  20619. * Whether the current active framebuffer has a depth attachment.
  20620. *
  20621. * @type {boolean}
  20622. * @default true
  20623. */
  20624. this.depth = true;
  20625. /**
  20626. * Whether the depth attachment should be cleared or not.
  20627. *
  20628. * @type {boolean}
  20629. * @default true
  20630. */
  20631. this.clearDepth = true;
  20632. /**
  20633. * The clear depth value.
  20634. *
  20635. * @type {number}
  20636. * @default 1
  20637. */
  20638. this.clearDepthValue = 1;
  20639. /**
  20640. * Whether the current active framebuffer has a stencil attachment.
  20641. *
  20642. * @type {boolean}
  20643. * @default false
  20644. */
  20645. this.stencil = false;
  20646. /**
  20647. * Whether the stencil attachment should be cleared or not.
  20648. *
  20649. * @type {boolean}
  20650. * @default true
  20651. */
  20652. this.clearStencil = true;
  20653. /**
  20654. * The clear stencil value.
  20655. *
  20656. * @type {number}
  20657. * @default 1
  20658. */
  20659. this.clearStencilValue = 1;
  20660. /**
  20661. * By default the viewport encloses the entire framebuffer If a smaller
  20662. * viewport is manually defined, this property is to `true` by the renderer.
  20663. *
  20664. * @type {boolean}
  20665. * @default false
  20666. */
  20667. this.viewport = false;
  20668. /**
  20669. * The viewport value. This value is in physical pixels meaning it incorporates
  20670. * the renderer's pixel ratio. The viewport property of render targets or
  20671. * the renderer is in logical pixels.
  20672. *
  20673. * @type {Vector4}
  20674. */
  20675. this.viewportValue = new Vector4();
  20676. /**
  20677. * When the scissor test is active and scissor rectangle smaller than the
  20678. * framebuffers dimensions, this property is to `true` by the renderer.
  20679. *
  20680. * @type {boolean}
  20681. * @default false
  20682. */
  20683. this.scissor = false;
  20684. /**
  20685. * The scissor rectangle.
  20686. *
  20687. * @type {Vector4}
  20688. */
  20689. this.scissorValue = new Vector4();
  20690. /**
  20691. * The active render target.
  20692. *
  20693. * @type {?RenderTarget}
  20694. * @default null
  20695. */
  20696. this.renderTarget = null;
  20697. /**
  20698. * The textures of the active render target.
  20699. * `null` when no render target is set.
  20700. *
  20701. * @type {?Array<Texture>}
  20702. * @default null
  20703. */
  20704. this.textures = null;
  20705. /**
  20706. * The depth texture of the active render target.
  20707. * `null` when no render target is set.
  20708. *
  20709. * @type {?DepthTexture}
  20710. * @default null
  20711. */
  20712. this.depthTexture = null;
  20713. /**
  20714. * The active cube face.
  20715. *
  20716. * @type {number}
  20717. * @default 0
  20718. */
  20719. this.activeCubeFace = 0;
  20720. /**
  20721. * The active mipmap level.
  20722. *
  20723. * @type {number}
  20724. * @default 0
  20725. */
  20726. this.activeMipmapLevel = 0;
  20727. /**
  20728. * The number of MSAA samples. This value is always `1` when
  20729. * MSAA isn't used.
  20730. *
  20731. * @type {number}
  20732. * @default 1
  20733. */
  20734. this.sampleCount = 1;
  20735. /**
  20736. * The active render target's width in physical pixels.
  20737. *
  20738. * @type {number}
  20739. * @default 0
  20740. */
  20741. this.width = 0;
  20742. /**
  20743. * The active render target's height in physical pixels.
  20744. *
  20745. * @type {number}
  20746. * @default 0
  20747. */
  20748. this.height = 0;
  20749. /**
  20750. * The occlusion query count.
  20751. *
  20752. * @type {number}
  20753. * @default 0
  20754. */
  20755. this.occlusionQueryCount = 0;
  20756. /**
  20757. * The current clipping context.
  20758. *
  20759. * @type {?ClippingContext}
  20760. * @default null
  20761. */
  20762. this.clippingContext = null;
  20763. /**
  20764. * This flag can be used for type testing.
  20765. *
  20766. * @type {boolean}
  20767. * @readonly
  20768. * @default true
  20769. */
  20770. this.isRenderContext = true;
  20771. }
  20772. /**
  20773. * Returns the cache key of this render context.
  20774. *
  20775. * @return {number} The cache key.
  20776. */
  20777. getCacheKey() {
  20778. return getCacheKey( this );
  20779. }
  20780. }
  20781. /**
  20782. * Computes a cache key for the given render context. This key
  20783. * should identify the render target state so it is possible to
  20784. * configure the correct attachments in the respective backend.
  20785. *
  20786. * @param {RenderContext} renderContext - The render context.
  20787. * @return {number} The cache key.
  20788. */
  20789. function getCacheKey( renderContext ) {
  20790. const { textures, activeCubeFace } = renderContext;
  20791. const values = [ activeCubeFace ];
  20792. for ( const texture of textures ) {
  20793. values.push( texture.id );
  20794. }
  20795. return hashArray( values );
  20796. }
  20797. const _chainKeys$3 = [];
  20798. const _defaultScene = /*@__PURE__*/ new Scene();
  20799. const _defaultCamera = /*@__PURE__*/ new Camera();
  20800. /**
  20801. * This module manages the render contexts of the renderer.
  20802. *
  20803. * @private
  20804. */
  20805. class RenderContexts {
  20806. /**
  20807. * Constructs a new render context management component.
  20808. */
  20809. constructor() {
  20810. /**
  20811. * A dictionary that manages render contexts in chain maps
  20812. * for each attachment state.
  20813. *
  20814. * @type {Object<string,ChainMap>}
  20815. */
  20816. this.chainMaps = {};
  20817. }
  20818. /**
  20819. * Returns a render context for the given scene, camera and render target.
  20820. *
  20821. * @param {Scene} scene - The scene.
  20822. * @param {Camera} camera - The camera that is used to render the scene.
  20823. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  20824. * @return {RenderContext} The render context.
  20825. */
  20826. get( scene, camera, renderTarget = null ) {
  20827. _chainKeys$3[ 0 ] = scene;
  20828. _chainKeys$3[ 1 ] = camera;
  20829. let attachmentState;
  20830. if ( renderTarget === null ) {
  20831. attachmentState = 'default';
  20832. } else {
  20833. const format = renderTarget.texture.format;
  20834. const count = renderTarget.textures.length;
  20835. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  20836. }
  20837. const chainMap = this._getChainMap( attachmentState );
  20838. let renderState = chainMap.get( _chainKeys$3 );
  20839. if ( renderState === undefined ) {
  20840. renderState = new RenderContext();
  20841. chainMap.set( _chainKeys$3, renderState );
  20842. }
  20843. _chainKeys$3.length = 0;
  20844. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  20845. return renderState;
  20846. }
  20847. /**
  20848. * Returns a render context intended for clear operations.
  20849. *
  20850. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  20851. * @return {RenderContext} The render context.
  20852. */
  20853. getForClear( renderTarget = null ) {
  20854. return this.get( _defaultScene, _defaultCamera, renderTarget );
  20855. }
  20856. /**
  20857. * Returns a chain map for the given attachment state.
  20858. *
  20859. * @private
  20860. * @param {string} attachmentState - The attachment state.
  20861. * @return {ChainMap} The chain map.
  20862. */
  20863. _getChainMap( attachmentState ) {
  20864. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  20865. }
  20866. /**
  20867. * Frees internal resources.
  20868. */
  20869. dispose() {
  20870. this.chainMaps = {};
  20871. }
  20872. }
  20873. const _size$3 = /*@__PURE__*/ new Vector3();
  20874. /**
  20875. * This module manages the textures of the renderer.
  20876. *
  20877. * @private
  20878. * @augments DataMap
  20879. */
  20880. class Textures extends DataMap {
  20881. /**
  20882. * Constructs a new texture management component.
  20883. *
  20884. * @param {Renderer} renderer - The renderer.
  20885. * @param {Backend} backend - The renderer's backend.
  20886. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20887. */
  20888. constructor( renderer, backend, info ) {
  20889. super();
  20890. /**
  20891. * The renderer.
  20892. *
  20893. * @type {Renderer}
  20894. */
  20895. this.renderer = renderer;
  20896. /**
  20897. * The backend.
  20898. *
  20899. * @type {Backend}
  20900. */
  20901. this.backend = backend;
  20902. /**
  20903. * Renderer component for managing metrics and monitoring data.
  20904. *
  20905. * @type {Info}
  20906. */
  20907. this.info = info;
  20908. }
  20909. /**
  20910. * Updates the given render target. Based on the given render target configuration,
  20911. * it updates the texture states representing the attachments of the framebuffer.
  20912. *
  20913. * @param {RenderTarget} renderTarget - The render target to update.
  20914. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  20915. */
  20916. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  20917. const renderTargetData = this.get( renderTarget );
  20918. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  20919. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  20920. const textures = renderTarget.textures;
  20921. const size = this.getSize( textures[ 0 ] );
  20922. const mipWidth = size.width >> activeMipmapLevel;
  20923. const mipHeight = size.height >> activeMipmapLevel;
  20924. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  20925. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  20926. let textureNeedsUpdate = false;
  20927. if ( depthTexture === undefined && useDepthTexture ) {
  20928. depthTexture = new DepthTexture();
  20929. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  20930. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  20931. depthTexture.image.width = mipWidth;
  20932. depthTexture.image.height = mipHeight;
  20933. depthTexture.image.depth = size.depth;
  20934. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  20935. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  20936. }
  20937. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  20938. textureNeedsUpdate = true;
  20939. if ( depthTexture ) {
  20940. depthTexture.needsUpdate = true;
  20941. depthTexture.image.width = mipWidth;
  20942. depthTexture.image.height = mipHeight;
  20943. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  20944. }
  20945. }
  20946. renderTargetData.width = size.width;
  20947. renderTargetData.height = size.height;
  20948. renderTargetData.textures = textures;
  20949. renderTargetData.depthTexture = depthTexture || null;
  20950. renderTargetData.depth = renderTarget.depthBuffer;
  20951. renderTargetData.stencil = renderTarget.stencilBuffer;
  20952. renderTargetData.renderTarget = renderTarget;
  20953. if ( renderTargetData.sampleCount !== sampleCount ) {
  20954. textureNeedsUpdate = true;
  20955. if ( depthTexture ) {
  20956. depthTexture.needsUpdate = true;
  20957. }
  20958. renderTargetData.sampleCount = sampleCount;
  20959. }
  20960. //
  20961. const options = { sampleCount };
  20962. // XR render targets require no texture updates
  20963. if ( renderTarget.isXRRenderTarget !== true ) {
  20964. for ( let i = 0; i < textures.length; i ++ ) {
  20965. const texture = textures[ i ];
  20966. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  20967. this.updateTexture( texture, options );
  20968. }
  20969. if ( depthTexture ) {
  20970. this.updateTexture( depthTexture, options );
  20971. }
  20972. }
  20973. // dispose handler
  20974. if ( renderTargetData.initialized !== true ) {
  20975. renderTargetData.initialized = true;
  20976. // dispose
  20977. const onDispose = () => {
  20978. renderTarget.removeEventListener( 'dispose', onDispose );
  20979. for ( let i = 0; i < textures.length; i ++ ) {
  20980. this._destroyTexture( textures[ i ] );
  20981. }
  20982. if ( depthTexture ) {
  20983. this._destroyTexture( depthTexture );
  20984. }
  20985. this.delete( renderTarget );
  20986. };
  20987. renderTarget.addEventListener( 'dispose', onDispose );
  20988. }
  20989. }
  20990. /**
  20991. * Updates the given texture. Depending on the texture state, this method
  20992. * triggers the upload of texture data to the GPU memory. If the texture data are
  20993. * not yet ready for the upload, it uses default texture data for as a placeholder.
  20994. *
  20995. * @param {Texture} texture - The texture to update.
  20996. * @param {Object} [options={}] - The options.
  20997. */
  20998. updateTexture( texture, options = {} ) {
  20999. const textureData = this.get( texture );
  21000. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  21001. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  21002. const backend = this.backend;
  21003. if ( isRenderTarget && textureData.initialized === true ) {
  21004. // it's an update
  21005. backend.destroySampler( texture );
  21006. backend.destroyTexture( texture );
  21007. }
  21008. //
  21009. if ( texture.isFramebufferTexture ) {
  21010. const renderTarget = this.renderer.getRenderTarget();
  21011. if ( renderTarget ) {
  21012. texture.type = renderTarget.texture.type;
  21013. } else {
  21014. texture.type = UnsignedByteType;
  21015. }
  21016. }
  21017. //
  21018. const { width, height, depth } = this.getSize( texture );
  21019. options.width = width;
  21020. options.height = height;
  21021. options.depth = depth;
  21022. options.needsMipmaps = this.needsMipmaps( texture );
  21023. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  21024. //
  21025. if ( isRenderTarget || texture.isStorageTexture === true ) {
  21026. backend.createSampler( texture );
  21027. backend.createTexture( texture, options );
  21028. textureData.generation = texture.version;
  21029. } else {
  21030. const needsCreate = textureData.initialized !== true;
  21031. if ( needsCreate ) backend.createSampler( texture );
  21032. if ( texture.version > 0 ) {
  21033. const image = texture.image;
  21034. if ( image === undefined ) {
  21035. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  21036. } else if ( image.complete === false ) {
  21037. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  21038. } else {
  21039. if ( texture.images ) {
  21040. const images = [];
  21041. for ( const image of texture.images ) {
  21042. images.push( image );
  21043. }
  21044. options.images = images;
  21045. } else {
  21046. options.image = image;
  21047. }
  21048. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  21049. backend.createTexture( texture, options );
  21050. textureData.isDefaultTexture = false;
  21051. textureData.generation = texture.version;
  21052. }
  21053. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  21054. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  21055. }
  21056. } else {
  21057. // async update
  21058. backend.createDefaultTexture( texture );
  21059. textureData.isDefaultTexture = true;
  21060. textureData.generation = texture.version;
  21061. }
  21062. }
  21063. // dispose handler
  21064. if ( textureData.initialized !== true ) {
  21065. textureData.initialized = true;
  21066. textureData.generation = texture.version;
  21067. //
  21068. this.info.memory.textures ++;
  21069. // dispose
  21070. const onDispose = () => {
  21071. texture.removeEventListener( 'dispose', onDispose );
  21072. this._destroyTexture( texture );
  21073. };
  21074. texture.addEventListener( 'dispose', onDispose );
  21075. }
  21076. //
  21077. textureData.version = texture.version;
  21078. }
  21079. /**
  21080. * Computes the size of the given texture and writes the result
  21081. * into the target vector. This vector is also returned by the
  21082. * method.
  21083. *
  21084. * If no texture data are available for the compute yet, the method
  21085. * returns default size values.
  21086. *
  21087. * @param {Texture} texture - The texture to compute the size for.
  21088. * @param {Vector3} target - The target vector.
  21089. * @return {Vector3} The target vector.
  21090. */
  21091. getSize( texture, target = _size$3 ) {
  21092. let image = texture.images ? texture.images[ 0 ] : texture.image;
  21093. if ( image ) {
  21094. if ( image.image !== undefined ) image = image.image;
  21095. target.width = image.width || 1;
  21096. target.height = image.height || 1;
  21097. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  21098. } else {
  21099. target.width = target.height = target.depth = 1;
  21100. }
  21101. return target;
  21102. }
  21103. /**
  21104. * Computes the number of mipmap levels for the given texture.
  21105. *
  21106. * @param {Texture} texture - The texture.
  21107. * @param {number} width - The texture's width.
  21108. * @param {number} height - The texture's height.
  21109. * @return {number} The number of mipmap levels.
  21110. */
  21111. getMipLevels( texture, width, height ) {
  21112. let mipLevelCount;
  21113. if ( texture.isCompressedTexture ) {
  21114. if ( texture.mipmaps ) {
  21115. mipLevelCount = texture.mipmaps.length;
  21116. } else {
  21117. mipLevelCount = 1;
  21118. }
  21119. } else {
  21120. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  21121. }
  21122. return mipLevelCount;
  21123. }
  21124. /**
  21125. * Returns `true` if the given texture requires mipmaps.
  21126. *
  21127. * @param {Texture} texture - The texture.
  21128. * @return {boolean} Whether mipmaps are required or not.
  21129. */
  21130. needsMipmaps( texture ) {
  21131. return texture.isCompressedTexture === true || texture.generateMipmaps;
  21132. }
  21133. /**
  21134. * Frees internal resource when the given texture isn't
  21135. * required anymore.
  21136. *
  21137. * @param {Texture} texture - The texture to destroy.
  21138. */
  21139. _destroyTexture( texture ) {
  21140. if ( this.has( texture ) === true ) {
  21141. this.backend.destroySampler( texture );
  21142. this.backend.destroyTexture( texture );
  21143. this.delete( texture );
  21144. this.info.memory.textures --;
  21145. }
  21146. }
  21147. }
  21148. /**
  21149. * A four-component version of {@link Color} which is internally
  21150. * used by the renderer to represents clear color with alpha as
  21151. * one object.
  21152. *
  21153. * @private
  21154. * @augments Color
  21155. */
  21156. class Color4 extends Color {
  21157. /**
  21158. * Constructs a new four-component color.
  21159. * You can also pass a single THREE.Color, hex or
  21160. * string argument to this constructor.
  21161. *
  21162. * @param {number|string} [r=1] - The red value.
  21163. * @param {number} [g=1] - The green value.
  21164. * @param {number} [b=1] - The blue value.
  21165. * @param {number} [a=1] - The alpha value.
  21166. */
  21167. constructor( r, g, b, a = 1 ) {
  21168. super( r, g, b );
  21169. this.a = a;
  21170. }
  21171. /**
  21172. * Overwrites the default to honor alpha.
  21173. * You can also pass a single THREE.Color, hex or
  21174. * string argument to this method.
  21175. *
  21176. * @param {number|string|Color} r - The red value.
  21177. * @param {number} g - The green value.
  21178. * @param {number} b - The blue value.
  21179. * @param {number} [a=1] - The alpha value.
  21180. * @return {Color4} A reference to this object.
  21181. */
  21182. set( r, g, b, a = 1 ) {
  21183. this.a = a;
  21184. return super.set( r, g, b );
  21185. }
  21186. /**
  21187. * Overwrites the default to honor alpha.
  21188. *
  21189. * @param {Color4} color - The color to copy.
  21190. * @return {Color4} A reference to this object.
  21191. */
  21192. copy( color ) {
  21193. if ( color.a !== undefined ) this.a = color.a;
  21194. return super.copy( color );
  21195. }
  21196. /**
  21197. * Overwrites the default to honor alpha.
  21198. *
  21199. * @return {Color4} The cloned color.
  21200. */
  21201. clone() {
  21202. return new this.constructor( this.r, this.g, this.b, this.a );
  21203. }
  21204. }
  21205. /**
  21206. * Special version of {@link PropertyNode} which is used for parameters.
  21207. *
  21208. * @augments PropertyNode
  21209. */
  21210. class ParameterNode extends PropertyNode {
  21211. static get type() {
  21212. return 'ParameterNode';
  21213. }
  21214. /**
  21215. * Constructs a new parameter node.
  21216. *
  21217. * @param {string} nodeType - The type of the node.
  21218. * @param {?string} [name=null] - The name of the parameter in the shader.
  21219. */
  21220. constructor( nodeType, name = null ) {
  21221. super( nodeType, name );
  21222. /**
  21223. * This flag can be used for type testing.
  21224. *
  21225. * @type {boolean}
  21226. * @readonly
  21227. * @default true
  21228. */
  21229. this.isParameterNode = true;
  21230. }
  21231. getHash() {
  21232. return this.uuid;
  21233. }
  21234. generate() {
  21235. return this.name;
  21236. }
  21237. }
  21238. /**
  21239. * TSL function for creating a parameter node.
  21240. *
  21241. * @tsl
  21242. * @function
  21243. * @param {string} type - The type of the node.
  21244. * @param {?string} name - The name of the parameter in the shader.
  21245. * @returns {ParameterNode}
  21246. */
  21247. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  21248. /**
  21249. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  21250. * They are usually needed in cases like `If`, `Else`.
  21251. *
  21252. * @augments Node
  21253. */
  21254. class StackNode extends Node {
  21255. static get type() {
  21256. return 'StackNode';
  21257. }
  21258. /**
  21259. * Constructs a new stack node.
  21260. *
  21261. * @param {?StackNode} [parent=null] - The parent stack node.
  21262. */
  21263. constructor( parent = null ) {
  21264. super();
  21265. /**
  21266. * List of nodes.
  21267. *
  21268. * @type {Array<Node>}
  21269. */
  21270. this.nodes = [];
  21271. /**
  21272. * The output node.
  21273. *
  21274. * @type {?Node}
  21275. * @default null
  21276. */
  21277. this.outputNode = null;
  21278. /**
  21279. * The parent stack node.
  21280. *
  21281. * @type {?StackNode}
  21282. * @default null
  21283. */
  21284. this.parent = parent;
  21285. /**
  21286. * The current conditional node.
  21287. *
  21288. * @private
  21289. * @type {ConditionalNode}
  21290. * @default null
  21291. */
  21292. this._currentCond = null;
  21293. /**
  21294. * The expression node. Only
  21295. * relevant for Switch/Case.
  21296. *
  21297. * @private
  21298. * @type {Node}
  21299. * @default null
  21300. */
  21301. this._expressionNode = null;
  21302. /**
  21303. * This flag can be used for type testing.
  21304. *
  21305. * @type {boolean}
  21306. * @readonly
  21307. * @default true
  21308. */
  21309. this.isStackNode = true;
  21310. }
  21311. getNodeType( builder ) {
  21312. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  21313. }
  21314. getMemberType( builder, name ) {
  21315. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  21316. }
  21317. /**
  21318. * Adds a node to this stack.
  21319. *
  21320. * @param {Node} node - The node to add.
  21321. * @return {StackNode} A reference to this stack node.
  21322. */
  21323. add( node ) {
  21324. this.nodes.push( node );
  21325. return this;
  21326. }
  21327. /**
  21328. * Represent an `if` statement in TSL.
  21329. *
  21330. * @param {Node} boolNode - Represents the condition.
  21331. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21332. * @return {StackNode} A reference to this stack node.
  21333. */
  21334. If( boolNode, method ) {
  21335. const methodNode = new ShaderNode( method );
  21336. this._currentCond = select( boolNode, methodNode );
  21337. return this.add( this._currentCond );
  21338. }
  21339. /**
  21340. * Represent an `elseif` statement in TSL.
  21341. *
  21342. * @param {Node} boolNode - Represents the condition.
  21343. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21344. * @return {StackNode} A reference to this stack node.
  21345. */
  21346. ElseIf( boolNode, method ) {
  21347. const methodNode = new ShaderNode( method );
  21348. const ifNode = select( boolNode, methodNode );
  21349. this._currentCond.elseNode = ifNode;
  21350. this._currentCond = ifNode;
  21351. return this;
  21352. }
  21353. /**
  21354. * Represent an `else` statement in TSL.
  21355. *
  21356. * @param {Function} method - TSL code which is executed in the `else` case.
  21357. * @return {StackNode} A reference to this stack node.
  21358. */
  21359. Else( method ) {
  21360. this._currentCond.elseNode = new ShaderNode( method );
  21361. return this;
  21362. }
  21363. /**
  21364. * Represents a `switch` statement in TSL.
  21365. *
  21366. * @param {any} expression - Represents the expression.
  21367. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21368. * @return {StackNode} A reference to this stack node.
  21369. */
  21370. Switch( expression ) {
  21371. this._expressionNode = nodeObject( expression );
  21372. return this;
  21373. }
  21374. /**
  21375. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  21376. * The last parameter must be the callback method that should be executed in the `true` case.
  21377. *
  21378. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  21379. * @return {StackNode} A reference to this stack node.
  21380. */
  21381. Case( ...params ) {
  21382. const caseNodes = [];
  21383. // extract case nodes from the parameter list
  21384. if ( params.length >= 2 ) {
  21385. for ( let i = 0; i < params.length - 1; i ++ ) {
  21386. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  21387. }
  21388. } else {
  21389. throw new Error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  21390. }
  21391. // extract method
  21392. const method = params[ params.length - 1 ];
  21393. const methodNode = new ShaderNode( method );
  21394. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  21395. let caseNode = caseNodes[ 0 ];
  21396. for ( let i = 1; i < caseNodes.length; i ++ ) {
  21397. caseNode = caseNode.or( caseNodes[ i ] );
  21398. }
  21399. // build condition
  21400. const condNode = select( caseNode, methodNode );
  21401. if ( this._currentCond === null ) {
  21402. this._currentCond = condNode;
  21403. return this.add( this._currentCond );
  21404. } else {
  21405. this._currentCond.elseNode = condNode;
  21406. this._currentCond = condNode;
  21407. return this;
  21408. }
  21409. }
  21410. /**
  21411. * Represents the default code block of a Switch/Case statement.
  21412. *
  21413. * @param {Function} method - TSL code which is executed in the `else` case.
  21414. * @return {StackNode} A reference to this stack node.
  21415. */
  21416. Default( method ) {
  21417. this.Else( method );
  21418. return this;
  21419. }
  21420. build( builder, ...params ) {
  21421. const previousStack = getCurrentStack();
  21422. setCurrentStack( this );
  21423. const buildStage = builder.buildStage;
  21424. for ( const node of this.nodes ) {
  21425. if ( buildStage === 'setup' ) {
  21426. node.build( builder );
  21427. } else if ( buildStage === 'analyze' ) {
  21428. node.build( builder, this );
  21429. } else if ( buildStage === 'generate' ) {
  21430. const stages = builder.getDataFromNode( node, 'any' ).stages;
  21431. const parents = stages && stages[ builder.shaderStage ];
  21432. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  21433. continue; // skip var nodes that are only used in .toVarying()
  21434. }
  21435. node.build( builder, 'void' );
  21436. }
  21437. }
  21438. setCurrentStack( previousStack );
  21439. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  21440. }
  21441. // Deprecated
  21442. /**
  21443. * @function
  21444. * @deprecated since r168. Use {@link StackNode#Else} instead.
  21445. *
  21446. * @param {...any} params
  21447. * @returns {StackNode}
  21448. */
  21449. else( ...params ) { // @deprecated, r168
  21450. console.warn( 'THREE.TSL: .else() has been renamed to .Else().' );
  21451. return this.Else( ...params );
  21452. }
  21453. /**
  21454. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  21455. *
  21456. * @param {...any} params
  21457. * @returns {StackNode}
  21458. */
  21459. elseif( ...params ) { // @deprecated, r168
  21460. console.warn( 'THREE.TSL: .elseif() has been renamed to .ElseIf().' );
  21461. return this.ElseIf( ...params );
  21462. }
  21463. }
  21464. /**
  21465. * TSL function for creating a stack node.
  21466. *
  21467. * @tsl
  21468. * @function
  21469. * @param {?StackNode} [parent=null] - The parent stack node.
  21470. * @returns {StackNode}
  21471. */
  21472. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  21473. /**
  21474. * Generates a layout for struct members.
  21475. * This function takes an object representing struct members and returns an array of member layouts.
  21476. * Each member layout includes the member's name, type, and whether it is atomic.
  21477. *
  21478. * @param {Object.<string, string|Object>} members - An object where keys are member names and values are either types (as strings) or objects with type and atomic properties.
  21479. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  21480. */
  21481. function getMembersLayout( members ) {
  21482. return Object.entries( members ).map( ( [ name, value ] ) => {
  21483. if ( typeof value === 'string' ) {
  21484. return { name, type: value, atomic: false };
  21485. }
  21486. return { name, type: value.type, atomic: value.atomic || false };
  21487. } );
  21488. }
  21489. /**
  21490. * Represents a struct type node in the node-based system.
  21491. * This class is used to define and manage the layout and types of struct members.
  21492. * It extends the base Node class and provides methods to get the length of the struct,
  21493. * retrieve member types, and generate the struct type for a builder.
  21494. *
  21495. * @augments Node
  21496. */
  21497. class StructTypeNode extends Node {
  21498. static get type() {
  21499. return 'StructTypeNode';
  21500. }
  21501. /**
  21502. * Creates an instance of StructTypeNode.
  21503. *
  21504. * @param {Object} membersLayout - The layout of the members for the struct.
  21505. * @param {?string} [name=null] - The optional name of the struct.
  21506. */
  21507. constructor( membersLayout, name = null ) {
  21508. super( 'struct' );
  21509. /**
  21510. * The layout of the members for the struct
  21511. *
  21512. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  21513. */
  21514. this.membersLayout = getMembersLayout( membersLayout );
  21515. /**
  21516. * The name of the struct.
  21517. *
  21518. * @type {?string}
  21519. * @default null
  21520. */
  21521. this.name = name;
  21522. /**
  21523. * This flag can be used for type testing.
  21524. *
  21525. * @type {boolean}
  21526. * @readonly
  21527. * @default true
  21528. */
  21529. this.isStructLayoutNode = true;
  21530. }
  21531. /**
  21532. * Returns the length of the struct.
  21533. * The length is calculated by summing the lengths of the struct's members.
  21534. *
  21535. * @returns {number} The length of the struct.
  21536. */
  21537. getLength() {
  21538. const GPU_CHUNK_BYTES = 8;
  21539. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  21540. let offset = 0; // global buffer offset in bytes
  21541. for ( const member of this.membersLayout ) {
  21542. const type = member.type;
  21543. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  21544. const boundary = getByteBoundaryFromType( type );
  21545. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  21546. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  21547. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  21548. offset += chunkPadding;
  21549. // Check for chunk overflow
  21550. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  21551. // Add padding to the end of the chunk
  21552. offset += ( GPU_CHUNK_BYTES - chunkStart );
  21553. }
  21554. offset += itemSize;
  21555. }
  21556. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  21557. }
  21558. getMemberType( builder, name ) {
  21559. const member = this.membersLayout.find( m => m.name === name );
  21560. return member ? member.type : 'void';
  21561. }
  21562. getNodeType( builder ) {
  21563. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  21564. return structType.name;
  21565. }
  21566. setup( builder ) {
  21567. builder.addInclude( this );
  21568. }
  21569. generate( builder ) {
  21570. return this.getNodeType( builder );
  21571. }
  21572. }
  21573. /**
  21574. * StructNode allows to create custom structures with multiple members.
  21575. * This can also be used to define structures in attribute and uniform data.
  21576. *
  21577. * ```js
  21578. * // Define a custom struct
  21579. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  21580. *
  21581. * // Create a new instance of the struct
  21582. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  21583. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  21584. *
  21585. * // Access the struct members
  21586. * const min = bb.get( 'min' );
  21587. *
  21588. * // Assign a new value to a member
  21589. * min.assign( vec3() );
  21590. * ```
  21591. * @augments Node
  21592. */
  21593. class StructNode extends Node {
  21594. static get type() {
  21595. return 'StructNode';
  21596. }
  21597. constructor( structLayoutNode, values ) {
  21598. super( 'vec3' );
  21599. this.structLayoutNode = structLayoutNode;
  21600. this.values = values;
  21601. this.isStructNode = true;
  21602. }
  21603. getNodeType( builder ) {
  21604. return this.structLayoutNode.getNodeType( builder );
  21605. }
  21606. getMemberType( builder, name ) {
  21607. return this.structLayoutNode.getMemberType( builder, name );
  21608. }
  21609. generate( builder ) {
  21610. const nodeVar = builder.getVarFromNode( this );
  21611. const structType = nodeVar.type;
  21612. const propertyName = builder.getPropertyName( nodeVar );
  21613. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  21614. return nodeVar.name;
  21615. }
  21616. }
  21617. /**
  21618. * TSL function for creating a struct node.
  21619. *
  21620. * @tsl
  21621. * @function
  21622. * @param {Object} membersLayout - The layout of the struct members.
  21623. * @param {?string} [name=null] - The name of the struct.
  21624. * @returns {Function} The struct function.
  21625. */
  21626. const struct = ( membersLayout, name = null ) => {
  21627. const structLayout = new StructTypeNode( membersLayout, name );
  21628. const struct = ( ...params ) => {
  21629. let values = null;
  21630. if ( params.length > 0 ) {
  21631. if ( params[ 0 ].isNode ) {
  21632. values = {};
  21633. const names = Object.keys( membersLayout );
  21634. for ( let i = 0; i < params.length; i ++ ) {
  21635. values[ names[ i ] ] = params[ i ];
  21636. }
  21637. } else {
  21638. values = params[ 0 ];
  21639. }
  21640. }
  21641. return nodeObject( new StructNode( structLayout, values ) );
  21642. };
  21643. struct.layout = structLayout;
  21644. struct.isStruct = true;
  21645. return struct;
  21646. };
  21647. /**
  21648. * This node can be used to define multiple outputs in a shader programs.
  21649. *
  21650. * @augments Node
  21651. */
  21652. class OutputStructNode extends Node {
  21653. static get type() {
  21654. return 'OutputStructNode';
  21655. }
  21656. /**
  21657. * Constructs a new output struct node. The constructor can be invoked with an
  21658. * arbitrary number of nodes representing the members.
  21659. *
  21660. * @param {...Node} members - A parameter list of nodes.
  21661. */
  21662. constructor( ...members ) {
  21663. super();
  21664. /**
  21665. * An array of nodes which defines the output.
  21666. *
  21667. * @type {Array<Node>}
  21668. */
  21669. this.members = members;
  21670. /**
  21671. * This flag can be used for type testing.
  21672. *
  21673. * @type {boolean}
  21674. * @readonly
  21675. * @default true
  21676. */
  21677. this.isOutputStructNode = true;
  21678. }
  21679. getNodeType( builder ) {
  21680. const properties = builder.getNodeProperties( this );
  21681. if ( properties.membersLayout === undefined ) {
  21682. const members = this.members;
  21683. const membersLayout = [];
  21684. for ( let i = 0; i < members.length; i ++ ) {
  21685. const name = 'm' + i;
  21686. const type = members[ i ].getNodeType( builder );
  21687. membersLayout.push( { name, type, index: i } );
  21688. }
  21689. properties.membersLayout = membersLayout;
  21690. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  21691. }
  21692. return properties.structType.name;
  21693. }
  21694. generate( builder ) {
  21695. const propertyName = builder.getOutputStructName();
  21696. const members = this.members;
  21697. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  21698. for ( let i = 0; i < members.length; i ++ ) {
  21699. const snippet = members[ i ].build( builder );
  21700. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  21701. }
  21702. return propertyName;
  21703. }
  21704. }
  21705. /**
  21706. * TSL function for creating an output struct node.
  21707. *
  21708. * @tsl
  21709. * @function
  21710. * @param {...Node} members - A parameter list of nodes.
  21711. * @returns {OutputStructNode}
  21712. */
  21713. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  21714. /**
  21715. * Returns the MRT texture index for the given name.
  21716. *
  21717. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  21718. * @param {string} name - The name of the MRT texture which index is requested.
  21719. * @return {number} The texture index.
  21720. */
  21721. function getTextureIndex( textures, name ) {
  21722. for ( let i = 0; i < textures.length; i ++ ) {
  21723. if ( textures[ i ].name === name ) {
  21724. return i;
  21725. }
  21726. }
  21727. return -1;
  21728. }
  21729. /**
  21730. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  21731. * post-processing is shown below:
  21732. * ```js
  21733. * const mrtNode = mrt( {
  21734. * output: output,
  21735. * normal: normalView
  21736. * } ) );
  21737. * ```
  21738. * The MRT output is defined as a dictionary.
  21739. *
  21740. * @augments OutputStructNode
  21741. */
  21742. class MRTNode extends OutputStructNode {
  21743. static get type() {
  21744. return 'MRTNode';
  21745. }
  21746. /**
  21747. * Constructs a new output struct node.
  21748. *
  21749. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  21750. */
  21751. constructor( outputNodes ) {
  21752. super();
  21753. /**
  21754. * A dictionary representing the MRT outputs. The key
  21755. * is the name of the output, the value the node which produces
  21756. * the output result.
  21757. *
  21758. * @type {Object<string, Node>}
  21759. */
  21760. this.outputNodes = outputNodes;
  21761. /**
  21762. * This flag can be used for type testing.
  21763. *
  21764. * @type {boolean}
  21765. * @readonly
  21766. * @default true
  21767. */
  21768. this.isMRTNode = true;
  21769. }
  21770. /**
  21771. * Returns `true` if the MRT node has an output with the given name.
  21772. *
  21773. * @param {string} name - The name of the output.
  21774. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  21775. */
  21776. has( name ) {
  21777. return this.outputNodes[ name ] !== undefined;
  21778. }
  21779. /**
  21780. * Returns the output node for the given name.
  21781. *
  21782. * @param {string} name - The name of the output.
  21783. * @return {Node} The output node.
  21784. */
  21785. get( name ) {
  21786. return this.outputNodes[ name ];
  21787. }
  21788. /**
  21789. * Merges the outputs of the given MRT node with the outputs of this node.
  21790. *
  21791. * @param {MRTNode} mrtNode - The MRT to merge.
  21792. * @return {MRTNode} A new MRT node with merged outputs..
  21793. */
  21794. merge( mrtNode ) {
  21795. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  21796. return mrt( outputs );
  21797. }
  21798. setup( builder ) {
  21799. const outputNodes = this.outputNodes;
  21800. const mrt = builder.renderer.getRenderTarget();
  21801. const members = [];
  21802. const textures = mrt.textures;
  21803. for ( const name in outputNodes ) {
  21804. const index = getTextureIndex( textures, name );
  21805. members[ index ] = vec4( outputNodes[ name ] );
  21806. }
  21807. this.members = members;
  21808. return super.setup( builder );
  21809. }
  21810. }
  21811. /**
  21812. * TSL function for creating a MRT node.
  21813. *
  21814. * @tsl
  21815. * @function
  21816. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  21817. * @returns {MRTNode}
  21818. */
  21819. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  21820. /**
  21821. * Generates a hash value in the range `[0, 1]` from the given seed.
  21822. *
  21823. * @tsl
  21824. * @function
  21825. * @param {Node<float>} seed - The seed.
  21826. * @return {Node<float>} The hash value.
  21827. */
  21828. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  21829. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  21830. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  21831. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  21832. const result = word.shiftRight( 22 ).bitXor( word );
  21833. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  21834. } );
  21835. /**
  21836. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  21837. * The corners are mapped to `0` and the center to `1`.
  21838. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21839. *
  21840. * @tsl
  21841. * @function
  21842. * @param {Node<float>} x - The value to remap.
  21843. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  21844. * @return {Node<float>} The remapped value.
  21845. */
  21846. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  21847. /**
  21848. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  21849. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  21850. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21851. *
  21852. * @tsl
  21853. * @function
  21854. * @param {Node<float>} x - The value to remap.
  21855. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  21856. * @return {Node<float>} The remapped value.
  21857. */
  21858. const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) );
  21859. /**
  21860. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  21861. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  21862. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21863. *
  21864. * @tsl
  21865. * @function
  21866. * @param {Node<float>} x - The value to remap.
  21867. * @param {Node<float>} a - First control parameter.
  21868. * @param {Node<float>} b - Second control parameter.
  21869. * @return {Node<float>} The remapped value.
  21870. */
  21871. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  21872. /**
  21873. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  21874. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21875. *
  21876. * @tsl
  21877. * @function
  21878. * @param {Node<float>} x - The value to compute the sin for.
  21879. * @param {Node<float>} k - Controls the amount of bounces.
  21880. * @return {Node<float>} The result value.
  21881. */
  21882. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  21883. // https://github.com/cabbibo/glsl-tri-noise-3d
  21884. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  21885. return x.fract().sub( .5 ).abs();
  21886. } ).setLayout( {
  21887. name: 'tri',
  21888. type: 'float',
  21889. inputs: [
  21890. { name: 'x', type: 'float' }
  21891. ]
  21892. } );
  21893. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  21894. return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) );
  21895. } ).setLayout( {
  21896. name: 'tri3',
  21897. type: 'vec3',
  21898. inputs: [
  21899. { name: 'p', type: 'vec3' }
  21900. ]
  21901. } );
  21902. /**
  21903. * Generates a noise value from the given position, speed and time parameters.
  21904. *
  21905. * @tsl
  21906. * @function
  21907. * @param {Node<vec3>} position - The position.
  21908. * @param {Node<float>} speed - The speed.
  21909. * @param {Node<float>} time - The time.
  21910. * @return {Node<float>} The generated noise.
  21911. */
  21912. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  21913. const p = vec3( position ).toVar();
  21914. const z = float( 1.4 ).toVar();
  21915. const rz = float( 0.0 ).toVar();
  21916. const bp = vec3( p ).toVar();
  21917. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  21918. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  21919. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  21920. bp.mulAssign( 1.8 );
  21921. z.mulAssign( 1.5 );
  21922. p.mulAssign( 1.2 );
  21923. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  21924. rz.addAssign( t.div( z ) );
  21925. bp.addAssign( 0.14 );
  21926. } );
  21927. return rz;
  21928. } ).setLayout( {
  21929. name: 'triNoise3D',
  21930. type: 'float',
  21931. inputs: [
  21932. { name: 'position', type: 'vec3' },
  21933. { name: 'speed', type: 'float' },
  21934. { name: 'time', type: 'float' }
  21935. ]
  21936. } );
  21937. /**
  21938. * This class allows to define multiple overloaded versions
  21939. * of the same function. Depending on the parameters of the function
  21940. * call, the node picks the best-fit overloaded version.
  21941. *
  21942. * @augments Node
  21943. */
  21944. class FunctionOverloadingNode extends Node {
  21945. static get type() {
  21946. return 'FunctionOverloadingNode';
  21947. }
  21948. /**
  21949. * Constructs a new function overloading node.
  21950. *
  21951. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  21952. * @param {...Node} parametersNodes - A list of parameter nodes.
  21953. */
  21954. constructor( functionNodes = [], ...parametersNodes ) {
  21955. super();
  21956. /**
  21957. * Array of `Fn` function definitions.
  21958. *
  21959. * @type {Array<Function>}
  21960. */
  21961. this.functionNodes = functionNodes;
  21962. /**
  21963. * A list of parameter nodes.
  21964. *
  21965. * @type {Array<Node>}
  21966. */
  21967. this.parametersNodes = parametersNodes;
  21968. /**
  21969. * The selected overloaded function call.
  21970. *
  21971. * @private
  21972. * @type {ShaderCallNodeInternal}
  21973. */
  21974. this._candidateFnCall = null;
  21975. /**
  21976. * This node is marked as global.
  21977. *
  21978. * @type {boolean}
  21979. * @default true
  21980. */
  21981. this.global = true;
  21982. }
  21983. /**
  21984. * This method is overwritten since the node type is inferred from
  21985. * the function's return type.
  21986. *
  21987. * @param {NodeBuilder} builder - The current node builder.
  21988. * @return {string} The node type.
  21989. */
  21990. getNodeType() {
  21991. return this.functionNodes[ 0 ].shaderNode.layout.type;
  21992. }
  21993. setup( builder ) {
  21994. const params = this.parametersNodes;
  21995. let candidateFnCall = this._candidateFnCall;
  21996. if ( candidateFnCall === null ) {
  21997. let candidateFn = null;
  21998. let candidateScore = -1;
  21999. for ( const functionNode of this.functionNodes ) {
  22000. const shaderNode = functionNode.shaderNode;
  22001. const layout = shaderNode.layout;
  22002. if ( layout === null ) {
  22003. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  22004. }
  22005. const inputs = layout.inputs;
  22006. if ( params.length === inputs.length ) {
  22007. let score = 0;
  22008. for ( let i = 0; i < params.length; i ++ ) {
  22009. const param = params[ i ];
  22010. const input = inputs[ i ];
  22011. if ( param.getNodeType( builder ) === input.type ) {
  22012. score ++;
  22013. } else {
  22014. score = 0;
  22015. }
  22016. }
  22017. if ( score > candidateScore ) {
  22018. candidateFn = functionNode;
  22019. candidateScore = score;
  22020. }
  22021. }
  22022. }
  22023. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  22024. }
  22025. return candidateFnCall;
  22026. }
  22027. }
  22028. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  22029. /**
  22030. * TSL function for creating a function overloading node.
  22031. *
  22032. * @tsl
  22033. * @function
  22034. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22035. * @returns {FunctionOverloadingNode}
  22036. */
  22037. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  22038. /**
  22039. * Represents the elapsed time in seconds.
  22040. *
  22041. * @tsl
  22042. * @type {UniformNode<float>}
  22043. */
  22044. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  22045. /**
  22046. * Represents the delta time in seconds.
  22047. *
  22048. * @tsl
  22049. * @type {UniformNode<float>}
  22050. */
  22051. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  22052. /**
  22053. * Represents the current frame ID.
  22054. *
  22055. * @tsl
  22056. * @type {UniformNode<uint>}
  22057. */
  22058. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  22059. // Deprecated
  22060. /**
  22061. * @tsl
  22062. * @function
  22063. * @deprecated since r170. Use {@link time} instead.
  22064. *
  22065. * @param {number} [timeScale=1] - The time scale.
  22066. * @returns {UniformNode<float>}
  22067. */
  22068. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  22069. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  22070. return time.mul( timeScale );
  22071. };
  22072. /**
  22073. * @tsl
  22074. * @function
  22075. * @deprecated since r170. Use {@link time} instead.
  22076. *
  22077. * @param {number} [timeScale=1] - The time scale.
  22078. * @returns {UniformNode<float>}
  22079. */
  22080. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  22081. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  22082. return time.mul( timeScale );
  22083. };
  22084. /**
  22085. * @tsl
  22086. * @function
  22087. * @deprecated since r170. Use {@link deltaTime} instead.
  22088. *
  22089. * @param {number} [timeScale=1] - The time scale.
  22090. * @returns {UniformNode<float>}
  22091. */
  22092. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  22093. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  22094. return deltaTime.mul( timeScale );
  22095. };
  22096. /**
  22097. * Generates a sine wave oscillation based on a timer.
  22098. *
  22099. * @tsl
  22100. * @function
  22101. * @param {Node<float>} t - The timer to generate the oscillation with.
  22102. * @return {Node<float>} The oscillation node.
  22103. */
  22104. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  22105. /**
  22106. * Generates a square wave oscillation based on a timer.
  22107. *
  22108. * @tsl
  22109. * @function
  22110. * @param {Node<float>} t - The timer to generate the oscillation with.
  22111. * @return {Node<float>} The oscillation node.
  22112. */
  22113. const oscSquare = ( t = time ) => t.fract().round();
  22114. /**
  22115. * Generates a triangle wave oscillation based on a timer.
  22116. *
  22117. * @tsl
  22118. * @function
  22119. * @param {Node<float>} t - The timer to generate the oscillation with.
  22120. * @return {Node<float>} The oscillation node.
  22121. */
  22122. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  22123. /**
  22124. * Generates a sawtooth wave oscillation based on a timer.
  22125. *
  22126. * @tsl
  22127. * @function
  22128. * @param {Node<float>} t - The timer to generate the oscillation with.
  22129. * @return {Node<float>} The oscillation node.
  22130. */
  22131. const oscSawtooth = ( t = time ) => t.fract();
  22132. /**
  22133. * Rotates the given uv coordinates around a center point
  22134. *
  22135. * @tsl
  22136. * @function
  22137. * @param {Node<vec2>} uv - The uv coordinates.
  22138. * @param {Node<float>} rotation - The rotation defined in radians.
  22139. * @param {Node<vec2>} center - The center of rotation
  22140. * @return {Node<vec2>} The rotated uv coordinates.
  22141. */
  22142. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  22143. return rotate( uv.sub( center ), rotation ).add( center );
  22144. } );
  22145. /**
  22146. * Applies a spherical warping effect to the given uv coordinates.
  22147. *
  22148. * @tsl
  22149. * @function
  22150. * @param {Node<vec2>} uv - The uv coordinates.
  22151. * @param {Node<float>} strength - The strength of the effect.
  22152. * @param {Node<vec2>} center - The center point
  22153. * @return {Node<vec2>} The updated uv coordinates.
  22154. */
  22155. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  22156. const delta = uv.sub( center );
  22157. const delta2 = delta.dot( delta );
  22158. const delta4 = delta2.mul( delta2 );
  22159. const deltaOffset = delta4.mul( strength );
  22160. return uv.add( delta.mul( deltaOffset ) );
  22161. } );
  22162. /**
  22163. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  22164. * oriented always towards the camera.
  22165. *
  22166. * ```js
  22167. * material.vertexNode = billboarding();
  22168. * ```
  22169. *
  22170. * @tsl
  22171. * @function
  22172. * @param {Object} config - The configuration object.
  22173. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  22174. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  22175. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  22176. * @return {Node<vec3>} The updated vertex position in clip space.
  22177. */
  22178. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  22179. let worldMatrix;
  22180. if ( position !== null ) {
  22181. worldMatrix = modelWorldMatrix.toVar();
  22182. worldMatrix[ 3 ][ 0 ] = position.x;
  22183. worldMatrix[ 3 ][ 1 ] = position.y;
  22184. worldMatrix[ 3 ][ 2 ] = position.z;
  22185. } else {
  22186. worldMatrix = modelWorldMatrix;
  22187. }
  22188. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  22189. if ( defined( horizontal ) ) {
  22190. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  22191. modelViewMatrix[ 0 ][ 1 ] = 0;
  22192. modelViewMatrix[ 0 ][ 2 ] = 0;
  22193. }
  22194. if ( defined( vertical ) ) {
  22195. modelViewMatrix[ 1 ][ 0 ] = 0;
  22196. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  22197. modelViewMatrix[ 1 ][ 2 ] = 0;
  22198. }
  22199. modelViewMatrix[ 2 ][ 0 ] = 0;
  22200. modelViewMatrix[ 2 ][ 1 ] = 0;
  22201. modelViewMatrix[ 2 ][ 2 ] = 1;
  22202. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  22203. } );
  22204. /**
  22205. * A special version of a screen uv function that involves a depth comparison
  22206. * when computing the final uvs. The function mitigates visual errors when
  22207. * using viewport texture nodes for refraction purposes. Without this function
  22208. * objects in front of a refractive surface might appear on the refractive surface
  22209. * which is incorrect.
  22210. *
  22211. * @tsl
  22212. * @function
  22213. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  22214. * @return {Node<vec2>} The update uv coordinates.
  22215. */
  22216. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  22217. const depth = linearDepth();
  22218. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  22219. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  22220. return finalUV;
  22221. } );
  22222. /**
  22223. * Can be used to compute texture coordinates for animated sprite sheets.
  22224. *
  22225. * ```js
  22226. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  22227. *
  22228. * material.colorNode = texture( spriteSheet, uvNode );
  22229. * ```
  22230. *
  22231. * @augments Node
  22232. */
  22233. class SpriteSheetUVNode extends Node {
  22234. static get type() {
  22235. return 'SpriteSheetUVNode';
  22236. }
  22237. /**
  22238. * Constructs a new sprite sheet uv node.
  22239. *
  22240. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22241. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  22242. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22243. */
  22244. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  22245. super( 'vec2' );
  22246. /**
  22247. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22248. *
  22249. * @type {Node<vec2>}
  22250. */
  22251. this.countNode = countNode;
  22252. /**
  22253. * The uv node.
  22254. *
  22255. * @type {Node<vec2>}
  22256. */
  22257. this.uvNode = uvNode;
  22258. /**
  22259. * The node that defines the current frame/sprite.
  22260. *
  22261. * @type {Node<float>}
  22262. */
  22263. this.frameNode = frameNode;
  22264. }
  22265. setup() {
  22266. const { frameNode, uvNode, countNode } = this;
  22267. const { width, height } = countNode;
  22268. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  22269. const column = frameNum.mod( width );
  22270. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  22271. const scale = countNode.reciprocal();
  22272. const uvFrameOffset = vec2( column, row );
  22273. return uvNode.add( uvFrameOffset ).mul( scale );
  22274. }
  22275. }
  22276. /**
  22277. * TSL function for creating a sprite sheet uv node.
  22278. *
  22279. * @tsl
  22280. * @function
  22281. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22282. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  22283. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22284. * @returns {SpriteSheetUVNode}
  22285. */
  22286. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  22287. /**
  22288. * Can be used for triplanar texture mapping.
  22289. *
  22290. * ```js
  22291. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  22292. * ```
  22293. *
  22294. * @augments Node
  22295. */
  22296. class TriplanarTexturesNode extends Node {
  22297. static get type() {
  22298. return 'TriplanarTexturesNode';
  22299. }
  22300. /**
  22301. * Constructs a new triplanar textures node.
  22302. *
  22303. * @param {Node} textureXNode - First texture node.
  22304. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22305. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22306. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22307. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22308. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22309. */
  22310. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  22311. super( 'vec4' );
  22312. /**
  22313. * First texture node.
  22314. *
  22315. * @type {Node}
  22316. */
  22317. this.textureXNode = textureXNode;
  22318. /**
  22319. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22320. *
  22321. * @type {?Node}
  22322. * @default null
  22323. */
  22324. this.textureYNode = textureYNode;
  22325. /**
  22326. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22327. *
  22328. * @type {?Node}
  22329. * @default null
  22330. */
  22331. this.textureZNode = textureZNode;
  22332. /**
  22333. * The scale node.
  22334. *
  22335. * @type {Node<float>}
  22336. * @default float(1)
  22337. */
  22338. this.scaleNode = scaleNode;
  22339. /**
  22340. * Vertex positions in local space.
  22341. *
  22342. * @type {Node<vec3>}
  22343. * @default positionLocal
  22344. */
  22345. this.positionNode = positionNode;
  22346. /**
  22347. * Normals in local space.
  22348. *
  22349. * @type {Node<vec3>}
  22350. * @default normalLocal
  22351. */
  22352. this.normalNode = normalNode;
  22353. }
  22354. setup() {
  22355. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  22356. // Ref: https://github.com/keijiro/StandardTriplanar
  22357. // Blending factor of triplanar mapping
  22358. let bf = normalNode.abs().normalize();
  22359. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  22360. // Triplanar mapping
  22361. const tx = positionNode.yz.mul( scaleNode );
  22362. const ty = positionNode.zx.mul( scaleNode );
  22363. const tz = positionNode.xy.mul( scaleNode );
  22364. // Base color
  22365. const textureX = textureXNode.value;
  22366. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  22367. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  22368. const cx = texture( textureX, tx ).mul( bf.x );
  22369. const cy = texture( textureY, ty ).mul( bf.y );
  22370. const cz = texture( textureZ, tz ).mul( bf.z );
  22371. return add( cx, cy, cz );
  22372. }
  22373. }
  22374. /**
  22375. * TSL function for creating a triplanar textures node.
  22376. *
  22377. * @tsl
  22378. * @function
  22379. * @param {Node} textureXNode - First texture node.
  22380. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22381. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22382. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22383. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22384. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22385. * @returns {TriplanarTexturesNode}
  22386. */
  22387. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode ).setParameterLength( 1, 6 );
  22388. /**
  22389. * TSL function for creating a triplanar textures node.
  22390. *
  22391. * @tsl
  22392. * @function
  22393. * @param {Node} textureXNode - First texture node.
  22394. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22395. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22396. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22397. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22398. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22399. * @returns {TriplanarTexturesNode}
  22400. */
  22401. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  22402. const _reflectorPlane = new Plane();
  22403. const _normal = new Vector3();
  22404. const _reflectorWorldPosition = new Vector3();
  22405. const _cameraWorldPosition = new Vector3();
  22406. const _rotationMatrix = new Matrix4();
  22407. const _lookAtPosition = new Vector3( 0, 0, -1 );
  22408. const clipPlane = new Vector4();
  22409. const _view = new Vector3();
  22410. const _target = new Vector3();
  22411. const _q = new Vector4();
  22412. const _size$2 = new Vector2();
  22413. const _defaultRT = new RenderTarget();
  22414. const _defaultUV = screenUV.flipX();
  22415. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  22416. let _inReflector = false;
  22417. /**
  22418. * This node can be used to implement mirror-like flat reflective surfaces.
  22419. *
  22420. * ```js
  22421. * const groundReflector = reflector();
  22422. * material.colorNode = groundReflector;
  22423. *
  22424. * const plane = new Mesh( geometry, material );
  22425. * plane.add( groundReflector.target );
  22426. * ```
  22427. *
  22428. * @augments TextureNode
  22429. */
  22430. class ReflectorNode extends TextureNode {
  22431. static get type() {
  22432. return 'ReflectorNode';
  22433. }
  22434. /**
  22435. * Constructs a new reflector node.
  22436. *
  22437. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22438. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22439. * @param {number} [parameters.resolution=1] - The resolution scale.
  22440. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22441. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22442. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22443. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  22444. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  22445. */
  22446. constructor( parameters = {} ) {
  22447. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  22448. /**
  22449. * A reference to the internal reflector base node which holds the actual implementation.
  22450. *
  22451. * @private
  22452. * @type {ReflectorBaseNode}
  22453. * @default ReflectorBaseNode
  22454. */
  22455. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  22456. /**
  22457. * A reference to the internal depth node.
  22458. *
  22459. * @private
  22460. * @type {?Node}
  22461. * @default null
  22462. */
  22463. this._depthNode = null;
  22464. this.setUpdateMatrix( false );
  22465. }
  22466. /**
  22467. * A reference to the internal reflector node.
  22468. *
  22469. * @type {ReflectorBaseNode}
  22470. */
  22471. get reflector() {
  22472. return this._reflectorBaseNode;
  22473. }
  22474. /**
  22475. * A reference to 3D object the reflector is linked to.
  22476. *
  22477. * @type {Object3D}
  22478. */
  22479. get target() {
  22480. return this._reflectorBaseNode.target;
  22481. }
  22482. /**
  22483. * Returns a node representing the mirror's depth. That can be used
  22484. * to implement more advanced reflection effects like distance attenuation.
  22485. *
  22486. * @return {Node} The depth node.
  22487. */
  22488. getDepthNode() {
  22489. if ( this._depthNode === null ) {
  22490. if ( this._reflectorBaseNode.depth !== true ) {
  22491. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  22492. }
  22493. this._depthNode = nodeObject( new ReflectorNode( {
  22494. defaultTexture: _defaultRT.depthTexture,
  22495. reflector: this._reflectorBaseNode
  22496. } ) );
  22497. }
  22498. return this._depthNode;
  22499. }
  22500. setup( builder ) {
  22501. // ignore if used in post-processing
  22502. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  22503. return super.setup( builder );
  22504. }
  22505. clone() {
  22506. const texture = new this.constructor( this.reflectorNode );
  22507. texture._reflectorBaseNode = this._reflectorBaseNode;
  22508. return texture;
  22509. }
  22510. /**
  22511. * Frees internal resources. Should be called when the node is no longer in use.
  22512. */
  22513. dispose() {
  22514. super.dispose();
  22515. this._reflectorBaseNode.dispose();
  22516. }
  22517. }
  22518. /**
  22519. * Holds the actual implementation of the reflector.
  22520. *
  22521. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  22522. * in `ReflectorNode`, see #29619.
  22523. *
  22524. * @private
  22525. * @augments Node
  22526. */
  22527. class ReflectorBaseNode extends Node {
  22528. static get type() {
  22529. return 'ReflectorBaseNode';
  22530. }
  22531. /**
  22532. * Constructs a new reflector base node.
  22533. *
  22534. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  22535. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22536. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22537. * @param {number} [parameters.resolution=1] - The resolution scale.
  22538. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22539. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22540. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22541. */
  22542. constructor( textureNode, parameters = {} ) {
  22543. super();
  22544. const {
  22545. target = new Object3D(),
  22546. resolution = 1,
  22547. generateMipmaps = false,
  22548. bounces = true,
  22549. depth = false
  22550. } = parameters;
  22551. /**
  22552. * Represents the rendered reflections as a texture node.
  22553. *
  22554. * @type {TextureNode}
  22555. */
  22556. this.textureNode = textureNode;
  22557. /**
  22558. * The 3D object the reflector is linked to.
  22559. *
  22560. * @type {Object3D}
  22561. * @default {new Object3D()}
  22562. */
  22563. this.target = target;
  22564. /**
  22565. * The resolution scale.
  22566. *
  22567. * @type {number}
  22568. * @default {1}
  22569. */
  22570. this.resolution = resolution;
  22571. /**
  22572. * Whether mipmaps should be generated or not.
  22573. *
  22574. * @type {boolean}
  22575. * @default {false}
  22576. */
  22577. this.generateMipmaps = generateMipmaps;
  22578. /**
  22579. * Whether reflectors can render other reflector nodes or not.
  22580. *
  22581. * @type {boolean}
  22582. * @default {true}
  22583. */
  22584. this.bounces = bounces;
  22585. /**
  22586. * Whether depth data should be generated or not.
  22587. *
  22588. * @type {boolean}
  22589. * @default {false}
  22590. */
  22591. this.depth = depth;
  22592. /**
  22593. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  22594. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  22595. *
  22596. * @type {string}
  22597. * @default 'render'
  22598. */
  22599. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  22600. /**
  22601. * Weak map for managing virtual cameras.
  22602. *
  22603. * @type {WeakMap<Camera, Camera>}
  22604. */
  22605. this.virtualCameras = new WeakMap();
  22606. /**
  22607. * Weak map for managing render targets.
  22608. *
  22609. * @type {Map<Camera, RenderTarget>}
  22610. */
  22611. this.renderTargets = new Map();
  22612. /**
  22613. * Force render even if reflector is facing away from camera.
  22614. *
  22615. * @type {boolean}
  22616. * @default {false}
  22617. */
  22618. this.forceUpdate = false;
  22619. /**
  22620. * Whether the reflector has been rendered or not.
  22621. *
  22622. * When the reflector is facing away from the camera,
  22623. * this flag is set to `false` and the texture will be empty(black).
  22624. *
  22625. * @type {boolean}
  22626. * @default {false}
  22627. */
  22628. this.hasOutput = false;
  22629. }
  22630. /**
  22631. * Updates the resolution of the internal render target.
  22632. *
  22633. * @private
  22634. * @param {RenderTarget} renderTarget - The render target to resize.
  22635. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  22636. */
  22637. _updateResolution( renderTarget, renderer ) {
  22638. const resolution = this.resolution;
  22639. renderer.getDrawingBufferSize( _size$2 );
  22640. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  22641. }
  22642. setup( builder ) {
  22643. this._updateResolution( _defaultRT, builder.renderer );
  22644. return super.setup( builder );
  22645. }
  22646. /**
  22647. * Frees internal resources. Should be called when the node is no longer in use.
  22648. */
  22649. dispose() {
  22650. super.dispose();
  22651. for ( const renderTarget of this.renderTargets.values() ) {
  22652. renderTarget.dispose();
  22653. }
  22654. }
  22655. /**
  22656. * Returns a virtual camera for the given camera. The virtual camera is used to
  22657. * render the scene from the reflector's view so correct reflections can be produced.
  22658. *
  22659. * @param {Camera} camera - The scene's camera.
  22660. * @return {Camera} The corresponding virtual camera.
  22661. */
  22662. getVirtualCamera( camera ) {
  22663. let virtualCamera = this.virtualCameras.get( camera );
  22664. if ( virtualCamera === undefined ) {
  22665. virtualCamera = camera.clone();
  22666. this.virtualCameras.set( camera, virtualCamera );
  22667. }
  22668. return virtualCamera;
  22669. }
  22670. /**
  22671. * Returns a render target for the given camera. The reflections are rendered
  22672. * into this render target.
  22673. *
  22674. * @param {Camera} camera - The scene's camera.
  22675. * @return {RenderTarget} The render target.
  22676. */
  22677. getRenderTarget( camera ) {
  22678. let renderTarget = this.renderTargets.get( camera );
  22679. if ( renderTarget === undefined ) {
  22680. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  22681. if ( this.generateMipmaps === true ) {
  22682. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  22683. renderTarget.texture.generateMipmaps = true;
  22684. }
  22685. if ( this.depth === true ) {
  22686. renderTarget.depthTexture = new DepthTexture();
  22687. }
  22688. this.renderTargets.set( camera, renderTarget );
  22689. }
  22690. return renderTarget;
  22691. }
  22692. updateBefore( frame ) {
  22693. if ( this.bounces === false && _inReflector ) return false;
  22694. _inReflector = true;
  22695. const { scene, camera, renderer, material } = frame;
  22696. const { target } = this;
  22697. const virtualCamera = this.getVirtualCamera( camera );
  22698. const renderTarget = this.getRenderTarget( virtualCamera );
  22699. renderer.getDrawingBufferSize( _size$2 );
  22700. this._updateResolution( renderTarget, renderer );
  22701. //
  22702. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  22703. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  22704. _rotationMatrix.extractRotation( target.matrixWorld );
  22705. _normal.set( 0, 0, 1 );
  22706. _normal.applyMatrix4( _rotationMatrix );
  22707. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  22708. // Avoid rendering when reflector is facing away unless forcing an update
  22709. const isFacingAway = _view.dot( _normal ) > 0;
  22710. let needsClear = false;
  22711. if ( isFacingAway === true && this.forceUpdate === false ) {
  22712. if ( this.hasOutput === false ) {
  22713. _inReflector = false;
  22714. return;
  22715. }
  22716. needsClear = true;
  22717. }
  22718. _view.reflect( _normal ).negate();
  22719. _view.add( _reflectorWorldPosition );
  22720. _rotationMatrix.extractRotation( camera.matrixWorld );
  22721. _lookAtPosition.set( 0, 0, -1 );
  22722. _lookAtPosition.applyMatrix4( _rotationMatrix );
  22723. _lookAtPosition.add( _cameraWorldPosition );
  22724. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  22725. _target.reflect( _normal ).negate();
  22726. _target.add( _reflectorWorldPosition );
  22727. //
  22728. virtualCamera.coordinateSystem = camera.coordinateSystem;
  22729. virtualCamera.position.copy( _view );
  22730. virtualCamera.up.set( 0, 1, 0 );
  22731. virtualCamera.up.applyMatrix4( _rotationMatrix );
  22732. virtualCamera.up.reflect( _normal );
  22733. virtualCamera.lookAt( _target );
  22734. virtualCamera.near = camera.near;
  22735. virtualCamera.far = camera.far;
  22736. virtualCamera.updateMatrixWorld();
  22737. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  22738. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  22739. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  22740. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  22741. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  22742. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  22743. const projectionMatrix = virtualCamera.projectionMatrix;
  22744. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  22745. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  22746. _q.z = -1;
  22747. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  22748. // Calculate the scaled plane vector
  22749. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  22750. const clipBias = 0;
  22751. // Replacing the third row of the projection matrix
  22752. projectionMatrix.elements[ 2 ] = clipPlane.x;
  22753. projectionMatrix.elements[ 6 ] = clipPlane.y;
  22754. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  22755. projectionMatrix.elements[ 14 ] = clipPlane.w;
  22756. //
  22757. this.textureNode.value = renderTarget.texture;
  22758. if ( this.depth === true ) {
  22759. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  22760. }
  22761. material.visible = false;
  22762. const currentRenderTarget = renderer.getRenderTarget();
  22763. const currentMRT = renderer.getMRT();
  22764. const currentAutoClear = renderer.autoClear;
  22765. renderer.setMRT( null );
  22766. renderer.setRenderTarget( renderTarget );
  22767. renderer.autoClear = true;
  22768. if ( needsClear ) {
  22769. renderer.clear();
  22770. this.hasOutput = false;
  22771. } else {
  22772. renderer.render( scene, virtualCamera );
  22773. this.hasOutput = true;
  22774. }
  22775. renderer.setMRT( currentMRT );
  22776. renderer.setRenderTarget( currentRenderTarget );
  22777. renderer.autoClear = currentAutoClear;
  22778. material.visible = true;
  22779. _inReflector = false;
  22780. this.forceUpdate = false;
  22781. }
  22782. }
  22783. /**
  22784. * TSL function for creating a reflector node.
  22785. *
  22786. * @tsl
  22787. * @function
  22788. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22789. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22790. * @param {number} [parameters.resolution=1] - The resolution scale.
  22791. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22792. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22793. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22794. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  22795. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  22796. * @returns {ReflectorNode}
  22797. */
  22798. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  22799. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  22800. /**
  22801. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  22802. *
  22803. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  22804. *
  22805. * @private
  22806. * @augments BufferGeometry
  22807. */
  22808. class QuadGeometry extends BufferGeometry {
  22809. /**
  22810. * Constructs a new quad geometry.
  22811. *
  22812. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  22813. */
  22814. constructor( flipY = false ) {
  22815. super();
  22816. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  22817. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  22818. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  22819. }
  22820. }
  22821. const _geometry = /*@__PURE__*/ new QuadGeometry();
  22822. /**
  22823. * This module is a helper for passes which need to render a full
  22824. * screen effect which is quite common in context of post processing.
  22825. *
  22826. * The intended usage is to reuse a single quad mesh for rendering
  22827. * subsequent passes by just reassigning the `material` reference.
  22828. *
  22829. * Note: This module can only be used with `WebGPURenderer`.
  22830. *
  22831. * @augments Mesh
  22832. */
  22833. class QuadMesh extends Mesh {
  22834. /**
  22835. * Constructs a new quad mesh.
  22836. *
  22837. * @param {?Material} [material=null] - The material to render the quad mesh with.
  22838. */
  22839. constructor( material = null ) {
  22840. super( _geometry, material );
  22841. /**
  22842. * The camera to render the quad mesh with.
  22843. *
  22844. * @type {OrthographicCamera}
  22845. * @readonly
  22846. */
  22847. this.camera = _camera;
  22848. /**
  22849. * This flag can be used for type testing.
  22850. *
  22851. * @type {boolean}
  22852. * @readonly
  22853. * @default true
  22854. */
  22855. this.isQuadMesh = true;
  22856. }
  22857. /**
  22858. * Async version of `render()`.
  22859. *
  22860. * @async
  22861. * @param {Renderer} renderer - The renderer.
  22862. * @return {Promise} A Promise that resolves when the render has been finished.
  22863. */
  22864. async renderAsync( renderer ) {
  22865. return renderer.renderAsync( this, _camera );
  22866. }
  22867. /**
  22868. * Renders the quad mesh
  22869. *
  22870. * @param {Renderer} renderer - The renderer.
  22871. */
  22872. render( renderer ) {
  22873. renderer.render( this, _camera );
  22874. }
  22875. }
  22876. const _size$1 = /*@__PURE__*/ new Vector2();
  22877. /**
  22878. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  22879. * This module is especially relevant in context of post processing where certain nodes require
  22880. * texture input for their effects. With the helper function `convertToTexture()` which is based
  22881. * on this module, the node system can automatically ensure texture input if required.
  22882. *
  22883. * @augments TextureNode
  22884. */
  22885. class RTTNode extends TextureNode {
  22886. static get type() {
  22887. return 'RTTNode';
  22888. }
  22889. /**
  22890. * Constructs a new RTT node.
  22891. *
  22892. * @param {Node} node - The node to render a texture with.
  22893. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  22894. * @param {?number} [height=null] - The height of the internal render target.
  22895. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  22896. */
  22897. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  22898. const renderTarget = new RenderTarget( width, height, options );
  22899. super( renderTarget.texture, uv() );
  22900. /**
  22901. * The node to render a texture with.
  22902. *
  22903. * @type {Node}
  22904. */
  22905. this.node = node;
  22906. /**
  22907. * The width of the internal render target.
  22908. * If not width is applied, the render target is automatically resized.
  22909. *
  22910. * @type {?number}
  22911. * @default null
  22912. */
  22913. this.width = width;
  22914. /**
  22915. * The height of the internal render target.
  22916. *
  22917. * @type {?number}
  22918. * @default null
  22919. */
  22920. this.height = height;
  22921. /**
  22922. * The pixel ratio
  22923. *
  22924. * @type {number}
  22925. * @default 1
  22926. */
  22927. this.pixelRatio = 1;
  22928. /**
  22929. * The render target
  22930. *
  22931. * @type {RenderTarget}
  22932. */
  22933. this.renderTarget = renderTarget;
  22934. /**
  22935. * Whether the texture requires an update or not.
  22936. *
  22937. * @type {boolean}
  22938. * @default true
  22939. */
  22940. this.textureNeedsUpdate = true;
  22941. /**
  22942. * Whether the texture should automatically be updated or not.
  22943. *
  22944. * @type {boolean}
  22945. * @default true
  22946. */
  22947. this.autoUpdate = true;
  22948. /**
  22949. * The node which is used with the quad mesh for RTT.
  22950. *
  22951. * @private
  22952. * @type {Node}
  22953. * @default null
  22954. */
  22955. this._rttNode = null;
  22956. /**
  22957. * The internal quad mesh for RTT.
  22958. *
  22959. * @private
  22960. * @type {QuadMesh}
  22961. */
  22962. this._quadMesh = new QuadMesh( new NodeMaterial() );
  22963. /**
  22964. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  22965. * the texture once per render in its {@link RTTNode#updateBefore} method.
  22966. *
  22967. * @type {string}
  22968. * @default 'render'
  22969. */
  22970. this.updateBeforeType = NodeUpdateType.RENDER;
  22971. }
  22972. /**
  22973. * Whether the internal render target should automatically be resized or not.
  22974. *
  22975. * @type {boolean}
  22976. * @readonly
  22977. * @default true
  22978. */
  22979. get autoSize() {
  22980. return this.width === null;
  22981. }
  22982. setup( builder ) {
  22983. this._rttNode = this.node.context( builder.getSharedContext() );
  22984. this._quadMesh.material.name = 'RTT';
  22985. this._quadMesh.material.needsUpdate = true;
  22986. return super.setup( builder );
  22987. }
  22988. /**
  22989. * Sets the size of the internal render target
  22990. *
  22991. * @param {number} width - The width to set.
  22992. * @param {number} height - The width to set.
  22993. */
  22994. setSize( width, height ) {
  22995. this.width = width;
  22996. this.height = height;
  22997. const effectiveWidth = width * this.pixelRatio;
  22998. const effectiveHeight = height * this.pixelRatio;
  22999. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23000. this.textureNeedsUpdate = true;
  23001. }
  23002. /**
  23003. * Sets the pixel ratio. This will also resize the render target.
  23004. *
  23005. * @param {number} pixelRatio - The pixel ratio to set.
  23006. */
  23007. setPixelRatio( pixelRatio ) {
  23008. this.pixelRatio = pixelRatio;
  23009. this.setSize( this.width, this.height );
  23010. }
  23011. updateBefore( { renderer } ) {
  23012. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  23013. this.textureNeedsUpdate = false;
  23014. //
  23015. if ( this.autoSize === true ) {
  23016. this.pixelRatio = renderer.getPixelRatio();
  23017. const size = renderer.getSize( _size$1 );
  23018. this.setSize( size.width, size.height );
  23019. }
  23020. //
  23021. this._quadMesh.material.fragmentNode = this._rttNode;
  23022. //
  23023. const currentRenderTarget = renderer.getRenderTarget();
  23024. renderer.setRenderTarget( this.renderTarget );
  23025. this._quadMesh.render( renderer );
  23026. renderer.setRenderTarget( currentRenderTarget );
  23027. }
  23028. clone() {
  23029. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  23030. newNode.sampler = this.sampler;
  23031. newNode.referenceNode = this;
  23032. return newNode;
  23033. }
  23034. }
  23035. /**
  23036. * TSL function for creating a RTT node.
  23037. *
  23038. * @tsl
  23039. * @function
  23040. * @param {Node} node - The node to render a texture with.
  23041. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23042. * @param {?number} [height=null] - The height of the internal render target.
  23043. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23044. * @returns {RTTNode}
  23045. */
  23046. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  23047. /**
  23048. * TSL function for converting nodes to textures nodes.
  23049. *
  23050. * @tsl
  23051. * @function
  23052. * @param {Node} node - The node to render a texture with.
  23053. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23054. * @param {?number} [height=null] - The height of the internal render target.
  23055. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23056. * @returns {RTTNode}
  23057. */
  23058. const convertToTexture = ( node, ...params ) => {
  23059. if ( node.isTextureNode ) return node;
  23060. if ( node.isPassNode ) return node.getTextureNode();
  23061. return rtt( node, ...params );
  23062. };
  23063. /**
  23064. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  23065. * depth value and the camera's inverse projection matrix.
  23066. *
  23067. * @tsl
  23068. * @function
  23069. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  23070. * @param {Node<float>} depth - The fragment's depth value.
  23071. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23072. * @return {Node<vec3>} The fragments position in view space.
  23073. */
  23074. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  23075. let clipSpacePosition;
  23076. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  23077. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  23078. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  23079. } else {
  23080. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  23081. }
  23082. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  23083. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  23084. } );
  23085. /**
  23086. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  23087. * and the camera's projection matrix
  23088. *
  23089. * @tsl
  23090. * @function
  23091. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  23092. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  23093. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  23094. */
  23095. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  23096. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  23097. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  23098. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  23099. } );
  23100. /**
  23101. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  23102. * target is available or if flat surface normals are required.
  23103. *
  23104. * @tsl
  23105. * @function
  23106. * @param {Node<vec2>} uv - The texture coordinate.
  23107. * @param {DepthTexture} depthTexture - The depth texture.
  23108. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23109. * @return {Node<vec3>} The computed normal vector.
  23110. */
  23111. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  23112. const size = textureSize( textureLoad( depthTexture ) );
  23113. const p = ivec2( uv.mul( size ) ).toVar();
  23114. const c0 = textureLoad( depthTexture, p ).toVar();
  23115. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  23116. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  23117. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  23118. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  23119. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  23120. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  23121. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  23122. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  23123. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  23124. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  23125. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  23126. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  23127. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  23128. const dpdx = dl.lessThan( dr ).select( ce.sub( getViewPosition( uv.sub( vec2( float( 1 ).div( size.x ), 0 ) ), l1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.add( vec2( float( 1 ).div( size.x ), 0 ) ), r1, projectionMatrixInverse ) ) );
  23129. const dpdy = db.lessThan( dt ).select( ce.sub( getViewPosition( uv.add( vec2( 0, float( 1 ).div( size.y ) ) ), b1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.sub( vec2( 0, float( 1 ).div( size.y ) ) ), t1, projectionMatrixInverse ) ) );
  23130. return normalize( cross( dpdx, dpdy ) );
  23131. } );
  23132. /**
  23133. * This special type of instanced buffer attribute is intended for compute shaders.
  23134. * In earlier three.js versions it was only possible to update attribute data
  23135. * on the CPU via JavaScript and then upload the data to the GPU. With the
  23136. * new material system and renderer it is now possible to use compute shaders
  23137. * to compute the data for an attribute more efficiently on the GPU.
  23138. *
  23139. * The idea is to create an instance of this class and provide it as an input
  23140. * to {@link StorageBufferNode}.
  23141. *
  23142. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  23143. *
  23144. * @augments InstancedBufferAttribute
  23145. */
  23146. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  23147. /**
  23148. * Constructs a new storage instanced buffer attribute.
  23149. *
  23150. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  23151. * The subsequent parameters are then obsolete.
  23152. * @param {number} itemSize - The item size.
  23153. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23154. */
  23155. constructor( count, itemSize, typeClass = Float32Array ) {
  23156. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23157. super( array, itemSize );
  23158. /**
  23159. * This flag can be used for type testing.
  23160. *
  23161. * @type {boolean}
  23162. * @readonly
  23163. * @default true
  23164. */
  23165. this.isStorageInstancedBufferAttribute = true;
  23166. }
  23167. }
  23168. /**
  23169. * This special type of buffer attribute is intended for compute shaders.
  23170. * In earlier three.js versions it was only possible to update attribute data
  23171. * on the CPU via JavaScript and then upload the data to the GPU. With the
  23172. * new material system and renderer it is now possible to use compute shaders
  23173. * to compute the data for an attribute more efficiently on the GPU.
  23174. *
  23175. * The idea is to create an instance of this class and provide it as an input
  23176. * to {@link StorageBufferNode}.
  23177. *
  23178. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  23179. *
  23180. * @augments BufferAttribute
  23181. */
  23182. class StorageBufferAttribute extends BufferAttribute {
  23183. /**
  23184. * Constructs a new storage buffer attribute.
  23185. *
  23186. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  23187. * The subsequent parameters are then obsolete.
  23188. * @param {number} itemSize - The item size.
  23189. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23190. */
  23191. constructor( count, itemSize, typeClass = Float32Array ) {
  23192. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23193. super( array, itemSize );
  23194. /**
  23195. * This flag can be used for type testing.
  23196. *
  23197. * @type {boolean}
  23198. * @readonly
  23199. * @default true
  23200. */
  23201. this.isStorageBufferAttribute = true;
  23202. }
  23203. }
  23204. /**
  23205. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  23206. *
  23207. * @tsl
  23208. * @function
  23209. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23210. * @param {string|Struct} [type='float'] - The data type.
  23211. * @returns {StorageBufferNode}
  23212. */
  23213. const attributeArray = ( count, type = 'float' ) => {
  23214. let itemSize, typedArray;
  23215. if ( type.isStruct === true ) {
  23216. itemSize = type.layout.getLength();
  23217. typedArray = getTypedArrayFromType( 'float' );
  23218. } else {
  23219. itemSize = getLengthFromType( type );
  23220. typedArray = getTypedArrayFromType( type );
  23221. }
  23222. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  23223. const node = storage( buffer, type, count );
  23224. return node;
  23225. };
  23226. /**
  23227. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  23228. *
  23229. * @tsl
  23230. * @function
  23231. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23232. * @param {string|Struct} [type='float'] - The data type.
  23233. * @returns {StorageBufferNode}
  23234. */
  23235. const instancedArray = ( count, type = 'float' ) => {
  23236. let itemSize, typedArray;
  23237. if ( type.isStruct === true ) {
  23238. itemSize = type.layout.getLength();
  23239. typedArray = getTypedArrayFromType( 'float' );
  23240. } else {
  23241. itemSize = getLengthFromType( type );
  23242. typedArray = getTypedArrayFromType( type );
  23243. }
  23244. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  23245. const node = storage( buffer, type, count );
  23246. return node;
  23247. };
  23248. /**
  23249. * A node for representing the uv coordinates of points.
  23250. *
  23251. * Can only be used with a WebGL backend. In WebGPU, point
  23252. * primitives always have the size of one pixel and can thus
  23253. * can't be used as sprite-like objects that display textures.
  23254. *
  23255. * @augments Node
  23256. */
  23257. class PointUVNode extends Node {
  23258. static get type() {
  23259. return 'PointUVNode';
  23260. }
  23261. /**
  23262. * Constructs a new point uv node.
  23263. */
  23264. constructor() {
  23265. super( 'vec2' );
  23266. /**
  23267. * This flag can be used for type testing.
  23268. *
  23269. * @type {boolean}
  23270. * @readonly
  23271. * @default true
  23272. */
  23273. this.isPointUVNode = true;
  23274. }
  23275. generate( /*builder*/ ) {
  23276. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  23277. }
  23278. }
  23279. /**
  23280. * TSL object that represents the uv coordinates of points.
  23281. *
  23282. * @tsl
  23283. * @type {PointUVNode}
  23284. */
  23285. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  23286. const _e1 = /*@__PURE__*/ new Euler();
  23287. const _m1 = /*@__PURE__*/ new Matrix4();
  23288. /**
  23289. * This module allows access to a collection of scene properties. The following predefined TSL objects
  23290. * are available for easier use:
  23291. *
  23292. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  23293. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  23294. * - `backgroundRotation`: A node that represents the scene's background rotation.
  23295. *
  23296. * @augments Node
  23297. */
  23298. class SceneNode extends Node {
  23299. static get type() {
  23300. return 'SceneNode';
  23301. }
  23302. /**
  23303. * Constructs a new scene node.
  23304. *
  23305. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  23306. * @param {?Scene} [scene=null] - A reference to the scene.
  23307. */
  23308. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  23309. super();
  23310. /**
  23311. * The scope defines the type of scene property that is accessed.
  23312. *
  23313. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  23314. */
  23315. this.scope = scope;
  23316. /**
  23317. * A reference to the scene that is going to be accessed.
  23318. *
  23319. * @type {?Scene}
  23320. * @default null
  23321. */
  23322. this.scene = scene;
  23323. }
  23324. /**
  23325. * Depending on the scope, the method returns a different type of node that represents
  23326. * the respective scene property.
  23327. *
  23328. * @param {NodeBuilder} builder - The current node builder.
  23329. * @return {Node} The output node.
  23330. */
  23331. setup( builder ) {
  23332. const scope = this.scope;
  23333. const scene = this.scene !== null ? this.scene : builder.scene;
  23334. let output;
  23335. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  23336. output = reference( 'backgroundBlurriness', 'float', scene );
  23337. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  23338. output = reference( 'backgroundIntensity', 'float', scene );
  23339. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  23340. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  23341. const background = scene.background;
  23342. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  23343. _e1.copy( scene.backgroundRotation );
  23344. // accommodate left-handed frame
  23345. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  23346. _m1.makeRotationFromEuler( _e1 );
  23347. } else {
  23348. _m1.identity();
  23349. }
  23350. return _m1;
  23351. } );
  23352. } else {
  23353. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  23354. }
  23355. return output;
  23356. }
  23357. }
  23358. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  23359. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  23360. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  23361. /**
  23362. * TSL object that represents the scene's background blurriness.
  23363. *
  23364. * @tsl
  23365. * @type {SceneNode}
  23366. */
  23367. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  23368. /**
  23369. * TSL object that represents the scene's background intensity.
  23370. *
  23371. * @tsl
  23372. * @type {SceneNode}
  23373. */
  23374. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  23375. /**
  23376. * TSL object that represents the scene's background rotation.
  23377. *
  23378. * @tsl
  23379. * @type {SceneNode}
  23380. */
  23381. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  23382. /**
  23383. * This special version of a texture node can be used to
  23384. * write data into a storage texture with a compute shader.
  23385. *
  23386. * ```js
  23387. * const storageTexture = new THREE.StorageTexture( width, height );
  23388. *
  23389. * const computeTexture = Fn( ( { storageTexture } ) => {
  23390. *
  23391. * const posX = instanceIndex.mod( width );
  23392. * const posY = instanceIndex.div( width );
  23393. * const indexUV = uvec2( posX, posY );
  23394. *
  23395. * // generate RGB values
  23396. *
  23397. * const r = 1;
  23398. * const g = 1;
  23399. * const b = 1;
  23400. *
  23401. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  23402. *
  23403. * } );
  23404. *
  23405. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  23406. * renderer.computeAsync( computeNode );
  23407. * ```
  23408. *
  23409. * This node can only be used with a WebGPU backend.
  23410. *
  23411. * @augments TextureNode
  23412. */
  23413. class StorageTextureNode extends TextureNode {
  23414. static get type() {
  23415. return 'StorageTextureNode';
  23416. }
  23417. /**
  23418. * Constructs a new storage texture node.
  23419. *
  23420. * @param {StorageTexture} value - The storage texture.
  23421. * @param {Node<vec2|vec3>} uvNode - The uv node.
  23422. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23423. */
  23424. constructor( value, uvNode, storeNode = null ) {
  23425. super( value, uvNode );
  23426. /**
  23427. * The value node that should be stored in the texture.
  23428. *
  23429. * @type {?Node}
  23430. * @default null
  23431. */
  23432. this.storeNode = storeNode;
  23433. /**
  23434. * This flag can be used for type testing.
  23435. *
  23436. * @type {boolean}
  23437. * @readonly
  23438. * @default true
  23439. */
  23440. this.isStorageTextureNode = true;
  23441. /**
  23442. * The access type of the texture node.
  23443. *
  23444. * @type {string}
  23445. * @default 'writeOnly'
  23446. */
  23447. this.access = NodeAccess.WRITE_ONLY;
  23448. }
  23449. /**
  23450. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  23451. *
  23452. * @param {NodeBuilder} builder - The current node builder.
  23453. * @return {string} The input type.
  23454. */
  23455. getInputType( /*builder*/ ) {
  23456. return 'storageTexture';
  23457. }
  23458. setup( builder ) {
  23459. super.setup( builder );
  23460. const properties = builder.getNodeProperties( this );
  23461. properties.storeNode = this.storeNode;
  23462. return properties;
  23463. }
  23464. /**
  23465. * Defines the node access.
  23466. *
  23467. * @param {string} value - The node access.
  23468. * @return {StorageTextureNode} A reference to this node.
  23469. */
  23470. setAccess( value ) {
  23471. this.access = value;
  23472. return this;
  23473. }
  23474. /**
  23475. * Generates the code snippet of the storage node. If no `storeNode`
  23476. * is defined, the texture node is generated as normal texture.
  23477. *
  23478. * @param {NodeBuilder} builder - The current node builder.
  23479. * @param {string} output - The current output.
  23480. * @return {string} The generated code snippet.
  23481. */
  23482. generate( builder, output ) {
  23483. let snippet;
  23484. if ( this.storeNode !== null ) {
  23485. snippet = this.generateStore( builder );
  23486. } else {
  23487. snippet = super.generate( builder, output );
  23488. }
  23489. return snippet;
  23490. }
  23491. /**
  23492. * Convenience method for configuring a read/write node access.
  23493. *
  23494. * @return {StorageTextureNode} A reference to this node.
  23495. */
  23496. toReadWrite() {
  23497. return this.setAccess( NodeAccess.READ_WRITE );
  23498. }
  23499. /**
  23500. * Convenience method for configuring a read-only node access.
  23501. *
  23502. * @return {StorageTextureNode} A reference to this node.
  23503. */
  23504. toReadOnly() {
  23505. return this.setAccess( NodeAccess.READ_ONLY );
  23506. }
  23507. /**
  23508. * Convenience method for configuring a write-only node access.
  23509. *
  23510. * @return {StorageTextureNode} A reference to this node.
  23511. */
  23512. toWriteOnly() {
  23513. return this.setAccess( NodeAccess.WRITE_ONLY );
  23514. }
  23515. /**
  23516. * Generates the code snippet of the storage texture node.
  23517. *
  23518. * @param {NodeBuilder} builder - The current node builder.
  23519. */
  23520. generateStore( builder ) {
  23521. const properties = builder.getNodeProperties( this );
  23522. const { uvNode, storeNode, depthNode } = properties;
  23523. const textureProperty = super.generate( builder, 'property' );
  23524. const uvSnippet = uvNode.build( builder, 'uvec2' );
  23525. const storeSnippet = storeNode.build( builder, 'vec4' );
  23526. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  23527. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  23528. builder.addLineFlowCode( snippet, this );
  23529. }
  23530. clone() {
  23531. const newNode = super.clone();
  23532. newNode.storeNode = this.storeNode;
  23533. return newNode;
  23534. }
  23535. }
  23536. /**
  23537. * TSL function for creating a storage texture node.
  23538. *
  23539. * @tsl
  23540. * @function
  23541. * @param {StorageTexture} value - The storage texture.
  23542. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  23543. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23544. * @returns {StorageTextureNode}
  23545. */
  23546. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  23547. /**
  23548. * TODO: Explain difference to `storageTexture()`.
  23549. *
  23550. * @tsl
  23551. * @function
  23552. * @param {StorageTexture} value - The storage texture.
  23553. * @param {Node<vec2|vec3>} uvNode - The uv node.
  23554. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23555. * @returns {StorageTextureNode}
  23556. */
  23557. const textureStore = ( value, uvNode, storeNode ) => {
  23558. const node = storageTexture( value, uvNode, storeNode );
  23559. if ( storeNode !== null ) node.toStack();
  23560. return node;
  23561. };
  23562. const normal = Fn( ( { texture, uv } ) => {
  23563. const epsilon = 0.0001;
  23564. const ret = vec3().toVar();
  23565. If( uv.x.lessThan( epsilon ), () => {
  23566. ret.assign( vec3( 1, 0, 0 ) );
  23567. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  23568. ret.assign( vec3( 0, 1, 0 ) );
  23569. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  23570. ret.assign( vec3( 0, 0, 1 ) );
  23571. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  23572. ret.assign( vec3( -1, 0, 0 ) );
  23573. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  23574. ret.assign( vec3( 0, -1, 0 ) );
  23575. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  23576. ret.assign( vec3( 0, 0, -1 ) );
  23577. } ).Else( () => {
  23578. const step = 0.01;
  23579. const x = texture.sample( uv.add( vec3( -0.01, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  23580. const y = texture.sample( uv.add( vec3( 0.0, -0.01, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  23581. const z = texture.sample( uv.add( vec3( 0.0, 0.0, -0.01 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  23582. ret.assign( vec3( x, y, z ) );
  23583. } );
  23584. return ret.normalize();
  23585. } );
  23586. /**
  23587. * This type of uniform node represents a 3D texture.
  23588. *
  23589. * @augments TextureNode
  23590. */
  23591. class Texture3DNode extends TextureNode {
  23592. static get type() {
  23593. return 'Texture3DNode';
  23594. }
  23595. /**
  23596. * Constructs a new 3D texture node.
  23597. *
  23598. * @param {Data3DTexture} value - The 3D texture.
  23599. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  23600. * @param {?Node<int>} [levelNode=null] - The level node.
  23601. */
  23602. constructor( value, uvNode = null, levelNode = null ) {
  23603. super( value, uvNode, levelNode );
  23604. /**
  23605. * This flag can be used for type testing.
  23606. *
  23607. * @type {boolean}
  23608. * @readonly
  23609. * @default true
  23610. */
  23611. this.isTexture3DNode = true;
  23612. }
  23613. /**
  23614. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  23615. *
  23616. * @param {NodeBuilder} builder - The current node builder.
  23617. * @return {string} The input type.
  23618. */
  23619. getInputType( /*builder*/ ) {
  23620. return 'texture3D';
  23621. }
  23622. /**
  23623. * Returns a default uv node which is in context of 3D textures a three-dimensional
  23624. * uv node.
  23625. *
  23626. * @return {Node<vec3>} The default uv node.
  23627. */
  23628. getDefaultUV() {
  23629. return vec3( 0.5, 0.5, 0.5 );
  23630. }
  23631. /**
  23632. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  23633. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  23634. *
  23635. * @param {boolean} value - The update toggle.
  23636. */
  23637. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  23638. /**
  23639. * Overwrites the default implementation to return the unmodified uv node.
  23640. *
  23641. * @param {NodeBuilder} builder - The current node builder.
  23642. * @param {Node} uvNode - The uv node to setup.
  23643. * @return {Node} The unmodified uv node.
  23644. */
  23645. setupUV( builder, uvNode ) {
  23646. const texture = this.value;
  23647. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  23648. if ( this.sampler ) {
  23649. uvNode = uvNode.flipY();
  23650. } else {
  23651. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  23652. }
  23653. }
  23654. return uvNode;
  23655. }
  23656. /**
  23657. * Generates the uv code snippet.
  23658. *
  23659. * @param {NodeBuilder} builder - The current node builder.
  23660. * @param {Node} uvNode - The uv node to generate code for.
  23661. * @return {string} The generated code snippet.
  23662. */
  23663. generateUV( builder, uvNode ) {
  23664. return uvNode.build( builder, 'vec3' );
  23665. }
  23666. /**
  23667. * TODO.
  23668. *
  23669. * @param {Node<vec3>} uvNode - The uv node .
  23670. * @return {Node<vec3>} TODO.
  23671. */
  23672. normal( uvNode ) {
  23673. return normal( { texture: this, uv: uvNode } );
  23674. }
  23675. }
  23676. /**
  23677. * TSL function for creating a 3D texture node.
  23678. *
  23679. * @tsl
  23680. * @function
  23681. * @param {Data3DTexture} value - The 3D texture.
  23682. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  23683. * @param {?Node<int>} [levelNode=null] - The level node.
  23684. * @returns {Texture3DNode}
  23685. */
  23686. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  23687. /**
  23688. * A special type of reference node that allows to link values in
  23689. * `userData` fields to node objects.
  23690. * ```js
  23691. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  23692. *
  23693. * const material = new THREE.SpriteNodeMaterial();
  23694. * material.rotationNode = userData( 'rotation', 'float' );
  23695. * ```
  23696. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  23697. * will automatically be updated when the `rotation` user data field changes.
  23698. *
  23699. * @augments ReferenceNode
  23700. */
  23701. class UserDataNode extends ReferenceNode {
  23702. static get type() {
  23703. return 'UserDataNode';
  23704. }
  23705. /**
  23706. * Constructs a new user data node.
  23707. *
  23708. * @param {string} property - The property name that should be referenced by the node.
  23709. * @param {string} inputType - The node data type of the reference.
  23710. * @param {?Object} [userData=null] - A reference to the `userData` object. If not provided, the `userData` property of the 3D object that uses the node material is evaluated.
  23711. */
  23712. constructor( property, inputType, userData = null ) {
  23713. super( property, inputType, userData );
  23714. /**
  23715. * A reference to the `userData` object. If not provided, the `userData`
  23716. * property of the 3D object that uses the node material is evaluated.
  23717. *
  23718. * @type {?Object}
  23719. * @default null
  23720. */
  23721. this.userData = userData;
  23722. }
  23723. /**
  23724. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  23725. * `userData` field.
  23726. *
  23727. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  23728. * @return {Object} A reference to the `userData` field.
  23729. */
  23730. updateReference( state ) {
  23731. this.reference = this.userData !== null ? this.userData : state.object.userData;
  23732. return this.reference;
  23733. }
  23734. }
  23735. /**
  23736. * TSL function for creating a user data node.
  23737. *
  23738. * @tsl
  23739. * @function
  23740. * @param {string} name - The property name that should be referenced by the node.
  23741. * @param {string} inputType - The node data type of the reference.
  23742. * @param {?Object} userData - A reference to the `userData` object. If not provided, the `userData` property of the 3D object that uses the node material is evaluated.
  23743. * @returns {UserDataNode}
  23744. */
  23745. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  23746. const _objectData = new WeakMap();
  23747. /**
  23748. * A node for representing motion or velocity vectors. Foundation
  23749. * for advanced post processing effects like motion blur or TRAA.
  23750. *
  23751. * The node keeps track of the model, view and projection matrices
  23752. * of the previous frame and uses them to compute offsets in NDC space.
  23753. * These offsets represent the final velocity.
  23754. *
  23755. * @augments TempNode
  23756. */
  23757. class VelocityNode extends TempNode {
  23758. static get type() {
  23759. return 'VelocityNode';
  23760. }
  23761. /**
  23762. * Constructs a new vertex color node.
  23763. */
  23764. constructor() {
  23765. super( 'vec2' );
  23766. /**
  23767. * The current projection matrix.
  23768. *
  23769. * @type {?Matrix4}
  23770. * @default null
  23771. */
  23772. this.projectionMatrix = null;
  23773. /**
  23774. * Overwritten since velocity nodes are updated per object.
  23775. *
  23776. * @type {string}
  23777. * @default 'object'
  23778. */
  23779. this.updateType = NodeUpdateType.OBJECT;
  23780. /**
  23781. * Overwritten since velocity nodes save data after the update.
  23782. *
  23783. * @type {string}
  23784. * @default 'object'
  23785. */
  23786. this.updateAfterType = NodeUpdateType.OBJECT;
  23787. /**
  23788. * Uniform node representing the previous model matrix in world space.
  23789. *
  23790. * @type {UniformNode<mat4>}
  23791. * @default null
  23792. */
  23793. this.previousModelWorldMatrix = uniform( new Matrix4() );
  23794. /**
  23795. * Uniform node representing the previous projection matrix.
  23796. *
  23797. * @type {UniformNode<mat4>}
  23798. * @default null
  23799. */
  23800. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  23801. /**
  23802. * Uniform node representing the previous view matrix.
  23803. *
  23804. * @type {UniformNode<mat4>}
  23805. * @default null
  23806. */
  23807. this.previousCameraViewMatrix = uniform( new Matrix4() );
  23808. }
  23809. /**
  23810. * Sets the given projection matrix.
  23811. *
  23812. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  23813. */
  23814. setProjectionMatrix( projectionMatrix ) {
  23815. this.projectionMatrix = projectionMatrix;
  23816. }
  23817. /**
  23818. * Updates velocity specific uniforms.
  23819. *
  23820. * @param {NodeFrame} frame - A reference to the current node frame.
  23821. */
  23822. update( { frameId, camera, object } ) {
  23823. const previousModelMatrix = getPreviousMatrix( object );
  23824. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  23825. //
  23826. const cameraData = getData( camera );
  23827. if ( cameraData.frameId !== frameId ) {
  23828. cameraData.frameId = frameId;
  23829. if ( cameraData.previousProjectionMatrix === undefined ) {
  23830. cameraData.previousProjectionMatrix = new Matrix4();
  23831. cameraData.previousCameraViewMatrix = new Matrix4();
  23832. cameraData.currentProjectionMatrix = new Matrix4();
  23833. cameraData.currentCameraViewMatrix = new Matrix4();
  23834. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  23835. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  23836. } else {
  23837. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  23838. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  23839. }
  23840. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  23841. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  23842. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  23843. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  23844. }
  23845. }
  23846. /**
  23847. * Overwritten to updated velocity specific uniforms.
  23848. *
  23849. * @param {NodeFrame} frame - A reference to the current node frame.
  23850. */
  23851. updateAfter( { object } ) {
  23852. getPreviousMatrix( object ).copy( object.matrixWorld );
  23853. }
  23854. /**
  23855. * Implements the velocity computation based on the previous and current vertex data.
  23856. *
  23857. * @param {NodeBuilder} builder - A reference to the current node builder.
  23858. * @return {Node<vec2>} The motion vector.
  23859. */
  23860. setup( /*builder*/ ) {
  23861. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  23862. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  23863. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23864. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  23865. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  23866. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  23867. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  23868. return velocity;
  23869. }
  23870. }
  23871. function getData( object ) {
  23872. let objectData = _objectData.get( object );
  23873. if ( objectData === undefined ) {
  23874. objectData = {};
  23875. _objectData.set( object, objectData );
  23876. }
  23877. return objectData;
  23878. }
  23879. function getPreviousMatrix( object, index = 0 ) {
  23880. const objectData = getData( object );
  23881. let matrix = objectData[ index ];
  23882. if ( matrix === undefined ) {
  23883. objectData[ index ] = matrix = new Matrix4();
  23884. objectData[ index ].copy( object.matrixWorld );
  23885. }
  23886. return matrix;
  23887. }
  23888. /**
  23889. * TSL object that represents the velocity of a render pass.
  23890. *
  23891. * @tsl
  23892. * @type {VelocityNode}
  23893. */
  23894. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  23895. /**
  23896. * Represents a "Color Burn" blend mode.
  23897. *
  23898. * It's designed to darken the base layer's colors based on the color of the blend layer.
  23899. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  23900. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  23901. *
  23902. * @tsl
  23903. * @function
  23904. * @param {Node<vec3>} base - The base color.
  23905. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  23906. * @return {Node<vec3>} The result.
  23907. */
  23908. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23909. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  23910. } ).setLayout( {
  23911. name: 'blendBurn',
  23912. type: 'vec3',
  23913. inputs: [
  23914. { name: 'base', type: 'vec3' },
  23915. { name: 'blend', type: 'vec3' }
  23916. ]
  23917. } );
  23918. /**
  23919. * Represents a "Color Dodge" blend mode.
  23920. *
  23921. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  23922. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  23923. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  23924. *
  23925. * @tsl
  23926. * @function
  23927. * @param {Node<vec3>} base - The base color.
  23928. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  23929. * @return {Node<vec3>} The result.
  23930. */
  23931. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23932. return min$1( base.div( blend.oneMinus() ), 1.0 );
  23933. } ).setLayout( {
  23934. name: 'blendDodge',
  23935. type: 'vec3',
  23936. inputs: [
  23937. { name: 'base', type: 'vec3' },
  23938. { name: 'blend', type: 'vec3' }
  23939. ]
  23940. } );
  23941. /**
  23942. * Represents a "Screen" blend mode.
  23943. *
  23944. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  23945. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  23946. * effects.
  23947. *
  23948. * @tsl
  23949. * @function
  23950. * @param {Node<vec3>} base - The base color.
  23951. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  23952. * @return {Node<vec3>} The result.
  23953. */
  23954. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23955. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  23956. } ).setLayout( {
  23957. name: 'blendScreen',
  23958. type: 'vec3',
  23959. inputs: [
  23960. { name: 'base', type: 'vec3' },
  23961. { name: 'blend', type: 'vec3' }
  23962. ]
  23963. } );
  23964. /**
  23965. * Represents a "Overlay" blend mode.
  23966. *
  23967. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  23968. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  23969. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  23970. *
  23971. * @tsl
  23972. * @function
  23973. * @param {Node<vec3>} base - The base color.
  23974. * @param {Node<vec3>} blend - The blend color
  23975. * @return {Node<vec3>} The result.
  23976. */
  23977. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23978. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  23979. } ).setLayout( {
  23980. name: 'blendOverlay',
  23981. type: 'vec3',
  23982. inputs: [
  23983. { name: 'base', type: 'vec3' },
  23984. { name: 'blend', type: 'vec3' }
  23985. ]
  23986. } );
  23987. /**
  23988. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  23989. * It assumes both input colors have non-premultiplied alpha.
  23990. *
  23991. * @tsl
  23992. * @function
  23993. * @param {Node<vec4>} base - The base color.
  23994. * @param {Node<vec4>} blend - The blend color
  23995. * @return {Node<vec4>} The result.
  23996. */
  23997. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23998. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  23999. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  24000. } ).setLayout( {
  24001. name: 'blendColor',
  24002. type: 'vec4',
  24003. inputs: [
  24004. { name: 'base', type: 'vec4' },
  24005. { name: 'blend', type: 'vec4' }
  24006. ]
  24007. } );
  24008. /**
  24009. * Premultiplies the RGB channels of a color by its alpha channel.
  24010. *
  24011. * This function is useful for converting a non-premultiplied alpha color
  24012. * into a premultiplied alpha format, where the RGB values are scaled
  24013. * by the alpha value. Premultiplied alpha is often used in graphics
  24014. * rendering for certain operations, such as compositing and image processing.
  24015. *
  24016. * @tsl
  24017. * @function
  24018. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  24019. * @return {Node<vec4>} The color with premultiplied alpha.
  24020. */
  24021. const premult = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24022. return vec4( color.rgb.mul( color.a ), color.a );
  24023. }, { color: 'vec4', return: 'vec4' } );
  24024. /**
  24025. * Unpremultiplies the RGB channels of a color by its alpha channel.
  24026. *
  24027. * This function is useful for converting a premultiplied alpha color
  24028. * back into a non-premultiplied alpha format, where the RGB values are
  24029. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  24030. * rendering for certain operations, such as compositing and image processing.
  24031. *
  24032. * @tsl
  24033. * @function
  24034. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  24035. * @return {Node<vec4>} The color with non-premultiplied alpha.
  24036. */
  24037. const unpremult = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24038. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  24039. return vec4( color.rgb.div( color.a ), color.a );
  24040. }, { color: 'vec4', return: 'vec4' } );
  24041. // Deprecated
  24042. /**
  24043. * @tsl
  24044. * @function
  24045. * @deprecated since r171. Use {@link blendBurn} instead.
  24046. *
  24047. * @param {...any} params
  24048. * @returns {Function}
  24049. */
  24050. const burn = ( ...params ) => { // @deprecated, r171
  24051. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  24052. return blendBurn( params );
  24053. };
  24054. /**
  24055. * @tsl
  24056. * @function
  24057. * @deprecated since r171. Use {@link blendDodge} instead.
  24058. *
  24059. * @param {...any} params
  24060. * @returns {Function}
  24061. */
  24062. const dodge = ( ...params ) => { // @deprecated, r171
  24063. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  24064. return blendDodge( params );
  24065. };
  24066. /**
  24067. * @tsl
  24068. * @function
  24069. * @deprecated since r171. Use {@link blendScreen} instead.
  24070. *
  24071. * @param {...any} params
  24072. * @returns {Function}
  24073. */
  24074. const screen = ( ...params ) => { // @deprecated, r171
  24075. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  24076. return blendScreen( params );
  24077. };
  24078. /**
  24079. * @tsl
  24080. * @function
  24081. * @deprecated since r171. Use {@link blendOverlay} instead.
  24082. *
  24083. * @param {...any} params
  24084. * @returns {Function}
  24085. */
  24086. const overlay = ( ...params ) => { // @deprecated, r171
  24087. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  24088. return blendOverlay( params );
  24089. };
  24090. /**
  24091. * Computes a grayscale value for the given RGB color value.
  24092. *
  24093. * @tsl
  24094. * @function
  24095. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  24096. * @return {Node<vec3>} The grayscale color.
  24097. */
  24098. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24099. return luminance( color.rgb );
  24100. } );
  24101. /**
  24102. * Super-saturates or desaturates the given RGB color.
  24103. *
  24104. * @tsl
  24105. * @function
  24106. * @param {Node<vec3>} color - The input color.
  24107. * @param {Node<float>} [adjustment=1] - Specifies the amount of the conversion. A value under `1` desaturates the color, a value over `1` super-saturates it.
  24108. * @return {Node<vec3>} The saturated color.
  24109. */
  24110. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24111. return adjustment.mix( luminance( color.rgb ), color.rgb );
  24112. } );
  24113. /**
  24114. * Selectively enhance the intensity of less saturated RGB colors. Can result
  24115. * in a more natural and visually appealing image with enhanced color depth
  24116. * compared to {@link ColorAdjustment#saturation}.
  24117. *
  24118. * @tsl
  24119. * @function
  24120. * @param {Node<vec3>} color - The input color.
  24121. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  24122. * @return {Node<vec3>} The updated color.
  24123. */
  24124. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24125. const average = add( color.r, color.g, color.b ).div( 3.0 );
  24126. const mx = color.r.max( color.g.max( color.b ) );
  24127. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  24128. return mix( color.rgb, mx, amt );
  24129. } );
  24130. /**
  24131. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  24132. *
  24133. * @tsl
  24134. * @function
  24135. * @param {Node<vec3>} color - The input color.
  24136. * @param {Node<float>} [adjustment=1] - Defines the degree of hue rotation in radians. A positive value rotates the hue clockwise, while a negative value rotates it counterclockwise.
  24137. * @return {Node<vec3>} The updated color.
  24138. */
  24139. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24140. const k = vec3( 0.57735, 0.57735, 0.57735 );
  24141. const cosAngle = adjustment.cos();
  24142. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  24143. } );
  24144. /**
  24145. * Computes the luminance for the given RGB color value.
  24146. *
  24147. * @tsl
  24148. * @function
  24149. * @param {Node<vec3>} color - The color value to compute the luminance for.
  24150. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  24151. * @return {Node<vec3>} The luminance.
  24152. */
  24153. const luminance = (
  24154. color,
  24155. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  24156. ) => dot( color, luminanceCoefficients );
  24157. /**
  24158. * Color Decision List (CDL) v1.2
  24159. *
  24160. * Compact representation of color grading information, defined by slope, offset, power, and
  24161. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  24162. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  24163. *
  24164. * @tsl
  24165. * @function
  24166. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  24167. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  24168. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  24169. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  24170. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  24171. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  24172. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  24173. *
  24174. * References:
  24175. * - ASC CDL v1.2
  24176. * - {@link https://blender.stackexchange.com/a/55239/43930}
  24177. * - {@link https://docs.acescentral.com/specifications/acescc/}
  24178. */
  24179. const cdl = /*@__PURE__*/ Fn( ( [
  24180. color,
  24181. slope = vec3( 1 ),
  24182. offset = vec3( 0 ),
  24183. power = vec3( 1 ),
  24184. saturation = float( 1 ),
  24185. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  24186. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  24187. ] ) => {
  24188. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  24189. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  24190. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  24191. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  24192. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  24193. const pv = v.pow( power ).toVar();
  24194. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  24195. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  24196. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  24197. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  24198. return vec4( v.rgb, color.a );
  24199. } );
  24200. /**
  24201. * Represents a posterize effect which reduces the number of colors
  24202. * in an image, resulting in a more blocky and stylized appearance.
  24203. *
  24204. * @augments TempNode
  24205. */
  24206. class PosterizeNode extends TempNode {
  24207. static get type() {
  24208. return 'PosterizeNode';
  24209. }
  24210. /**
  24211. * Constructs a new posterize node.
  24212. *
  24213. * @param {Node} sourceNode - The input color.
  24214. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24215. */
  24216. constructor( sourceNode, stepsNode ) {
  24217. super();
  24218. /**
  24219. * The input color.
  24220. *
  24221. * @type {Node}
  24222. */
  24223. this.sourceNode = sourceNode;
  24224. /**
  24225. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24226. *
  24227. * @type {Node}
  24228. */
  24229. this.stepsNode = stepsNode;
  24230. }
  24231. setup() {
  24232. const { sourceNode, stepsNode } = this;
  24233. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  24234. }
  24235. }
  24236. /**
  24237. * TSL function for creating a posterize node.
  24238. *
  24239. * @tsl
  24240. * @function
  24241. * @param {Node} sourceNode - The input color.
  24242. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24243. * @returns {PosterizeNode}
  24244. */
  24245. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  24246. const _size = /*@__PURE__*/ new Vector2();
  24247. /**
  24248. * Represents the texture of a pass node.
  24249. *
  24250. * @augments TextureNode
  24251. */
  24252. class PassTextureNode extends TextureNode {
  24253. static get type() {
  24254. return 'PassTextureNode';
  24255. }
  24256. /**
  24257. * Constructs a new pass texture node.
  24258. *
  24259. * @param {PassNode} passNode - The pass node.
  24260. * @param {Texture} texture - The output texture.
  24261. */
  24262. constructor( passNode, texture ) {
  24263. super( texture );
  24264. /**
  24265. * A reference to the pass node.
  24266. *
  24267. * @type {PassNode}
  24268. */
  24269. this.passNode = passNode;
  24270. this.setUpdateMatrix( false );
  24271. }
  24272. setup( builder ) {
  24273. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  24274. return super.setup( builder );
  24275. }
  24276. clone() {
  24277. return new this.constructor( this.passNode, this.value );
  24278. }
  24279. }
  24280. /**
  24281. * An extension of `PassTextureNode` which allows to manage more than one
  24282. * internal texture. Relevant for the `getPreviousTexture()` related API.
  24283. *
  24284. * @augments PassTextureNode
  24285. */
  24286. class PassMultipleTextureNode extends PassTextureNode {
  24287. static get type() {
  24288. return 'PassMultipleTextureNode';
  24289. }
  24290. /**
  24291. * Constructs a new pass texture node.
  24292. *
  24293. * @param {PassNode} passNode - The pass node.
  24294. * @param {string} textureName - The output texture name.
  24295. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  24296. */
  24297. constructor( passNode, textureName, previousTexture = false ) {
  24298. // null is passed to the super call since this class does not
  24299. // use an external texture for rendering pass data into. Instead
  24300. // the texture is managed by the pass node itself
  24301. super( passNode, null );
  24302. /**
  24303. * The output texture name.
  24304. *
  24305. * @type {string}
  24306. */
  24307. this.textureName = textureName;
  24308. /**
  24309. * Whether previous frame data should be used or not.
  24310. *
  24311. * @type {boolean}
  24312. */
  24313. this.previousTexture = previousTexture;
  24314. }
  24315. /**
  24316. * Updates the texture reference of this node.
  24317. */
  24318. updateTexture() {
  24319. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  24320. }
  24321. setup( builder ) {
  24322. this.updateTexture();
  24323. return super.setup( builder );
  24324. }
  24325. clone() {
  24326. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  24327. }
  24328. }
  24329. /**
  24330. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  24331. * This pass produces a render for the given scene and camera and can provide multiple outputs
  24332. * via MRT for further processing.
  24333. *
  24334. * ```js
  24335. * const postProcessing = new PostProcessing( renderer );
  24336. *
  24337. * const scenePass = pass( scene, camera );
  24338. *
  24339. * postProcessing.outputNode = scenePass;
  24340. * ```
  24341. *
  24342. * @augments TempNode
  24343. */
  24344. class PassNode extends TempNode {
  24345. static get type() {
  24346. return 'PassNode';
  24347. }
  24348. /**
  24349. * Constructs a new pass node.
  24350. *
  24351. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  24352. * @param {Scene} scene - A reference to the scene.
  24353. * @param {Camera} camera - A reference to the camera.
  24354. * @param {Object} options - Options for the internal render target.
  24355. */
  24356. constructor( scope, scene, camera, options = {} ) {
  24357. super( 'vec4' );
  24358. /**
  24359. * The scope of the pass. The scope determines whether the node outputs color or depth.
  24360. *
  24361. * @type {('color'|'depth')}
  24362. */
  24363. this.scope = scope;
  24364. /**
  24365. * A reference to the scene.
  24366. *
  24367. * @type {Scene}
  24368. */
  24369. this.scene = scene;
  24370. /**
  24371. * A reference to the camera.
  24372. *
  24373. * @type {Camera}
  24374. */
  24375. this.camera = camera;
  24376. /**
  24377. * Options for the internal render target.
  24378. *
  24379. * @type {Object}
  24380. */
  24381. this.options = options;
  24382. /**
  24383. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  24384. *
  24385. * @private
  24386. * @type {number}
  24387. * @default 1
  24388. */
  24389. this._pixelRatio = 1;
  24390. /**
  24391. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  24392. * @private
  24393. * @type {number}
  24394. * @default 1
  24395. */
  24396. this._width = 1;
  24397. /**
  24398. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  24399. * @private
  24400. * @type {number}
  24401. * @default 1
  24402. */
  24403. this._height = 1;
  24404. const depthTexture = new DepthTexture();
  24405. depthTexture.isRenderTargetTexture = true;
  24406. //depthTexture.type = FloatType;
  24407. depthTexture.name = 'depth';
  24408. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  24409. renderTarget.texture.name = 'output';
  24410. renderTarget.depthTexture = depthTexture;
  24411. /**
  24412. * The pass's render target.
  24413. *
  24414. * @type {RenderTarget}
  24415. */
  24416. this.renderTarget = renderTarget;
  24417. /**
  24418. * A dictionary holding the internal result textures.
  24419. *
  24420. * @private
  24421. * @type {Object<string, Texture>}
  24422. */
  24423. this._textures = {
  24424. output: renderTarget.texture,
  24425. depth: depthTexture
  24426. };
  24427. /**
  24428. * A dictionary holding the internal texture nodes.
  24429. *
  24430. * @private
  24431. * @type {Object<string, TextureNode>}
  24432. */
  24433. this._textureNodes = {};
  24434. /**
  24435. * A dictionary holding the internal depth nodes.
  24436. *
  24437. * @private
  24438. * @type {Object}
  24439. */
  24440. this._linearDepthNodes = {};
  24441. /**
  24442. * A dictionary holding the internal viewZ nodes.
  24443. *
  24444. * @private
  24445. * @type {Object}
  24446. */
  24447. this._viewZNodes = {};
  24448. /**
  24449. * A dictionary holding the texture data of the previous frame.
  24450. * Used for computing velocity/motion vectors.
  24451. *
  24452. * @private
  24453. * @type {Object<string, Texture>}
  24454. */
  24455. this._previousTextures = {};
  24456. /**
  24457. * A dictionary holding the texture nodes of the previous frame.
  24458. * Used for computing velocity/motion vectors.
  24459. *
  24460. * @private
  24461. * @type {Object<string, TextureNode>}
  24462. */
  24463. this._previousTextureNodes = {};
  24464. /**
  24465. * The `near` property of the camera as a uniform.
  24466. *
  24467. * @private
  24468. * @type {UniformNode}
  24469. */
  24470. this._cameraNear = uniform( 0 );
  24471. /**
  24472. * The `far` property of the camera as a uniform.
  24473. *
  24474. * @private
  24475. * @type {UniformNode}
  24476. */
  24477. this._cameraFar = uniform( 0 );
  24478. /**
  24479. * A MRT node configuring the MRT settings.
  24480. *
  24481. * @private
  24482. * @type {?MRTNode}
  24483. * @default null
  24484. */
  24485. this._mrt = null;
  24486. this._layers = null;
  24487. this._resolution = 1;
  24488. /**
  24489. * This flag can be used for type testing.
  24490. *
  24491. * @type {boolean}
  24492. * @readonly
  24493. * @default true
  24494. */
  24495. this.isPassNode = true;
  24496. /**
  24497. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  24498. * scene once per frame in its {@link PassNode#updateBefore} method.
  24499. *
  24500. * @type {string}
  24501. * @default 'frame'
  24502. */
  24503. this.updateBeforeType = NodeUpdateType.FRAME;
  24504. /**
  24505. * This flag is used for global cache.
  24506. *
  24507. * @type {boolean}
  24508. * @default true
  24509. */
  24510. this.global = true;
  24511. }
  24512. /**
  24513. * Sets the resolution for the pass.
  24514. * The resolution is a factor that is multiplied with the renderer's width and height.
  24515. *
  24516. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  24517. * @return {PassNode} A reference to this pass.
  24518. */
  24519. setResolution( resolution ) {
  24520. this._resolution = resolution;
  24521. return this;
  24522. }
  24523. /**
  24524. * Gets the current resolution of the pass.
  24525. *
  24526. * @return {number} The current resolution. A value of `1` means full resolution.
  24527. * @default 1
  24528. */
  24529. getResolution() {
  24530. return this._resolution;
  24531. }
  24532. setLayers( layers ) {
  24533. this._layers = layers;
  24534. return this;
  24535. }
  24536. getLayers() {
  24537. return this._layers;
  24538. }
  24539. /**
  24540. * Sets the given MRT node to setup MRT for this pass.
  24541. *
  24542. * @param {MRTNode} mrt - The MRT object.
  24543. * @return {PassNode} A reference to this pass.
  24544. */
  24545. setMRT( mrt ) {
  24546. this._mrt = mrt;
  24547. return this;
  24548. }
  24549. /**
  24550. * Returns the current MRT node.
  24551. *
  24552. * @return {MRTNode} The current MRT node.
  24553. */
  24554. getMRT() {
  24555. return this._mrt;
  24556. }
  24557. /**
  24558. * Returns the texture for the given output name.
  24559. *
  24560. * @param {string} name - The output name to get the texture for.
  24561. * @return {Texture} The texture.
  24562. */
  24563. getTexture( name ) {
  24564. let texture = this._textures[ name ];
  24565. if ( texture === undefined ) {
  24566. const refTexture = this.renderTarget.texture;
  24567. texture = refTexture.clone();
  24568. texture.name = name;
  24569. this._textures[ name ] = texture;
  24570. this.renderTarget.textures.push( texture );
  24571. }
  24572. return texture;
  24573. }
  24574. /**
  24575. * Returns the texture holding the data of the previous frame for the given output name.
  24576. *
  24577. * @param {string} name - The output name to get the texture for.
  24578. * @return {Texture} The texture holding the data of the previous frame.
  24579. */
  24580. getPreviousTexture( name ) {
  24581. let texture = this._previousTextures[ name ];
  24582. if ( texture === undefined ) {
  24583. texture = this.getTexture( name ).clone();
  24584. this._previousTextures[ name ] = texture;
  24585. }
  24586. return texture;
  24587. }
  24588. /**
  24589. * Switches current and previous textures for the given output name.
  24590. *
  24591. * @param {string} name - The output name.
  24592. */
  24593. toggleTexture( name ) {
  24594. const prevTexture = this._previousTextures[ name ];
  24595. if ( prevTexture !== undefined ) {
  24596. const texture = this._textures[ name ];
  24597. const index = this.renderTarget.textures.indexOf( texture );
  24598. this.renderTarget.textures[ index ] = prevTexture;
  24599. this._textures[ name ] = prevTexture;
  24600. this._previousTextures[ name ] = texture;
  24601. this._textureNodes[ name ].updateTexture();
  24602. this._previousTextureNodes[ name ].updateTexture();
  24603. }
  24604. }
  24605. /**
  24606. * Returns the texture node for the given output name.
  24607. *
  24608. * @param {string} [name='output'] - The output name to get the texture node for.
  24609. * @return {TextureNode} The texture node.
  24610. */
  24611. getTextureNode( name = 'output' ) {
  24612. let textureNode = this._textureNodes[ name ];
  24613. if ( textureNode === undefined ) {
  24614. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  24615. textureNode.updateTexture();
  24616. this._textureNodes[ name ] = textureNode;
  24617. }
  24618. return textureNode;
  24619. }
  24620. /**
  24621. * Returns the previous texture node for the given output name.
  24622. *
  24623. * @param {string} [name='output'] - The output name to get the previous texture node for.
  24624. * @return {TextureNode} The previous texture node.
  24625. */
  24626. getPreviousTextureNode( name = 'output' ) {
  24627. let textureNode = this._previousTextureNodes[ name ];
  24628. if ( textureNode === undefined ) {
  24629. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  24630. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  24631. textureNode.updateTexture();
  24632. this._previousTextureNodes[ name ] = textureNode;
  24633. }
  24634. return textureNode;
  24635. }
  24636. /**
  24637. * Returns a viewZ node of this pass.
  24638. *
  24639. * @param {string} [name='depth'] - The output name to get the viewZ node for. In most cases the default `'depth'` can be used however the parameter exists for custom depth outputs.
  24640. * @return {Node} The viewZ node.
  24641. */
  24642. getViewZNode( name = 'depth' ) {
  24643. let viewZNode = this._viewZNodes[ name ];
  24644. if ( viewZNode === undefined ) {
  24645. const cameraNear = this._cameraNear;
  24646. const cameraFar = this._cameraFar;
  24647. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  24648. }
  24649. return viewZNode;
  24650. }
  24651. /**
  24652. * Returns a linear depth node of this pass.
  24653. *
  24654. * @param {string} [name='depth'] - The output name to get the linear depth node for. In most cases the default `'depth'` can be used however the parameter exists for custom depth outputs.
  24655. * @return {Node} The linear depth node.
  24656. */
  24657. getLinearDepthNode( name = 'depth' ) {
  24658. let linearDepthNode = this._linearDepthNodes[ name ];
  24659. if ( linearDepthNode === undefined ) {
  24660. const cameraNear = this._cameraNear;
  24661. const cameraFar = this._cameraFar;
  24662. const viewZNode = this.getViewZNode( name );
  24663. // TODO: just if ( builder.camera.isPerspectiveCamera )
  24664. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  24665. }
  24666. return linearDepthNode;
  24667. }
  24668. setup( { renderer } ) {
  24669. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  24670. // TODO: Disable MSAA for WebGL backend for now
  24671. if ( renderer.backend.isWebGLBackend === true ) {
  24672. this.renderTarget.samples = 0;
  24673. }
  24674. this.renderTarget.texture.type = renderer.getColorBufferType();
  24675. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  24676. }
  24677. updateBefore( frame ) {
  24678. const { renderer } = frame;
  24679. const { scene } = this;
  24680. let camera;
  24681. let pixelRatio;
  24682. const outputRenderTarget = renderer.getOutputRenderTarget();
  24683. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  24684. pixelRatio = 1;
  24685. camera = renderer.xr.getCamera();
  24686. renderer.xr.updateCamera( camera );
  24687. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  24688. } else {
  24689. camera = this.camera;
  24690. pixelRatio = renderer.getPixelRatio();
  24691. renderer.getSize( _size );
  24692. }
  24693. this._pixelRatio = pixelRatio;
  24694. this.setSize( _size.width, _size.height );
  24695. const currentRenderTarget = renderer.getRenderTarget();
  24696. const currentMRT = renderer.getMRT();
  24697. const currentMask = camera.layers.mask;
  24698. this._cameraNear.value = camera.near;
  24699. this._cameraFar.value = camera.far;
  24700. if ( this._layers !== null ) {
  24701. camera.layers.mask = this._layers.mask;
  24702. }
  24703. for ( const name in this._previousTextures ) {
  24704. this.toggleTexture( name );
  24705. }
  24706. renderer.setRenderTarget( this.renderTarget );
  24707. renderer.setMRT( this._mrt );
  24708. renderer.render( scene, camera );
  24709. renderer.setRenderTarget( currentRenderTarget );
  24710. renderer.setMRT( currentMRT );
  24711. camera.layers.mask = currentMask;
  24712. }
  24713. /**
  24714. * Sets the size of the pass's render target. Honors the pixel ratio.
  24715. *
  24716. * @param {number} width - The width to set.
  24717. * @param {number} height - The height to set.
  24718. */
  24719. setSize( width, height ) {
  24720. this._width = width;
  24721. this._height = height;
  24722. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  24723. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  24724. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24725. }
  24726. /**
  24727. * Sets the pixel ratio the pass's render target and updates the size.
  24728. *
  24729. * @param {number} pixelRatio - The pixel ratio to set.
  24730. */
  24731. setPixelRatio( pixelRatio ) {
  24732. this._pixelRatio = pixelRatio;
  24733. this.setSize( this._width, this._height );
  24734. }
  24735. /**
  24736. * Frees internal resources. Should be called when the node is no longer in use.
  24737. */
  24738. dispose() {
  24739. this.renderTarget.dispose();
  24740. }
  24741. }
  24742. /**
  24743. * @static
  24744. * @type {'color'}
  24745. * @default 'color'
  24746. */
  24747. PassNode.COLOR = 'color';
  24748. /**
  24749. * @static
  24750. * @type {'depth'}
  24751. * @default 'depth'
  24752. */
  24753. PassNode.DEPTH = 'depth';
  24754. /**
  24755. * TSL function for creating a pass node.
  24756. *
  24757. * @tsl
  24758. * @function
  24759. * @param {Scene} scene - A reference to the scene.
  24760. * @param {Camera} camera - A reference to the camera.
  24761. * @param {Object} options - Options for the internal render target.
  24762. * @returns {PassNode}
  24763. */
  24764. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  24765. /**
  24766. * TSL function for creating a pass texture node.
  24767. *
  24768. * @tsl
  24769. * @function
  24770. * @param {PassNode} pass - The pass node.
  24771. * @param {Texture} texture - The output texture.
  24772. * @returns {PassTextureNode}
  24773. */
  24774. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  24775. /**
  24776. * TSL function for creating a depth pass node.
  24777. *
  24778. * @tsl
  24779. * @function
  24780. * @param {Scene} scene - A reference to the scene.
  24781. * @param {Camera} camera - A reference to the camera.
  24782. * @param {Object} options - Options for the internal render target.
  24783. * @returns {PassNode}
  24784. */
  24785. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  24786. /**
  24787. * Represents a render pass for producing a toon outline effect on compatible objects.
  24788. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  24789. * will receive the outline.
  24790. *
  24791. * ```js
  24792. * const postProcessing = new PostProcessing( renderer );
  24793. *
  24794. * const scenePass = toonOutlinePass( scene, camera );
  24795. *
  24796. * postProcessing.outputNode = scenePass;
  24797. * ```
  24798. * @augments PassNode
  24799. */
  24800. class ToonOutlinePassNode extends PassNode {
  24801. static get type() {
  24802. return 'ToonOutlinePassNode';
  24803. }
  24804. /**
  24805. * Constructs a new outline pass node.
  24806. *
  24807. * @param {Scene} scene - A reference to the scene.
  24808. * @param {Camera} camera - A reference to the camera.
  24809. * @param {Node} colorNode - Defines the outline's color.
  24810. * @param {Node} thicknessNode - Defines the outline's thickness.
  24811. * @param {Node} alphaNode - Defines the outline's alpha.
  24812. */
  24813. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  24814. super( PassNode.COLOR, scene, camera );
  24815. /**
  24816. * Defines the outline's color.
  24817. *
  24818. * @type {Node}
  24819. */
  24820. this.colorNode = colorNode;
  24821. /**
  24822. * Defines the outline's thickness.
  24823. *
  24824. * @type {Node}
  24825. */
  24826. this.thicknessNode = thicknessNode;
  24827. /**
  24828. * Defines the outline's alpha.
  24829. *
  24830. * @type {Node}
  24831. */
  24832. this.alphaNode = alphaNode;
  24833. /**
  24834. * An internal material cache.
  24835. *
  24836. * @private
  24837. * @type {WeakMap<Material, NodeMaterial>}
  24838. */
  24839. this._materialCache = new WeakMap();
  24840. }
  24841. updateBefore( frame ) {
  24842. const { renderer } = frame;
  24843. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  24844. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  24845. // only render outline for supported materials
  24846. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  24847. if ( material.wireframe === false ) {
  24848. const outlineMaterial = this._getOutlineMaterial( material );
  24849. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  24850. }
  24851. }
  24852. // default
  24853. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  24854. } );
  24855. super.updateBefore( frame );
  24856. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  24857. }
  24858. /**
  24859. * Creates the material used for outline rendering.
  24860. *
  24861. * @private
  24862. * @return {NodeMaterial} The outline material.
  24863. */
  24864. _createMaterial() {
  24865. const material = new NodeMaterial();
  24866. material.isMeshToonOutlineMaterial = true;
  24867. material.name = 'Toon_Outline';
  24868. material.side = BackSide;
  24869. // vertex node
  24870. const outlineNormal = normalLocal.negate();
  24871. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  24872. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  24873. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  24874. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  24875. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  24876. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  24877. // color node
  24878. material.colorNode = vec4( this.colorNode, this.alphaNode );
  24879. return material;
  24880. }
  24881. /**
  24882. * For the given toon material, this method returns a corresponding
  24883. * outline material.
  24884. *
  24885. * @private
  24886. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  24887. * @return {NodeMaterial} The outline material.
  24888. */
  24889. _getOutlineMaterial( originalMaterial ) {
  24890. let outlineMaterial = this._materialCache.get( originalMaterial );
  24891. if ( outlineMaterial === undefined ) {
  24892. outlineMaterial = this._createMaterial();
  24893. this._materialCache.set( originalMaterial, outlineMaterial );
  24894. }
  24895. return outlineMaterial;
  24896. }
  24897. }
  24898. /**
  24899. * TSL function for creating a toon outline pass node.
  24900. *
  24901. * @tsl
  24902. * @function
  24903. * @param {Scene} scene - A reference to the scene.
  24904. * @param {Camera} camera - A reference to the camera.
  24905. * @param {Color} color - Defines the outline's color.
  24906. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  24907. * @param {number} [alpha=1] - Defines the outline's alpha.
  24908. * @returns {ToonOutlinePassNode}
  24909. */
  24910. const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) );
  24911. /**
  24912. * Linear tone mapping, exposure only.
  24913. *
  24914. * @tsl
  24915. * @function
  24916. * @param {Node<vec3>} color - The color that should be tone mapped.
  24917. * @param {Node<float>} exposure - The exposure.
  24918. * @return {Node<vec3>} The tone mapped color.
  24919. */
  24920. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24921. return color.mul( exposure ).clamp();
  24922. } ).setLayout( {
  24923. name: 'linearToneMapping',
  24924. type: 'vec3',
  24925. inputs: [
  24926. { name: 'color', type: 'vec3' },
  24927. { name: 'exposure', type: 'float' }
  24928. ]
  24929. } );
  24930. /**
  24931. * Reinhard tone mapping.
  24932. *
  24933. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  24934. *
  24935. * @tsl
  24936. * @function
  24937. * @param {Node<vec3>} color - The color that should be tone mapped.
  24938. * @param {Node<float>} exposure - The exposure.
  24939. * @return {Node<vec3>} The tone mapped color.
  24940. */
  24941. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24942. color = color.mul( exposure );
  24943. return color.div( color.add( 1.0 ) ).clamp();
  24944. } ).setLayout( {
  24945. name: 'reinhardToneMapping',
  24946. type: 'vec3',
  24947. inputs: [
  24948. { name: 'color', type: 'vec3' },
  24949. { name: 'exposure', type: 'float' }
  24950. ]
  24951. } );
  24952. /**
  24953. * Cineon tone mapping.
  24954. *
  24955. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  24956. *
  24957. * @tsl
  24958. * @function
  24959. * @param {Node<vec3>} color - The color that should be tone mapped.
  24960. * @param {Node<float>} exposure - The exposure.
  24961. * @return {Node<vec3>} The tone mapped color.
  24962. */
  24963. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24964. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  24965. color = color.mul( exposure );
  24966. color = color.sub( 0.004 ).max( 0.0 );
  24967. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  24968. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  24969. return a.div( b ).pow( 2.2 );
  24970. } ).setLayout( {
  24971. name: 'cineonToneMapping',
  24972. type: 'vec3',
  24973. inputs: [
  24974. { name: 'color', type: 'vec3' },
  24975. { name: 'exposure', type: 'float' }
  24976. ]
  24977. } );
  24978. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  24979. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24980. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  24981. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  24982. return a.div( b );
  24983. } );
  24984. /**
  24985. * ACESFilmic tone mapping.
  24986. *
  24987. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  24988. *
  24989. * @tsl
  24990. * @function
  24991. * @param {Node<vec3>} color - The color that should be tone mapped.
  24992. * @param {Node<float>} exposure - The exposure.
  24993. * @return {Node<vec3>} The tone mapped color.
  24994. */
  24995. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24996. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  24997. const ACESInputMat = mat3(
  24998. 0.59719, 0.35458, 0.04823,
  24999. 0.07600, 0.90834, 0.01566,
  25000. 0.02840, 0.13383, 0.83777
  25001. );
  25002. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  25003. const ACESOutputMat = mat3(
  25004. 1.60475, -0.53108, -0.07367,
  25005. -0.10208, 1.10813, -605e-5,
  25006. -327e-5, -0.07276, 1.07602
  25007. );
  25008. color = color.mul( exposure ).div( 0.6 );
  25009. color = ACESInputMat.mul( color );
  25010. // Apply RRT and ODT
  25011. color = RRTAndODTFit( color );
  25012. color = ACESOutputMat.mul( color );
  25013. // Clamp to [0, 1]
  25014. return color.clamp();
  25015. } ).setLayout( {
  25016. name: 'acesFilmicToneMapping',
  25017. type: 'vec3',
  25018. inputs: [
  25019. { name: 'color', type: 'vec3' },
  25020. { name: 'exposure', type: 'float' }
  25021. ]
  25022. } );
  25023. const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, -0.1246, -0.0182 ), vec3( -0.5876, 1.1329, -0.1006 ), vec3( -0.0728, -83e-4, 1.1187 ) );
  25024. const LINEAR_SRGB_TO_LINEAR_REC2020 = /*@__PURE__*/ mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) );
  25025. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  25026. const x = vec3( x_immutable ).toVar();
  25027. const x2 = vec3( x.mul( x ) ).toVar();
  25028. const x4 = vec3( x2.mul( x2 ) ).toVar();
  25029. return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) );
  25030. } );
  25031. /**
  25032. * AgX tone mapping.
  25033. *
  25034. * @tsl
  25035. * @function
  25036. * @param {Node<vec3>} color - The color that should be tone mapped.
  25037. * @param {Node<float>} exposure - The exposure.
  25038. * @return {Node<vec3>} The tone mapped color.
  25039. */
  25040. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25041. const colortone = vec3( color ).toVar();
  25042. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  25043. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  25044. const AgxMinEv = float( -12.47393 );
  25045. const AgxMaxEv = float( 4.026069 );
  25046. colortone.mulAssign( exposure );
  25047. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  25048. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  25049. colortone.assign( max$1( colortone, 1e-10 ) );
  25050. colortone.assign( log2( colortone ) );
  25051. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  25052. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25053. colortone.assign( agxDefaultContrastApprox( colortone ) );
  25054. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  25055. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  25056. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  25057. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25058. return colortone;
  25059. } ).setLayout( {
  25060. name: 'agxToneMapping',
  25061. type: 'vec3',
  25062. inputs: [
  25063. { name: 'color', type: 'vec3' },
  25064. { name: 'exposure', type: 'float' }
  25065. ]
  25066. } );
  25067. /**
  25068. * Neutral tone mapping.
  25069. *
  25070. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  25071. *
  25072. * @tsl
  25073. * @function
  25074. * @param {Node<vec3>} color - The color that should be tone mapped.
  25075. * @param {Node<float>} exposure - The exposure.
  25076. * @return {Node<vec3>} The tone mapped color.
  25077. */
  25078. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25079. const StartCompression = float( 0.8 - 0.04 );
  25080. const Desaturation = float( 0.15 );
  25081. color = color.mul( exposure );
  25082. const x = min$1( color.r, min$1( color.g, color.b ) );
  25083. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  25084. color.subAssign( offset );
  25085. const peak = max$1( color.r, max$1( color.g, color.b ) );
  25086. If( peak.lessThan( StartCompression ), () => {
  25087. return color;
  25088. } );
  25089. const d = sub( 1, StartCompression );
  25090. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  25091. color.mulAssign( newPeak.div( peak ) );
  25092. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  25093. return mix( color, vec3( newPeak ), g );
  25094. } ).setLayout( {
  25095. name: 'neutralToneMapping',
  25096. type: 'vec3',
  25097. inputs: [
  25098. { name: 'color', type: 'vec3' },
  25099. { name: 'exposure', type: 'float' }
  25100. ]
  25101. } );
  25102. /**
  25103. * This class represents native code sections. It is the base
  25104. * class for modules like {@link FunctionNode} which allows to implement
  25105. * functions with native shader languages.
  25106. *
  25107. * @augments Node
  25108. */
  25109. class CodeNode extends Node {
  25110. static get type() {
  25111. return 'CodeNode';
  25112. }
  25113. /**
  25114. * Constructs a new code node.
  25115. *
  25116. * @param {string} [code=''] - The native code.
  25117. * @param {Array<Node>} [includes=[]] - An array of includes.
  25118. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25119. */
  25120. constructor( code = '', includes = [], language = '' ) {
  25121. super( 'code' );
  25122. /**
  25123. * This flag can be used for type testing.
  25124. *
  25125. * @type {boolean}
  25126. * @readonly
  25127. * @default true
  25128. */
  25129. this.isCodeNode = true;
  25130. /**
  25131. * This flag is used for global cache.
  25132. *
  25133. * @type {boolean}
  25134. * @default true
  25135. */
  25136. this.global = true;
  25137. /**
  25138. * The native code.
  25139. *
  25140. * @type {string}
  25141. * @default ''
  25142. */
  25143. this.code = code;
  25144. /**
  25145. * An array of includes
  25146. *
  25147. * @type {Array<Node>}
  25148. * @default []
  25149. */
  25150. this.includes = includes;
  25151. /**
  25152. * The used language.
  25153. *
  25154. * @type {('js'|'wgsl'|'glsl')}
  25155. * @default ''
  25156. */
  25157. this.language = language;
  25158. }
  25159. /**
  25160. * Sets the includes of this code node.
  25161. *
  25162. * @param {Array<Node>} includes - The includes to set.
  25163. * @return {CodeNode} A reference to this node.
  25164. */
  25165. setIncludes( includes ) {
  25166. this.includes = includes;
  25167. return this;
  25168. }
  25169. /**
  25170. * Returns the includes of this code node.
  25171. *
  25172. * @param {NodeBuilder} builder - The current node builder.
  25173. * @return {Array<Node>} The includes.
  25174. */
  25175. getIncludes( /*builder*/ ) {
  25176. return this.includes;
  25177. }
  25178. generate( builder ) {
  25179. const includes = this.getIncludes( builder );
  25180. for ( const include of includes ) {
  25181. include.build( builder );
  25182. }
  25183. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  25184. nodeCode.code = this.code;
  25185. return nodeCode.code;
  25186. }
  25187. serialize( data ) {
  25188. super.serialize( data );
  25189. data.code = this.code;
  25190. data.language = this.language;
  25191. }
  25192. deserialize( data ) {
  25193. super.deserialize( data );
  25194. this.code = data.code;
  25195. this.language = data.language;
  25196. }
  25197. }
  25198. /**
  25199. * TSL function for creating a code node.
  25200. *
  25201. * @tsl
  25202. * @function
  25203. * @param {string} [code] - The native code.
  25204. * @param {?Array<Node>} [includes=[]] - An array of includes.
  25205. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25206. * @returns {CodeNode}
  25207. */
  25208. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  25209. /**
  25210. * TSL function for creating a JS code node.
  25211. *
  25212. * @tsl
  25213. * @function
  25214. * @param {string} src - The native code.
  25215. * @param {Array<Node>} includes - An array of includes.
  25216. * @returns {CodeNode}
  25217. */
  25218. const js = ( src, includes ) => code( src, includes, 'js' );
  25219. /**
  25220. * TSL function for creating a WGSL code node.
  25221. *
  25222. * @tsl
  25223. * @function
  25224. * @param {string} src - The native code.
  25225. * @param {Array<Node>} includes - An array of includes.
  25226. * @returns {CodeNode}
  25227. */
  25228. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  25229. /**
  25230. * TSL function for creating a GLSL code node.
  25231. *
  25232. * @tsl
  25233. * @function
  25234. * @param {string} src - The native code.
  25235. * @param {Array<Node>} includes - An array of includes.
  25236. * @returns {CodeNode}
  25237. */
  25238. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  25239. /**
  25240. * This class represents a native shader function. It can be used to implement
  25241. * certain aspects of a node material with native shader code. There are two predefined
  25242. * TSL functions for easier usage.
  25243. *
  25244. * - `wgslFn`: Creates a WGSL function node.
  25245. * - `glslFn`: Creates a GLSL function node.
  25246. *
  25247. * A basic example with one include looks like so:
  25248. *
  25249. * ```js
  25250. * const desaturateWGSLFn = wgslFn( `
  25251. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  25252. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  25253. * return vec3<f32>( dot( lum, color ) );
  25254. * }`
  25255. *);
  25256. * const someWGSLFn = wgslFn( `
  25257. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  25258. * return desaturate( color );
  25259. * }
  25260. * `, [ desaturateWGSLFn ] );
  25261. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  25262. *```
  25263. * @augments CodeNode
  25264. */
  25265. class FunctionNode extends CodeNode {
  25266. static get type() {
  25267. return 'FunctionNode';
  25268. }
  25269. /**
  25270. * Constructs a new function node.
  25271. *
  25272. * @param {string} [code=''] - The native code.
  25273. * @param {Array<Node>} [includes=[]] - An array of includes.
  25274. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25275. */
  25276. constructor( code = '', includes = [], language = '' ) {
  25277. super( code, includes, language );
  25278. }
  25279. getNodeType( builder ) {
  25280. return this.getNodeFunction( builder ).type;
  25281. }
  25282. /**
  25283. * Returns the inputs of this function node.
  25284. *
  25285. * @param {NodeBuilder} builder - The current node builder.
  25286. * @return {Array<NodeFunctionInput>} The inputs.
  25287. */
  25288. getInputs( builder ) {
  25289. return this.getNodeFunction( builder ).inputs;
  25290. }
  25291. /**
  25292. * Returns the node function for this function node.
  25293. *
  25294. * @param {NodeBuilder} builder - The current node builder.
  25295. * @return {NodeFunction} The node function.
  25296. */
  25297. getNodeFunction( builder ) {
  25298. const nodeData = builder.getDataFromNode( this );
  25299. let nodeFunction = nodeData.nodeFunction;
  25300. if ( nodeFunction === undefined ) {
  25301. nodeFunction = builder.parser.parseFunction( this.code );
  25302. nodeData.nodeFunction = nodeFunction;
  25303. }
  25304. return nodeFunction;
  25305. }
  25306. generate( builder, output ) {
  25307. super.generate( builder );
  25308. const nodeFunction = this.getNodeFunction( builder );
  25309. const name = nodeFunction.name;
  25310. const type = nodeFunction.type;
  25311. const nodeCode = builder.getCodeFromNode( this, type );
  25312. if ( name !== '' ) {
  25313. // use a custom property name
  25314. nodeCode.name = name;
  25315. }
  25316. const propertyName = builder.getPropertyName( nodeCode );
  25317. const code = this.getNodeFunction( builder ).getCode( propertyName );
  25318. nodeCode.code = code + '\n';
  25319. if ( output === 'property' ) {
  25320. return propertyName;
  25321. } else {
  25322. return builder.format( `${ propertyName }()`, type, output );
  25323. }
  25324. }
  25325. }
  25326. const nativeFn = ( code, includes = [], language = '' ) => {
  25327. for ( let i = 0; i < includes.length; i ++ ) {
  25328. const include = includes[ i ];
  25329. // TSL Function: glslFn, wgslFn
  25330. if ( typeof include === 'function' ) {
  25331. includes[ i ] = include.functionNode;
  25332. }
  25333. }
  25334. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  25335. const fn = ( ...params ) => functionNode.call( ...params );
  25336. fn.functionNode = functionNode;
  25337. return fn;
  25338. };
  25339. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  25340. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  25341. /**
  25342. * `ScriptableNode` uses this class to manage script inputs and outputs.
  25343. *
  25344. * @augments Node
  25345. */
  25346. class ScriptableValueNode extends Node {
  25347. static get type() {
  25348. return 'ScriptableValueNode';
  25349. }
  25350. /**
  25351. * Constructs a new scriptable node.
  25352. *
  25353. * @param {any} [value=null] - The value.
  25354. */
  25355. constructor( value = null ) {
  25356. super();
  25357. /**
  25358. * A reference to the value.
  25359. *
  25360. * @private
  25361. * @default null
  25362. */
  25363. this._value = value;
  25364. /**
  25365. * Depending on the type of `_value`, this property might cache parsed data.
  25366. *
  25367. * @private
  25368. * @default null
  25369. */
  25370. this._cache = null;
  25371. /**
  25372. * If this node represents an input, this property represents the input type.
  25373. *
  25374. * @type {?string}
  25375. * @default null
  25376. */
  25377. this.inputType = null;
  25378. /**
  25379. * If this node represents an output, this property represents the output type.
  25380. *
  25381. * @type {?string}
  25382. * @default null
  25383. */
  25384. this.outputType = null;
  25385. /**
  25386. * An event dispatcher for managing events.
  25387. *
  25388. * @type {EventDispatcher}
  25389. */
  25390. this.events = new EventDispatcher();
  25391. /**
  25392. * This flag can be used for type testing.
  25393. *
  25394. * @type {boolean}
  25395. * @readonly
  25396. * @default true
  25397. */
  25398. this.isScriptableValueNode = true;
  25399. }
  25400. /**
  25401. * Whether this node represents an output or not.
  25402. *
  25403. * @type {boolean}
  25404. * @readonly
  25405. * @default true
  25406. */
  25407. get isScriptableOutputNode() {
  25408. return this.outputType !== null;
  25409. }
  25410. set value( val ) {
  25411. if ( this._value === val ) return;
  25412. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  25413. URL.revokeObjectURL( this._cache );
  25414. this._cache = null;
  25415. }
  25416. this._value = val;
  25417. this.events.dispatchEvent( { type: 'change' } );
  25418. this.refresh();
  25419. }
  25420. /**
  25421. * The node's value.
  25422. *
  25423. * @type {any}
  25424. */
  25425. get value() {
  25426. return this._value;
  25427. }
  25428. /**
  25429. * Dispatches the `refresh` event.
  25430. */
  25431. refresh() {
  25432. this.events.dispatchEvent( { type: 'refresh' } );
  25433. }
  25434. /**
  25435. * The `value` property usually represents a node or even binary data in form of array buffers.
  25436. * In this case, this method tries to return the actual value behind the complex type.
  25437. *
  25438. * @return {any} The value.
  25439. */
  25440. getValue() {
  25441. const value = this.value;
  25442. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  25443. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  25444. } else if ( value && value.value !== null && value.value !== undefined && (
  25445. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  25446. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  25447. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  25448. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  25449. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  25450. ( this.inputType === 'Color' && value.value.isColor ) ||
  25451. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  25452. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  25453. ) ) {
  25454. return value.value;
  25455. }
  25456. return this._cache || value;
  25457. }
  25458. /**
  25459. * Overwritten since the node type is inferred from the value.
  25460. *
  25461. * @param {NodeBuilder} builder - The current node builder.
  25462. * @return {string} The node type.
  25463. */
  25464. getNodeType( builder ) {
  25465. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  25466. }
  25467. setup() {
  25468. return this.value && this.value.isNode ? this.value : float();
  25469. }
  25470. serialize( data ) {
  25471. super.serialize( data );
  25472. if ( this.value !== null ) {
  25473. if ( this.inputType === 'ArrayBuffer' ) {
  25474. data.value = arrayBufferToBase64( this.value );
  25475. } else {
  25476. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  25477. }
  25478. } else {
  25479. data.value = null;
  25480. }
  25481. data.inputType = this.inputType;
  25482. data.outputType = this.outputType;
  25483. }
  25484. deserialize( data ) {
  25485. super.deserialize( data );
  25486. let value = null;
  25487. if ( data.value !== null ) {
  25488. if ( data.inputType === 'ArrayBuffer' ) {
  25489. value = base64ToArrayBuffer( data.value );
  25490. } else if ( data.inputType === 'Texture' ) {
  25491. value = data.meta.textures[ data.value ];
  25492. } else {
  25493. value = data.meta.nodes[ data.value ] || null;
  25494. }
  25495. }
  25496. this.value = value;
  25497. this.inputType = data.inputType;
  25498. this.outputType = data.outputType;
  25499. }
  25500. }
  25501. /**
  25502. * TSL function for creating a scriptable value node.
  25503. *
  25504. * @tsl
  25505. * @function
  25506. * @param {any} [value] - The value.
  25507. * @returns {ScriptableValueNode}
  25508. */
  25509. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  25510. /**
  25511. * A Map-like data structure for managing resources of scriptable nodes.
  25512. *
  25513. * @augments Map
  25514. */
  25515. class Resources extends Map {
  25516. get( key, callback = null, ...params ) {
  25517. if ( this.has( key ) ) return super.get( key );
  25518. if ( callback !== null ) {
  25519. const value = callback( ...params );
  25520. this.set( key, value );
  25521. return value;
  25522. }
  25523. }
  25524. }
  25525. class Parameters {
  25526. constructor( scriptableNode ) {
  25527. this.scriptableNode = scriptableNode;
  25528. }
  25529. get parameters() {
  25530. return this.scriptableNode.parameters;
  25531. }
  25532. get layout() {
  25533. return this.scriptableNode.getLayout();
  25534. }
  25535. getInputLayout( id ) {
  25536. return this.scriptableNode.getInputLayout( id );
  25537. }
  25538. get( name ) {
  25539. const param = this.parameters[ name ];
  25540. const value = param ? param.getValue() : null;
  25541. return value;
  25542. }
  25543. }
  25544. /**
  25545. * Defines the resources (e.g. namespaces) of scriptable nodes.
  25546. *
  25547. * @type {Resources}
  25548. */
  25549. const ScriptableNodeResources = new Resources();
  25550. /**
  25551. * This type of node allows to implement nodes with custom scripts. The script
  25552. * section is represented as an instance of `CodeNode` written with JavaScript.
  25553. * The script itself must adhere to a specific structure.
  25554. *
  25555. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  25556. * - layout: The layout object defines the script's interface (inputs and outputs).
  25557. *
  25558. * ```js
  25559. * ScriptableNodeResources.set( 'TSL', TSL );
  25560. *
  25561. * const scriptableNode = scriptable( js( `
  25562. * layout = {
  25563. * outputType: 'node',
  25564. * elements: [
  25565. * { name: 'source', inputType: 'node' },
  25566. * ]
  25567. * };
  25568. *
  25569. * const { mul, oscSine } = TSL;
  25570. *
  25571. * function main() {
  25572. * const source = parameters.get( 'source' ) || float();
  25573. * return mul( source, oscSine() ) );
  25574. * }
  25575. *
  25576. * ` ) );
  25577. *
  25578. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  25579. *
  25580. * const material = new THREE.MeshBasicNodeMaterial();
  25581. * material.colorNode = scriptableNode;
  25582. * ```
  25583. *
  25584. * @augments Node
  25585. */
  25586. class ScriptableNode extends Node {
  25587. static get type() {
  25588. return 'ScriptableNode';
  25589. }
  25590. /**
  25591. * Constructs a new scriptable node.
  25592. *
  25593. * @param {?CodeNode} [codeNode=null] - The code node.
  25594. * @param {Object} [parameters={}] - The parameters definition.
  25595. */
  25596. constructor( codeNode = null, parameters = {} ) {
  25597. super();
  25598. /**
  25599. * The code node.
  25600. *
  25601. * @type {?CodeNode}
  25602. * @default null
  25603. */
  25604. this.codeNode = codeNode;
  25605. /**
  25606. * The parameters definition.
  25607. *
  25608. * @type {Object}
  25609. * @default {}
  25610. */
  25611. this.parameters = parameters;
  25612. this._local = new Resources();
  25613. this._output = scriptableValue( null );
  25614. this._outputs = {};
  25615. this._source = this.source;
  25616. this._method = null;
  25617. this._object = null;
  25618. this._value = null;
  25619. this._needsOutputUpdate = true;
  25620. this.onRefresh = this.onRefresh.bind( this );
  25621. /**
  25622. * This flag can be used for type testing.
  25623. *
  25624. * @type {boolean}
  25625. * @readonly
  25626. * @default true
  25627. */
  25628. this.isScriptableNode = true;
  25629. }
  25630. /**
  25631. * The source code of the scriptable node.
  25632. *
  25633. * @type {string}
  25634. */
  25635. get source() {
  25636. return this.codeNode ? this.codeNode.code : '';
  25637. }
  25638. /**
  25639. * Sets the reference of a local script variable.
  25640. *
  25641. * @param {string} name - The variable name.
  25642. * @param {Object} value - The reference to set.
  25643. * @return {Resources} The resource map
  25644. */
  25645. setLocal( name, value ) {
  25646. return this._local.set( name, value );
  25647. }
  25648. /**
  25649. * Gets the value of a local script variable.
  25650. *
  25651. * @param {string} name - The variable name.
  25652. * @return {Object} The value.
  25653. */
  25654. getLocal( name ) {
  25655. return this._local.get( name );
  25656. }
  25657. /**
  25658. * Event listener for the `refresh` event.
  25659. */
  25660. onRefresh() {
  25661. this._refresh();
  25662. }
  25663. /**
  25664. * Returns an input from the layout with the given id/name.
  25665. *
  25666. * @param {string} id - The id/name of the input.
  25667. * @return {Object} The element entry.
  25668. */
  25669. getInputLayout( id ) {
  25670. for ( const element of this.getLayout() ) {
  25671. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  25672. return element;
  25673. }
  25674. }
  25675. }
  25676. /**
  25677. * Returns an output from the layout with the given id/name.
  25678. *
  25679. * @param {string} id - The id/name of the output.
  25680. * @return {Object} The element entry.
  25681. */
  25682. getOutputLayout( id ) {
  25683. for ( const element of this.getLayout() ) {
  25684. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  25685. return element;
  25686. }
  25687. }
  25688. }
  25689. /**
  25690. * Defines a script output for the given name and value.
  25691. *
  25692. * @param {string} name - The name of the output.
  25693. * @param {Node} value - The node value.
  25694. * @return {ScriptableNode} A reference to this node.
  25695. */
  25696. setOutput( name, value ) {
  25697. const outputs = this._outputs;
  25698. if ( outputs[ name ] === undefined ) {
  25699. outputs[ name ] = scriptableValue( value );
  25700. } else {
  25701. outputs[ name ].value = value;
  25702. }
  25703. return this;
  25704. }
  25705. /**
  25706. * Returns a script output for the given name.
  25707. *
  25708. * @param {string} name - The name of the output.
  25709. * @return {ScriptableValueNode} The node value.
  25710. */
  25711. getOutput( name ) {
  25712. return this._outputs[ name ];
  25713. }
  25714. /**
  25715. * Returns a parameter for the given name
  25716. *
  25717. * @param {string} name - The name of the parameter.
  25718. * @return {ScriptableValueNode} The node value.
  25719. */
  25720. getParameter( name ) {
  25721. return this.parameters[ name ];
  25722. }
  25723. /**
  25724. * Sets a value for the given parameter name.
  25725. *
  25726. * @param {string} name - The parameter name.
  25727. * @param {any} value - The parameter value.
  25728. * @return {ScriptableNode} A reference to this node.
  25729. */
  25730. setParameter( name, value ) {
  25731. const parameters = this.parameters;
  25732. if ( value && value.isScriptableNode ) {
  25733. this.deleteParameter( name );
  25734. parameters[ name ] = value;
  25735. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  25736. } else if ( value && value.isScriptableValueNode ) {
  25737. this.deleteParameter( name );
  25738. parameters[ name ] = value;
  25739. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  25740. } else if ( parameters[ name ] === undefined ) {
  25741. parameters[ name ] = scriptableValue( value );
  25742. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  25743. } else {
  25744. parameters[ name ].value = value;
  25745. }
  25746. return this;
  25747. }
  25748. /**
  25749. * Returns the value of this node which is the value of
  25750. * the default output.
  25751. *
  25752. * @return {Node} The value.
  25753. */
  25754. getValue() {
  25755. return this.getDefaultOutput().getValue();
  25756. }
  25757. /**
  25758. * Deletes a parameter from the script.
  25759. *
  25760. * @param {string} name - The parameter to remove.
  25761. * @return {ScriptableNode} A reference to this node.
  25762. */
  25763. deleteParameter( name ) {
  25764. let valueNode = this.parameters[ name ];
  25765. if ( valueNode ) {
  25766. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  25767. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  25768. }
  25769. return this;
  25770. }
  25771. /**
  25772. * Deletes all parameters from the script.
  25773. *
  25774. * @return {ScriptableNode} A reference to this node.
  25775. */
  25776. clearParameters() {
  25777. for ( const name of Object.keys( this.parameters ) ) {
  25778. this.deleteParameter( name );
  25779. }
  25780. this.needsUpdate = true;
  25781. return this;
  25782. }
  25783. /**
  25784. * Calls a function from the script.
  25785. *
  25786. * @param {string} name - The function name.
  25787. * @param {...any} params - A list of parameters.
  25788. * @return {any} The result of the function call.
  25789. */
  25790. call( name, ...params ) {
  25791. const object = this.getObject();
  25792. const method = object[ name ];
  25793. if ( typeof method === 'function' ) {
  25794. return method( ...params );
  25795. }
  25796. }
  25797. /**
  25798. * Asynchronously calls a function from the script.
  25799. *
  25800. * @param {string} name - The function name.
  25801. * @param {...any} params - A list of parameters.
  25802. * @return {Promise<any>} The result of the function call.
  25803. */
  25804. async callAsync( name, ...params ) {
  25805. const object = this.getObject();
  25806. const method = object[ name ];
  25807. if ( typeof method === 'function' ) {
  25808. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  25809. }
  25810. }
  25811. /**
  25812. * Overwritten since the node types is inferred from the script's output.
  25813. *
  25814. * @param {NodeBuilder} builder - The current node builder
  25815. * @return {string} The node type.
  25816. */
  25817. getNodeType( builder ) {
  25818. return this.getDefaultOutputNode().getNodeType( builder );
  25819. }
  25820. /**
  25821. * Refreshes the script node.
  25822. *
  25823. * @param {?string} [output=null] - An optional output.
  25824. */
  25825. refresh( output = null ) {
  25826. if ( output !== null ) {
  25827. this.getOutput( output ).refresh();
  25828. } else {
  25829. this._refresh();
  25830. }
  25831. }
  25832. /**
  25833. * Returns an object representation of the script.
  25834. *
  25835. * @return {Object} The result object.
  25836. */
  25837. getObject() {
  25838. if ( this.needsUpdate ) this.dispose();
  25839. if ( this._object !== null ) return this._object;
  25840. //
  25841. const refresh = () => this.refresh();
  25842. const setOutput = ( id, value ) => this.setOutput( id, value );
  25843. const parameters = new Parameters( this );
  25844. const THREE = ScriptableNodeResources.get( 'THREE' );
  25845. const TSL = ScriptableNodeResources.get( 'TSL' );
  25846. const method = this.getMethod();
  25847. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  25848. this._object = method( ...params );
  25849. const layout = this._object.layout;
  25850. if ( layout ) {
  25851. if ( layout.cache === false ) {
  25852. this._local.clear();
  25853. }
  25854. // default output
  25855. this._output.outputType = layout.outputType || null;
  25856. if ( Array.isArray( layout.elements ) ) {
  25857. for ( const element of layout.elements ) {
  25858. const id = element.id || element.name;
  25859. if ( element.inputType ) {
  25860. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  25861. this.getParameter( id ).inputType = element.inputType;
  25862. }
  25863. if ( element.outputType ) {
  25864. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  25865. this.getOutput( id ).outputType = element.outputType;
  25866. }
  25867. }
  25868. }
  25869. }
  25870. return this._object;
  25871. }
  25872. deserialize( data ) {
  25873. super.deserialize( data );
  25874. for ( const name in this.parameters ) {
  25875. let valueNode = this.parameters[ name ];
  25876. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  25877. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  25878. }
  25879. }
  25880. /**
  25881. * Returns the layout of the script.
  25882. *
  25883. * @return {Object} The script's layout.
  25884. */
  25885. getLayout() {
  25886. return this.getObject().layout;
  25887. }
  25888. /**
  25889. * Returns default node output of the script.
  25890. *
  25891. * @return {Node} The default node output.
  25892. */
  25893. getDefaultOutputNode() {
  25894. const output = this.getDefaultOutput().value;
  25895. if ( output && output.isNode ) {
  25896. return output;
  25897. }
  25898. return float();
  25899. }
  25900. /**
  25901. * Returns default output of the script.
  25902. *
  25903. * @return {ScriptableValueNode} The default output.
  25904. */
  25905. getDefaultOutput() {
  25906. return this._exec()._output;
  25907. }
  25908. /**
  25909. * Returns a function created from the node's script.
  25910. *
  25911. * @return {Function} The function representing the node's code.
  25912. */
  25913. getMethod() {
  25914. if ( this.needsUpdate ) this.dispose();
  25915. if ( this._method !== null ) return this._method;
  25916. //
  25917. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  25918. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  25919. const properties = interfaceProps.join( ', ' );
  25920. const declarations = 'var ' + properties + '; var output = {};\n';
  25921. const returns = '\nreturn { ...output, ' + properties + ' };';
  25922. const code = declarations + this.codeNode.code + returns;
  25923. //
  25924. this._method = new Function( ...parametersProps, code );
  25925. return this._method;
  25926. }
  25927. /**
  25928. * Frees all internal resources.
  25929. */
  25930. dispose() {
  25931. if ( this._method === null ) return;
  25932. if ( this._object && typeof this._object.dispose === 'function' ) {
  25933. this._object.dispose();
  25934. }
  25935. this._method = null;
  25936. this._object = null;
  25937. this._source = null;
  25938. this._value = null;
  25939. this._needsOutputUpdate = true;
  25940. this._output.value = null;
  25941. this._outputs = {};
  25942. }
  25943. setup() {
  25944. return this.getDefaultOutputNode();
  25945. }
  25946. getCacheKey( force ) {
  25947. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  25948. for ( const param in this.parameters ) {
  25949. values.push( this.parameters[ param ].getCacheKey( force ) );
  25950. }
  25951. return hashArray( values );
  25952. }
  25953. set needsUpdate( value ) {
  25954. if ( value === true ) this.dispose();
  25955. }
  25956. get needsUpdate() {
  25957. return this.source !== this._source;
  25958. }
  25959. /**
  25960. * Executes the `main` function of the script.
  25961. *
  25962. * @private
  25963. * @return {ScriptableNode} A reference to this node.
  25964. */
  25965. _exec() {
  25966. if ( this.codeNode === null ) return this;
  25967. if ( this._needsOutputUpdate === true ) {
  25968. this._value = this.call( 'main' );
  25969. this._needsOutputUpdate = false;
  25970. }
  25971. this._output.value = this._value;
  25972. return this;
  25973. }
  25974. /**
  25975. * Executes the refresh.
  25976. *
  25977. * @private
  25978. */
  25979. _refresh() {
  25980. this.needsUpdate = true;
  25981. this._exec();
  25982. this._output.refresh();
  25983. }
  25984. }
  25985. /**
  25986. * TSL function for creating a scriptable node.
  25987. *
  25988. * @tsl
  25989. * @function
  25990. * @param {CodeNode} [codeNode] - The code node.
  25991. * @param {?Object} [parameters={}] - The parameters definition.
  25992. * @returns {ScriptableNode}
  25993. */
  25994. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  25995. /**
  25996. * Returns a node that represents the `z` coordinate in view space
  25997. * for the current fragment. It's a different representation of the
  25998. * default depth value.
  25999. *
  26000. * This value can be part of a computation that defines how the fog
  26001. * density increases when moving away from the camera.
  26002. *
  26003. * @param {NodeBuilder} builder - The current node builder.
  26004. * @return {Node} The viewZ node.
  26005. */
  26006. function getViewZNode( builder ) {
  26007. let viewZ;
  26008. const getViewZ = builder.context.getViewZ;
  26009. if ( getViewZ !== undefined ) {
  26010. viewZ = getViewZ( this );
  26011. }
  26012. return ( viewZ || positionView.z ).negate();
  26013. }
  26014. /**
  26015. * Constructs a new range factor node.
  26016. *
  26017. * @tsl
  26018. * @function
  26019. * @param {Node} near - Defines the near value.
  26020. * @param {Node} far - Defines the far value.
  26021. */
  26022. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  26023. const viewZ = getViewZNode( builder );
  26024. return smoothstep( near, far, viewZ );
  26025. } );
  26026. /**
  26027. * Represents an exponential squared fog. This type of fog gives
  26028. * a clear view near the camera and a faster than exponentially
  26029. * densening fog farther from the camera.
  26030. *
  26031. * @tsl
  26032. * @function
  26033. * @param {Node} density - Defines the fog density.
  26034. */
  26035. const densityFogFactor = Fn( ( [ density ], builder ) => {
  26036. const viewZ = getViewZNode( builder );
  26037. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  26038. } );
  26039. /**
  26040. * This class can be used to configure a fog for the scene.
  26041. * Nodes of this type are assigned to `Scene.fogNode`.
  26042. *
  26043. * @tsl
  26044. * @function
  26045. * @param {Node} color - Defines the color of the fog.
  26046. * @param {Node} factor - Defines how the fog is factored in the scene.
  26047. */
  26048. const fog = Fn( ( [ color, factor ] ) => {
  26049. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  26050. } );
  26051. // Deprecated
  26052. /**
  26053. * @tsl
  26054. * @function
  26055. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  26056. *
  26057. * @param {Node} color
  26058. * @param {Node} near
  26059. * @param {Node} far
  26060. * @returns {Function}
  26061. */
  26062. function rangeFog( color, near, far ) { // @deprecated, r171
  26063. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  26064. return fog( color, rangeFogFactor( near, far ) );
  26065. }
  26066. /**
  26067. * @tsl
  26068. * @function
  26069. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  26070. *
  26071. * @param {Node} color
  26072. * @param {Node} density
  26073. * @returns {Function}
  26074. */
  26075. function densityFog( color, density ) { // @deprecated, r171
  26076. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  26077. return fog( color, densityFogFactor( density ) );
  26078. }
  26079. let min = null;
  26080. let max = null;
  26081. /**
  26082. * `RangeNode` generates random instanced attribute data in a defined range.
  26083. * An exemplary use case for this utility node is to generate random per-instance
  26084. * colors:
  26085. * ```js
  26086. * const material = new MeshBasicNodeMaterial();
  26087. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  26088. * const mesh = new InstancedMesh( geometry, material, count );
  26089. * ```
  26090. * @augments Node
  26091. */
  26092. class RangeNode extends Node {
  26093. static get type() {
  26094. return 'RangeNode';
  26095. }
  26096. /**
  26097. * Constructs a new range node.
  26098. *
  26099. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  26100. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  26101. */
  26102. constructor( minNode = float(), maxNode = float() ) {
  26103. super();
  26104. /**
  26105. * A node defining the lower bound of the range.
  26106. *
  26107. * @type {Node<any>}
  26108. * @default float()
  26109. */
  26110. this.minNode = minNode;
  26111. /**
  26112. * A node defining the upper bound of the range.
  26113. *
  26114. * @type {Node<any>}
  26115. * @default float()
  26116. */
  26117. this.maxNode = maxNode;
  26118. }
  26119. /**
  26120. * Returns the vector length which is computed based on the range definition.
  26121. *
  26122. * @param {NodeBuilder} builder - The current node builder.
  26123. * @return {number} The vector length.
  26124. */
  26125. getVectorLength( builder ) {
  26126. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  26127. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  26128. return minLength > maxLength ? minLength : maxLength;
  26129. }
  26130. /**
  26131. * This method is overwritten since the node type is inferred from range definition.
  26132. *
  26133. * @param {NodeBuilder} builder - The current node builder.
  26134. * @return {string} The node type.
  26135. */
  26136. getNodeType( builder ) {
  26137. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  26138. }
  26139. setup( builder ) {
  26140. const object = builder.object;
  26141. let output = null;
  26142. if ( object.count > 1 ) {
  26143. const minValue = this.minNode.value;
  26144. const maxValue = this.maxNode.value;
  26145. const minLength = builder.getTypeLength( getValueType( minValue ) );
  26146. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  26147. min = min || new Vector4();
  26148. max = max || new Vector4();
  26149. min.setScalar( 0 );
  26150. max.setScalar( 0 );
  26151. if ( minLength === 1 ) min.setScalar( minValue );
  26152. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  26153. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  26154. if ( maxLength === 1 ) max.setScalar( maxValue );
  26155. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  26156. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  26157. const stride = 4;
  26158. const length = stride * object.count;
  26159. const array = new Float32Array( length );
  26160. for ( let i = 0; i < length; i ++ ) {
  26161. const index = i % stride;
  26162. const minElementValue = min.getComponent( index );
  26163. const maxElementValue = max.getComponent( index );
  26164. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  26165. }
  26166. const nodeType = this.getNodeType( builder );
  26167. if ( object.count <= 4096 ) {
  26168. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  26169. } else {
  26170. // TODO: Improve anonymous buffer attribute creation removing this part
  26171. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  26172. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  26173. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  26174. }
  26175. } else {
  26176. output = float( 0 );
  26177. }
  26178. return output;
  26179. }
  26180. }
  26181. /**
  26182. * TSL function for creating a range node.
  26183. *
  26184. * @tsl
  26185. * @function
  26186. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  26187. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  26188. * @returns {RangeNode}
  26189. */
  26190. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  26191. /**
  26192. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  26193. * about the currently running dispatch and/or the device it is running on.
  26194. *
  26195. * This node can only be used with a WebGPU backend.
  26196. *
  26197. * @augments Node
  26198. */
  26199. class ComputeBuiltinNode extends Node {
  26200. static get type() {
  26201. return 'ComputeBuiltinNode';
  26202. }
  26203. /**
  26204. * Constructs a new compute builtin node.
  26205. *
  26206. * @param {string} builtinName - The built-in name.
  26207. * @param {string} nodeType - The node type.
  26208. */
  26209. constructor( builtinName, nodeType ) {
  26210. super( nodeType );
  26211. /**
  26212. * The built-in name.
  26213. *
  26214. * @private
  26215. * @type {string}
  26216. */
  26217. this._builtinName = builtinName;
  26218. }
  26219. /**
  26220. * This method is overwritten since hash is derived from the built-in name.
  26221. *
  26222. * @param {NodeBuilder} builder - The current node builder.
  26223. * @return {string} The hash.
  26224. */
  26225. getHash( builder ) {
  26226. return this.getBuiltinName( builder );
  26227. }
  26228. /**
  26229. * This method is overwritten since the node type is simply derived from `nodeType`..
  26230. *
  26231. * @param {NodeBuilder} builder - The current node builder.
  26232. * @return {string} The node type.
  26233. */
  26234. getNodeType( /*builder*/ ) {
  26235. return this.nodeType;
  26236. }
  26237. /**
  26238. * Sets the builtin name.
  26239. *
  26240. * @param {string} builtinName - The built-in name.
  26241. * @return {ComputeBuiltinNode} A reference to this node.
  26242. */
  26243. setBuiltinName( builtinName ) {
  26244. this._builtinName = builtinName;
  26245. return this;
  26246. }
  26247. /**
  26248. * Returns the builtin name.
  26249. *
  26250. * @param {NodeBuilder} builder - The current node builder.
  26251. * @return {string} The builtin name.
  26252. */
  26253. getBuiltinName( /*builder*/ ) {
  26254. return this._builtinName;
  26255. }
  26256. /**
  26257. * Whether the current node builder has the builtin or not.
  26258. *
  26259. * @param {NodeBuilder} builder - The current node builder.
  26260. * @return {boolean} Whether the builder has the builtin or not.
  26261. */
  26262. hasBuiltin( builder ) {
  26263. return builder.hasBuiltin( this._builtinName );
  26264. }
  26265. generate( builder, output ) {
  26266. const builtinName = this.getBuiltinName( builder );
  26267. const nodeType = this.getNodeType( builder );
  26268. if ( builder.shaderStage === 'compute' ) {
  26269. return builder.format( builtinName, nodeType, output );
  26270. } else {
  26271. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  26272. return builder.generateConst( nodeType );
  26273. }
  26274. }
  26275. serialize( data ) {
  26276. super.serialize( data );
  26277. data.global = this.global;
  26278. data._builtinName = this._builtinName;
  26279. }
  26280. deserialize( data ) {
  26281. super.deserialize( data );
  26282. this.global = data.global;
  26283. this._builtinName = data._builtinName;
  26284. }
  26285. }
  26286. /**
  26287. * TSL function for creating a compute builtin node.
  26288. *
  26289. * @tsl
  26290. * @function
  26291. * @param {string} name - The built-in name.
  26292. * @param {string} nodeType - The node type.
  26293. * @returns {ComputeBuiltinNode}
  26294. */
  26295. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  26296. /**
  26297. * Represents the number of workgroups dispatched by the compute shader.
  26298. * ```js
  26299. * // Run 512 invocations/threads with a workgroup size of 128.
  26300. * const computeFn = Fn(() => {
  26301. *
  26302. * // numWorkgroups.x = 4
  26303. * storageBuffer.element(0).assign(numWorkgroups.x)
  26304. *
  26305. * })().compute(512, [128]);
  26306. *
  26307. * // Run 512 invocations/threads with the default workgroup size of 64.
  26308. * const computeFn = Fn(() => {
  26309. *
  26310. * // numWorkgroups.x = 8
  26311. * storageBuffer.element(0).assign(numWorkgroups.x)
  26312. *
  26313. * })().compute(512);
  26314. * ```
  26315. *
  26316. * @tsl
  26317. * @type {ComputeBuiltinNode<uvec3>}
  26318. */
  26319. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  26320. /**
  26321. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  26322. * ```js
  26323. * // Execute 12 compute threads with a workgroup size of 3.
  26324. * const computeFn = Fn( () => {
  26325. *
  26326. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  26327. *
  26328. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  26329. *
  26330. * } ).Else( () => {
  26331. *
  26332. * storageBuffer.element( instanceIndex ).assign( 0 );
  26333. *
  26334. * } );
  26335. *
  26336. * } )().compute( 12, [ 3 ] );
  26337. *
  26338. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  26339. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  26340. * ```
  26341. *
  26342. * @tsl
  26343. * @type {ComputeBuiltinNode<uvec3>}
  26344. */
  26345. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  26346. /**
  26347. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  26348. *
  26349. * @tsl
  26350. * @type {ComputeBuiltinNode<uvec3>}
  26351. */
  26352. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  26353. /**
  26354. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  26355. *
  26356. * @tsl
  26357. * @type {ComputeBuiltinNode<uvec3>}
  26358. */
  26359. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  26360. /**
  26361. * A device dependent variable that exposes the size of the current invocation's subgroup.
  26362. *
  26363. * @tsl
  26364. * @type {ComputeBuiltinNode<uint>}
  26365. */
  26366. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  26367. /**
  26368. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  26369. *
  26370. * This node can only be used with a WebGPU backend.
  26371. *
  26372. * @augments Node
  26373. */
  26374. class BarrierNode extends Node {
  26375. /**
  26376. * Constructs a new barrier node.
  26377. *
  26378. * @param {string} scope - The scope defines the behavior of the node.
  26379. */
  26380. constructor( scope ) {
  26381. super();
  26382. this.scope = scope;
  26383. }
  26384. generate( builder ) {
  26385. const { scope } = this;
  26386. const { renderer } = builder;
  26387. if ( renderer.backend.isWebGLBackend === true ) {
  26388. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  26389. } else {
  26390. builder.addLineFlowCode( `${scope}Barrier()`, this );
  26391. }
  26392. }
  26393. }
  26394. /**
  26395. * TSL function for creating a barrier node.
  26396. *
  26397. * @tsl
  26398. * @function
  26399. * @param {string} scope - The scope defines the behavior of the node..
  26400. * @returns {BarrierNode}
  26401. */
  26402. const barrier = nodeProxy( BarrierNode );
  26403. /**
  26404. * TSL function for creating a workgroup barrier. All compute shader
  26405. * invocations must wait for each invocation within a workgroup to
  26406. * complete before the barrier can be surpassed.
  26407. *
  26408. * @tsl
  26409. * @function
  26410. * @returns {BarrierNode}
  26411. */
  26412. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  26413. /**
  26414. * TSL function for creating a storage barrier. All invocations must
  26415. * wait for each access to variables within the 'storage' address space
  26416. * to complete before the barrier can be passed.
  26417. *
  26418. * @tsl
  26419. * @function
  26420. * @returns {BarrierNode}
  26421. */
  26422. const storageBarrier = () => barrier( 'storage' ).toStack();
  26423. /**
  26424. * TSL function for creating a texture barrier. All invocations must
  26425. * wait for each access to variables within the 'texture' address space
  26426. * to complete before the barrier can be passed.
  26427. *
  26428. * @tsl
  26429. * @function
  26430. * @returns {BarrierNode}
  26431. */
  26432. const textureBarrier = () => barrier( 'texture' ).toStack();
  26433. /**
  26434. * Represents an element of a 'workgroup' scoped buffer.
  26435. *
  26436. * @augments ArrayElementNode
  26437. */
  26438. class WorkgroupInfoElementNode extends ArrayElementNode {
  26439. /**
  26440. * Constructs a new workgroup info element node.
  26441. *
  26442. * @param {Node} workgroupInfoNode - The workgroup info node.
  26443. * @param {Node} indexNode - The index node that defines the element access.
  26444. */
  26445. constructor( workgroupInfoNode, indexNode ) {
  26446. super( workgroupInfoNode, indexNode );
  26447. /**
  26448. * This flag can be used for type testing.
  26449. *
  26450. * @type {boolean}
  26451. * @readonly
  26452. * @default true
  26453. */
  26454. this.isWorkgroupInfoElementNode = true;
  26455. }
  26456. generate( builder, output ) {
  26457. let snippet;
  26458. const isAssignContext = builder.context.assign;
  26459. snippet = super.generate( builder );
  26460. if ( isAssignContext !== true ) {
  26461. const type = this.getNodeType( builder );
  26462. snippet = builder.format( snippet, type, output );
  26463. }
  26464. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  26465. return snippet;
  26466. }
  26467. }
  26468. /**
  26469. * A node allowing the user to create a 'workgroup' scoped buffer within the
  26470. * context of a compute shader. Typically, workgroup scoped buffers are
  26471. * created to hold data that is transferred from a global storage scope into
  26472. * a local workgroup scope. For invocations within a workgroup, data
  26473. * access speeds on 'workgroup' scoped buffers can be significantly faster
  26474. * than similar access operations on globally accessible storage buffers.
  26475. *
  26476. * This node can only be used with a WebGPU backend.
  26477. *
  26478. * @augments Node
  26479. */
  26480. class WorkgroupInfoNode extends Node {
  26481. /**
  26482. * Constructs a new buffer scoped to type scope.
  26483. *
  26484. * @param {string} scope - TODO.
  26485. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  26486. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  26487. */
  26488. constructor( scope, bufferType, bufferCount = 0 ) {
  26489. super( bufferType );
  26490. /**
  26491. * The buffer type.
  26492. *
  26493. * @type {string}
  26494. */
  26495. this.bufferType = bufferType;
  26496. /**
  26497. * The buffer count.
  26498. *
  26499. * @type {number}
  26500. * @default 0
  26501. */
  26502. this.bufferCount = bufferCount;
  26503. /**
  26504. * This flag can be used for type testing.
  26505. *
  26506. * @type {boolean}
  26507. * @readonly
  26508. * @default true
  26509. */
  26510. this.isWorkgroupInfoNode = true;
  26511. /**
  26512. * The data type of the array buffer.
  26513. *
  26514. * @type {string}
  26515. */
  26516. this.elementType = bufferType;
  26517. /**
  26518. * TODO.
  26519. *
  26520. * @type {string}
  26521. */
  26522. this.scope = scope;
  26523. }
  26524. /**
  26525. * Sets the name/label of this node.
  26526. *
  26527. * @param {string} name - The name to set.
  26528. * @return {WorkgroupInfoNode} A reference to this node.
  26529. */
  26530. label( name ) {
  26531. this.name = name;
  26532. return this;
  26533. }
  26534. /**
  26535. * Sets the scope of this node.
  26536. *
  26537. * @param {string} scope - The scope to set.
  26538. * @return {WorkgroupInfoNode} A reference to this node.
  26539. */
  26540. setScope( scope ) {
  26541. this.scope = scope;
  26542. return this;
  26543. }
  26544. /**
  26545. * The data type of the array buffer.
  26546. *
  26547. * @return {string} The element type.
  26548. */
  26549. getElementType() {
  26550. return this.elementType;
  26551. }
  26552. /**
  26553. * Overwrites the default implementation since the input type
  26554. * is inferred from the scope.
  26555. *
  26556. * @param {NodeBuilder} builder - The current node builder.
  26557. * @return {string} The input type.
  26558. */
  26559. getInputType( /*builder*/ ) {
  26560. return `${this.scope}Array`;
  26561. }
  26562. /**
  26563. * This method can be used to access elements via an index node.
  26564. *
  26565. * @param {IndexNode} indexNode - indexNode.
  26566. * @return {WorkgroupInfoElementNode} A reference to an element.
  26567. */
  26568. element( indexNode ) {
  26569. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  26570. }
  26571. generate( builder ) {
  26572. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  26573. }
  26574. }
  26575. /**
  26576. * TSL function for creating a workgroup info node.
  26577. * Creates a new 'workgroup' scoped array buffer.
  26578. *
  26579. * @tsl
  26580. * @function
  26581. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  26582. * @param {number} [count=0] - The number of elements in the buffer.
  26583. * @returns {WorkgroupInfoNode}
  26584. */
  26585. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  26586. /**
  26587. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  26588. * within a shader. In an atomic function, any modification to an atomic variable will
  26589. * occur as an indivisible step with a defined order relative to other modifications.
  26590. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  26591. * atomic operations will not interfere with each other.
  26592. *
  26593. * This node can only be used with a WebGPU backend.
  26594. *
  26595. * @augments Node
  26596. */
  26597. class AtomicFunctionNode extends Node {
  26598. static get type() {
  26599. return 'AtomicFunctionNode';
  26600. }
  26601. /**
  26602. * Constructs a new atomic function node.
  26603. *
  26604. * @param {string} method - The signature of the atomic function to construct.
  26605. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26606. * @param {Node} valueNode - The value that mutates the atomic variable.
  26607. */
  26608. constructor( method, pointerNode, valueNode ) {
  26609. super( 'uint' );
  26610. /**
  26611. * The signature of the atomic function to construct.
  26612. *
  26613. * @type {string}
  26614. */
  26615. this.method = method;
  26616. /**
  26617. * An atomic variable or element of an atomic buffer.
  26618. *
  26619. * @type {Node}
  26620. */
  26621. this.pointerNode = pointerNode;
  26622. /**
  26623. * A value that modifies the atomic variable.
  26624. *
  26625. * @type {Node}
  26626. */
  26627. this.valueNode = valueNode;
  26628. /**
  26629. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  26630. *
  26631. * @type {boolean}
  26632. * @default true
  26633. */
  26634. this.parents = true;
  26635. }
  26636. /**
  26637. * Overwrites the default implementation to return the type of
  26638. * the pointer node.
  26639. *
  26640. * @param {NodeBuilder} builder - The current node builder.
  26641. * @return {string} The input type.
  26642. */
  26643. getInputType( builder ) {
  26644. return this.pointerNode.getNodeType( builder );
  26645. }
  26646. /**
  26647. * Overwritten since the node type is inferred from the input type.
  26648. *
  26649. * @param {NodeBuilder} builder - The current node builder.
  26650. * @return {string} The node type.
  26651. */
  26652. getNodeType( builder ) {
  26653. return this.getInputType( builder );
  26654. }
  26655. generate( builder ) {
  26656. const properties = builder.getNodeProperties( this );
  26657. const parents = properties.parents;
  26658. const method = this.method;
  26659. const type = this.getNodeType( builder );
  26660. const inputType = this.getInputType( builder );
  26661. const a = this.pointerNode;
  26662. const b = this.valueNode;
  26663. const params = [];
  26664. params.push( `&${ a.build( builder, inputType ) }` );
  26665. if ( b !== null ) {
  26666. params.push( b.build( builder, inputType ) );
  26667. }
  26668. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  26669. const isVoid = parents.length === 1 && parents[ 0 ].isStackNode === true;
  26670. if ( isVoid ) {
  26671. builder.addLineFlowCode( methodSnippet, this );
  26672. } else {
  26673. if ( properties.constNode === undefined ) {
  26674. properties.constNode = expression( methodSnippet, type ).toConst();
  26675. }
  26676. return properties.constNode.build( builder );
  26677. }
  26678. }
  26679. }
  26680. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  26681. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  26682. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  26683. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  26684. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  26685. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  26686. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  26687. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  26688. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  26689. /**
  26690. * TSL function for creating an atomic function node.
  26691. *
  26692. * @tsl
  26693. * @function
  26694. * @param {string} method - The signature of the atomic function to construct.
  26695. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26696. * @param {Node} valueNode - The value that mutates the atomic variable.
  26697. * @returns {AtomicFunctionNode}
  26698. */
  26699. const atomicNode = nodeProxy( AtomicFunctionNode );
  26700. /**
  26701. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  26702. *
  26703. * @tsl
  26704. * @function
  26705. * @param {string} method - The signature of the atomic function to construct.
  26706. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26707. * @param {Node} valueNode - The value that mutates the atomic variable.
  26708. * @returns {AtomicFunctionNode}
  26709. */
  26710. const atomicFunc = ( method, pointerNode, valueNode ) => {
  26711. return atomicNode( method, pointerNode, valueNode ).toStack();
  26712. };
  26713. /**
  26714. * Loads the value stored in the atomic variable.
  26715. *
  26716. * @tsl
  26717. * @function
  26718. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26719. * @returns {AtomicFunctionNode}
  26720. */
  26721. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  26722. /**
  26723. * Stores a value in the atomic variable.
  26724. *
  26725. * @tsl
  26726. * @function
  26727. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26728. * @param {Node} valueNode - The value that mutates the atomic variable.
  26729. * @returns {AtomicFunctionNode}
  26730. */
  26731. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  26732. /**
  26733. * Increments the value stored in the atomic variable.
  26734. *
  26735. * @tsl
  26736. * @function
  26737. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26738. * @param {Node} valueNode - The value that mutates the atomic variable.
  26739. * @returns {AtomicFunctionNode}
  26740. */
  26741. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  26742. /**
  26743. * Decrements the value stored in the atomic variable.
  26744. *
  26745. * @tsl
  26746. * @function
  26747. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26748. * @param {Node} valueNode - The value that mutates the atomic variable.
  26749. * @returns {AtomicFunctionNode}
  26750. */
  26751. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  26752. /**
  26753. * Stores in an atomic variable the maximum between its current value and a parameter.
  26754. *
  26755. * @tsl
  26756. * @function
  26757. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26758. * @param {Node} valueNode - The value that mutates the atomic variable.
  26759. * @returns {AtomicFunctionNode}
  26760. */
  26761. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  26762. /**
  26763. * Stores in an atomic variable the minimum between its current value and a parameter.
  26764. *
  26765. * @tsl
  26766. * @function
  26767. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26768. * @param {Node} valueNode - The value that mutates the atomic variable.
  26769. * @returns {AtomicFunctionNode}
  26770. */
  26771. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  26772. /**
  26773. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  26774. *
  26775. * @tsl
  26776. * @function
  26777. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26778. * @param {Node} valueNode - The value that mutates the atomic variable.
  26779. * @returns {AtomicFunctionNode}
  26780. */
  26781. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  26782. /**
  26783. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  26784. *
  26785. * @tsl
  26786. * @function
  26787. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26788. * @param {Node} valueNode - The value that mutates the atomic variable.
  26789. * @returns {AtomicFunctionNode}
  26790. */
  26791. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  26792. /**
  26793. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  26794. *
  26795. * @tsl
  26796. * @function
  26797. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26798. * @param {Node} valueNode - The value that mutates the atomic variable.
  26799. * @returns {AtomicFunctionNode}
  26800. */
  26801. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  26802. let uniformsLib;
  26803. function getLightData( light ) {
  26804. uniformsLib = uniformsLib || new WeakMap();
  26805. let uniforms = uniformsLib.get( light );
  26806. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  26807. return uniforms;
  26808. }
  26809. /**
  26810. * TSL function for getting a shadow matrix uniform node for the given light.
  26811. *
  26812. * @tsl
  26813. * @function
  26814. * @param {Light} light -The light source.
  26815. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  26816. */
  26817. function lightShadowMatrix( light ) {
  26818. const data = getLightData( light );
  26819. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  26820. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  26821. light.shadow.updateMatrices( light );
  26822. }
  26823. return light.shadow.matrix;
  26824. } ) );
  26825. }
  26826. /**
  26827. * TSL function for getting projected uv coordinates for the given light.
  26828. * Relevant when using maps with spot lights.
  26829. *
  26830. * @tsl
  26831. * @function
  26832. * @param {Light} light -The light source.
  26833. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  26834. * @returns {Node<vec3>} The projected uvs.
  26835. */
  26836. function lightProjectionUV( light, position = positionWorld ) {
  26837. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  26838. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  26839. return projectionUV;
  26840. }
  26841. /**
  26842. * TSL function for getting the position in world space for the given light.
  26843. *
  26844. * @tsl
  26845. * @function
  26846. * @param {Light} light -The light source.
  26847. * @returns {UniformNode<vec3>} The light's position in world space.
  26848. */
  26849. function lightPosition( light ) {
  26850. const data = getLightData( light );
  26851. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  26852. }
  26853. /**
  26854. * TSL function for getting the light target position in world space for the given light.
  26855. *
  26856. * @tsl
  26857. * @function
  26858. * @param {Light} light -The light source.
  26859. * @returns {UniformNode<vec3>} The light target position in world space.
  26860. */
  26861. function lightTargetPosition( light ) {
  26862. const data = getLightData( light );
  26863. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  26864. }
  26865. /**
  26866. * TSL function for getting the position in view space for the given light.
  26867. *
  26868. * @tsl
  26869. * @function
  26870. * @param {Light} light - The light source.
  26871. * @returns {UniformNode<vec3>} The light's position in view space.
  26872. */
  26873. function lightViewPosition( light ) {
  26874. const data = getLightData( light );
  26875. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  26876. self.value = self.value || new Vector3();
  26877. self.value.setFromMatrixPosition( light.matrixWorld );
  26878. self.value.applyMatrix4( camera.matrixWorldInverse );
  26879. } ) );
  26880. }
  26881. /**
  26882. * TSL function for getting the light target direction for the given light.
  26883. *
  26884. * @tsl
  26885. * @function
  26886. * @param {Light} light -The light source.
  26887. * @returns {Node<vec3>} The light's target direction.
  26888. */
  26889. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  26890. const sortLights = ( lights ) => {
  26891. return lights.sort( ( a, b ) => a.id - b.id );
  26892. };
  26893. const getLightNodeById = ( id, lightNodes ) => {
  26894. for ( const lightNode of lightNodes ) {
  26895. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26896. return lightNode;
  26897. }
  26898. }
  26899. return null;
  26900. };
  26901. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  26902. const _hashData = [];
  26903. /**
  26904. * This node represents the scene's lighting and manages the lighting model's life cycle
  26905. * for the current build 3D object. It is responsible for computing the total outgoing
  26906. * light in a given lighting context.
  26907. *
  26908. * @augments Node
  26909. */
  26910. class LightsNode extends Node {
  26911. static get type() {
  26912. return 'LightsNode';
  26913. }
  26914. /**
  26915. * Constructs a new lights node.
  26916. */
  26917. constructor() {
  26918. super( 'vec3' );
  26919. /**
  26920. * A node representing the total diffuse light.
  26921. *
  26922. * @type {Node<vec3>}
  26923. */
  26924. this.totalDiffuseNode = vec3().toVar();
  26925. /**
  26926. * A node representing the total specular light.
  26927. *
  26928. * @type {Node<vec3>}
  26929. */
  26930. this.totalSpecularNode = vec3().toVar();
  26931. /**
  26932. * A node representing the outgoing light.
  26933. *
  26934. * @type {Node<vec3>}
  26935. */
  26936. this.outgoingLightNode = vec3().toVar();
  26937. /**
  26938. * An array representing the lights in the scene.
  26939. *
  26940. * @private
  26941. * @type {Array<Light>}
  26942. */
  26943. this._lights = [];
  26944. /**
  26945. * For each light in the scene, this node will create a
  26946. * corresponding light node.
  26947. *
  26948. * @private
  26949. * @type {?Array<LightingNode>}
  26950. * @default null
  26951. */
  26952. this._lightNodes = null;
  26953. /**
  26954. * A hash for identifying the current light nodes setup.
  26955. *
  26956. * @private
  26957. * @type {?string}
  26958. * @default null
  26959. */
  26960. this._lightNodesHash = null;
  26961. /**
  26962. * `LightsNode` sets this property to `true` by default.
  26963. *
  26964. * @type {boolean}
  26965. * @default true
  26966. */
  26967. this.global = true;
  26968. }
  26969. /**
  26970. * Overwrites the default {@link Node#customCacheKey} implementation by including
  26971. * light data into the cache key.
  26972. *
  26973. * @return {number} The custom cache key.
  26974. */
  26975. customCacheKey() {
  26976. const lights = this._lights;
  26977. for ( let i = 0; i < lights.length; i ++ ) {
  26978. const light = lights[ i ];
  26979. _hashData.push( light.id );
  26980. _hashData.push( light.castShadow ? 1 : 0 );
  26981. if ( light.isSpotLight === true ) {
  26982. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  26983. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  26984. _hashData.push( hashMap, hashColorNode );
  26985. }
  26986. }
  26987. const cacheKey = hashArray( _hashData );
  26988. _hashData.length = 0;
  26989. return cacheKey;
  26990. }
  26991. /**
  26992. * Computes a hash value for identifying the current light nodes setup.
  26993. *
  26994. * @param {NodeBuilder} builder - A reference to the current node builder.
  26995. * @return {string} The computed hash.
  26996. */
  26997. getHash( builder ) {
  26998. if ( this._lightNodesHash === null ) {
  26999. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  27000. const hash = [];
  27001. for ( const lightNode of this._lightNodes ) {
  27002. hash.push( lightNode.getSelf().getHash() );
  27003. }
  27004. this._lightNodesHash = 'lights-' + hash.join( ',' );
  27005. }
  27006. return this._lightNodesHash;
  27007. }
  27008. analyze( builder ) {
  27009. const properties = builder.getNodeProperties( this );
  27010. for ( const node of properties.nodes ) {
  27011. node.build( builder );
  27012. }
  27013. properties.outputNode.build( builder );
  27014. }
  27015. /**
  27016. * Creates lighting nodes for each scene light. This makes it possible to further
  27017. * process lights in the node system.
  27018. *
  27019. * @param {NodeBuilder} builder - A reference to the current node builder.
  27020. */
  27021. setupLightsNode( builder ) {
  27022. const lightNodes = [];
  27023. const previousLightNodes = this._lightNodes;
  27024. const lights = sortLights( this._lights );
  27025. const nodeLibrary = builder.renderer.library;
  27026. for ( const light of lights ) {
  27027. if ( light.isNode ) {
  27028. lightNodes.push( nodeObject( light ) );
  27029. } else {
  27030. let lightNode = null;
  27031. if ( previousLightNodes !== null ) {
  27032. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  27033. }
  27034. if ( lightNode === null ) {
  27035. // find the corresponding node type for a given light
  27036. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  27037. if ( lightNodeClass === null ) {
  27038. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  27039. continue;
  27040. }
  27041. let lightNode = null;
  27042. if ( ! _lightsNodeRef.has( light ) ) {
  27043. lightNode = nodeObject( new lightNodeClass( light ) );
  27044. _lightsNodeRef.set( light, lightNode );
  27045. } else {
  27046. lightNode = _lightsNodeRef.get( light );
  27047. }
  27048. lightNodes.push( lightNode );
  27049. }
  27050. }
  27051. }
  27052. this._lightNodes = lightNodes;
  27053. }
  27054. /**
  27055. * Sets up a direct light in the lighting model.
  27056. *
  27057. * @param {Object} builder - The builder object containing the context and stack.
  27058. * @param {Object} lightNode - The light node.
  27059. * @param {Object} lightData - The light object containing color and direction properties.
  27060. */
  27061. setupDirectLight( builder, lightNode, lightData ) {
  27062. const { lightingModel, reflectedLight } = builder.context;
  27063. lightingModel.direct( {
  27064. ...lightData,
  27065. lightNode,
  27066. reflectedLight
  27067. }, builder );
  27068. }
  27069. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  27070. const { lightingModel, reflectedLight } = builder.context;
  27071. lightingModel.directRectArea( {
  27072. ...lightData,
  27073. lightNode,
  27074. reflectedLight
  27075. }, builder );
  27076. }
  27077. /**
  27078. * Setups the internal lights by building all respective
  27079. * light nodes.
  27080. *
  27081. * @param {NodeBuilder} builder - A reference to the current node builder.
  27082. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  27083. */
  27084. setupLights( builder, lightNodes ) {
  27085. for ( const lightNode of lightNodes ) {
  27086. lightNode.build( builder );
  27087. }
  27088. }
  27089. getLightNodes( builder ) {
  27090. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  27091. return this._lightNodes;
  27092. }
  27093. /**
  27094. * The implementation makes sure that for each light in the scene
  27095. * there is a corresponding light node. By building the light nodes
  27096. * and evaluating the lighting model the outgoing light is computed.
  27097. *
  27098. * @param {NodeBuilder} builder - A reference to the current node builder.
  27099. * @return {Node<vec3>} A node representing the outgoing light.
  27100. */
  27101. setup( builder ) {
  27102. const currentLightsNode = builder.lightsNode;
  27103. builder.lightsNode = this;
  27104. //
  27105. let outgoingLightNode = this.outgoingLightNode;
  27106. const context = builder.context;
  27107. const lightingModel = context.lightingModel;
  27108. const properties = builder.getNodeProperties( this );
  27109. if ( lightingModel ) {
  27110. const { totalDiffuseNode, totalSpecularNode } = this;
  27111. context.outgoingLight = outgoingLightNode;
  27112. const stack = builder.addStack();
  27113. //
  27114. properties.nodes = stack.nodes;
  27115. //
  27116. lightingModel.start( builder );
  27117. //
  27118. const { backdrop, backdropAlpha } = context;
  27119. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  27120. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  27121. if ( backdrop !== null ) {
  27122. if ( backdropAlpha !== null ) {
  27123. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  27124. } else {
  27125. totalDiffuse = vec3( backdrop );
  27126. }
  27127. context.material.transparent = true;
  27128. }
  27129. totalDiffuseNode.assign( totalDiffuse );
  27130. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  27131. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  27132. //
  27133. lightingModel.finish( builder );
  27134. //
  27135. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  27136. } else {
  27137. properties.nodes = [];
  27138. }
  27139. //
  27140. builder.lightsNode = currentLightsNode;
  27141. return outgoingLightNode;
  27142. }
  27143. /**
  27144. * Configures this node with an array of lights.
  27145. *
  27146. * @param {Array<Light>} lights - An array of lights.
  27147. * @return {LightsNode} A reference to this node.
  27148. */
  27149. setLights( lights ) {
  27150. this._lights = lights;
  27151. this._lightNodes = null;
  27152. this._lightNodesHash = null;
  27153. return this;
  27154. }
  27155. /**
  27156. * Returns an array of the scene's lights.
  27157. *
  27158. * @return {Array<Light>} The scene's lights.
  27159. */
  27160. getLights() {
  27161. return this._lights;
  27162. }
  27163. /**
  27164. * Whether the scene has lights or not.
  27165. *
  27166. * @type {boolean}
  27167. */
  27168. get hasLights() {
  27169. return this._lights.length > 0;
  27170. }
  27171. }
  27172. /**
  27173. * TSL function for creating an instance of `LightsNode` and configuring
  27174. * it with the given array of lights.
  27175. *
  27176. * @tsl
  27177. * @function
  27178. * @param {Array<Light>} lights - An array of lights.
  27179. * @return {LightsNode} The created lights node.
  27180. */
  27181. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  27182. /**
  27183. * Base class for all shadow nodes.
  27184. *
  27185. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  27186. * Lighting nodes might share the same shadow node type or use specific ones depending on
  27187. * their requirements.
  27188. *
  27189. * @augments Node
  27190. */
  27191. class ShadowBaseNode extends Node {
  27192. static get type() {
  27193. return 'ShadowBaseNode';
  27194. }
  27195. /**
  27196. * Constructs a new shadow base node.
  27197. *
  27198. * @param {Light} light - The shadow casting light.
  27199. */
  27200. constructor( light ) {
  27201. super();
  27202. /**
  27203. * The shadow casting light.
  27204. *
  27205. * @type {Light}
  27206. */
  27207. this.light = light;
  27208. /**
  27209. * Overwritten since shadows are updated by default per render.
  27210. *
  27211. * @type {string}
  27212. * @default 'render'
  27213. */
  27214. this.updateBeforeType = NodeUpdateType.RENDER;
  27215. /**
  27216. * This flag can be used for type testing.
  27217. *
  27218. * @type {boolean}
  27219. * @readonly
  27220. * @default true
  27221. */
  27222. this.isShadowBaseNode = true;
  27223. }
  27224. /**
  27225. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  27226. *
  27227. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  27228. */
  27229. setupShadowPosition( { context, material } ) {
  27230. // Use assign inside an Fn()
  27231. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  27232. }
  27233. /**
  27234. * Can be called when the shadow isn't required anymore. That can happen when
  27235. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  27236. * to `false`.
  27237. */
  27238. dispose() {
  27239. this.updateBeforeType = NodeUpdateType.NONE;
  27240. }
  27241. }
  27242. /**
  27243. * TSL object that represents the vertex position in world space during the shadow pass.
  27244. *
  27245. * @tsl
  27246. * @type {Node<vec3>}
  27247. */
  27248. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  27249. /**
  27250. * Saves the state of the given renderer and stores it into the given state object.
  27251. *
  27252. * If not state object is provided, the function creates one.
  27253. *
  27254. * @function
  27255. * @param {Renderer} renderer - The renderer.
  27256. * @param {Object} [state={}] - The state.
  27257. * @return {Object} The state.
  27258. */
  27259. function saveRendererState( renderer, state = {} ) {
  27260. state.toneMapping = renderer.toneMapping;
  27261. state.toneMappingExposure = renderer.toneMappingExposure;
  27262. state.outputColorSpace = renderer.outputColorSpace;
  27263. state.renderTarget = renderer.getRenderTarget();
  27264. state.activeCubeFace = renderer.getActiveCubeFace();
  27265. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  27266. state.renderObjectFunction = renderer.getRenderObjectFunction();
  27267. state.pixelRatio = renderer.getPixelRatio();
  27268. state.mrt = renderer.getMRT();
  27269. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  27270. state.clearAlpha = renderer.getClearAlpha();
  27271. state.autoClear = renderer.autoClear;
  27272. state.scissorTest = renderer.getScissorTest();
  27273. return state;
  27274. }
  27275. /**
  27276. * Saves the state of the given renderer and stores it into the given state object.
  27277. * Besides, the function also resets the state of the renderer to its default values.
  27278. *
  27279. * If not state object is provided, the function creates one.
  27280. *
  27281. * @function
  27282. * @param {Renderer} renderer - The renderer.
  27283. * @param {Object} [state={}] - The state.
  27284. * @return {Object} The state.
  27285. */
  27286. function resetRendererState( renderer, state ) {
  27287. state = saveRendererState( renderer, state );
  27288. renderer.setMRT( null );
  27289. renderer.setRenderObjectFunction( null );
  27290. renderer.setClearColor( 0x000000, 1 );
  27291. renderer.autoClear = true;
  27292. return state;
  27293. }
  27294. /**
  27295. * Restores the state of the given renderer from the given state object.
  27296. *
  27297. * @function
  27298. * @param {Renderer} renderer - The renderer.
  27299. * @param {Object} state - The state to restore.
  27300. */
  27301. function restoreRendererState( renderer, state ) {
  27302. renderer.toneMapping = state.toneMapping;
  27303. renderer.toneMappingExposure = state.toneMappingExposure;
  27304. renderer.outputColorSpace = state.outputColorSpace;
  27305. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  27306. renderer.setRenderObjectFunction( state.renderObjectFunction );
  27307. renderer.setPixelRatio( state.pixelRatio );
  27308. renderer.setMRT( state.mrt );
  27309. renderer.setClearColor( state.clearColor, state.clearAlpha );
  27310. renderer.autoClear = state.autoClear;
  27311. renderer.setScissorTest( state.scissorTest );
  27312. }
  27313. /**
  27314. * Saves the state of the given scene and stores it into the given state object.
  27315. *
  27316. * If not state object is provided, the function creates one.
  27317. *
  27318. * @function
  27319. * @param {Scene} scene - The scene.
  27320. * @param {Object} [state={}] - The state.
  27321. * @return {Object} The state.
  27322. */
  27323. function saveSceneState( scene, state = {} ) {
  27324. state.background = scene.background;
  27325. state.backgroundNode = scene.backgroundNode;
  27326. state.overrideMaterial = scene.overrideMaterial;
  27327. return state;
  27328. }
  27329. /**
  27330. * Saves the state of the given scene and stores it into the given state object.
  27331. * Besides, the function also resets the state of the scene to its default values.
  27332. *
  27333. * If not state object is provided, the function creates one.
  27334. *
  27335. * @function
  27336. * @param {Scene} scene - The scene.
  27337. * @param {Object} [state={}] - The state.
  27338. * @return {Object} The state.
  27339. */
  27340. function resetSceneState( scene, state ) {
  27341. state = saveSceneState( scene, state );
  27342. scene.background = null;
  27343. scene.backgroundNode = null;
  27344. scene.overrideMaterial = null;
  27345. return state;
  27346. }
  27347. /**
  27348. * Restores the state of the given scene from the given state object.
  27349. *
  27350. * @function
  27351. * @param {Scene} scene - The scene.
  27352. * @param {Object} state - The state to restore.
  27353. */
  27354. function restoreSceneState( scene, state ) {
  27355. scene.background = state.background;
  27356. scene.backgroundNode = state.backgroundNode;
  27357. scene.overrideMaterial = state.overrideMaterial;
  27358. }
  27359. /**
  27360. * Saves the state of the given renderer and scene and stores it into the given state object.
  27361. *
  27362. * If not state object is provided, the function creates one.
  27363. *
  27364. * @function
  27365. * @param {Renderer} renderer - The renderer.
  27366. * @param {Scene} scene - The scene.
  27367. * @param {Object} [state={}] - The state.
  27368. * @return {Object} The state.
  27369. */
  27370. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  27371. state = saveRendererState( renderer, state );
  27372. state = saveSceneState( scene, state );
  27373. return state;
  27374. }
  27375. /**
  27376. * Saves the state of the given renderer and scene and stores it into the given state object.
  27377. * Besides, the function also resets the state of the renderer and scene to its default values.
  27378. *
  27379. * If not state object is provided, the function creates one.
  27380. *
  27381. * @function
  27382. * @param {Renderer} renderer - The renderer.
  27383. * @param {Scene} scene - The scene.
  27384. * @param {Object} [state={}] - The state.
  27385. * @return {Object} The state.
  27386. */
  27387. function resetRendererAndSceneState( renderer, scene, state ) {
  27388. state = resetRendererState( renderer, state );
  27389. state = resetSceneState( scene, state );
  27390. return state;
  27391. }
  27392. /**
  27393. * Restores the state of the given renderer and scene from the given state object.
  27394. *
  27395. * @function
  27396. * @param {Renderer} renderer - The renderer.
  27397. * @param {Scene} scene - The scene.
  27398. * @param {Object} state - The state to restore.
  27399. */
  27400. function restoreRendererAndSceneState( renderer, scene, state ) {
  27401. restoreRendererState( renderer, state );
  27402. restoreSceneState( scene, state );
  27403. }
  27404. var RendererUtils = /*#__PURE__*/Object.freeze({
  27405. __proto__: null,
  27406. resetRendererAndSceneState: resetRendererAndSceneState,
  27407. resetRendererState: resetRendererState,
  27408. resetSceneState: resetSceneState,
  27409. restoreRendererAndSceneState: restoreRendererAndSceneState,
  27410. restoreRendererState: restoreRendererState,
  27411. restoreSceneState: restoreSceneState,
  27412. saveRendererAndSceneState: saveRendererAndSceneState,
  27413. saveRendererState: saveRendererState,
  27414. saveSceneState: saveSceneState
  27415. });
  27416. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  27417. /**
  27418. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  27419. * with a binary `[0,1]` result.
  27420. *
  27421. * @method
  27422. * @param {Object} inputs - The input parameter object.
  27423. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27424. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27425. * @return {Node<float>} The filtering result.
  27426. */
  27427. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  27428. let basic = texture( depthTexture, shadowCoord.xy ).label( 't_basic' );
  27429. if ( depthTexture.isArrayTexture ) {
  27430. basic = basic.depth( depthLayer );
  27431. }
  27432. return basic.compare( shadowCoord.z );
  27433. } );
  27434. /**
  27435. * A shadow filtering function performing PCF filtering.
  27436. *
  27437. * @method
  27438. * @param {Object} inputs - The input parameter object.
  27439. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27440. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27441. * @param {LightShadow} inputs.shadow - The light shadow.
  27442. * @return {Node<float>} The filtering result.
  27443. */
  27444. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  27445. const depthCompare = ( uv, compare ) => {
  27446. let depth = texture( depthTexture, uv );
  27447. if ( depthTexture.isArrayTexture ) {
  27448. depth = depth.depth( depthLayer );
  27449. }
  27450. return depth.compare( compare );
  27451. };
  27452. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27453. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27454. const texelSize = vec2( 1 ).div( mapSize );
  27455. const dx0 = texelSize.x.negate().mul( radius );
  27456. const dy0 = texelSize.y.negate().mul( radius );
  27457. const dx1 = texelSize.x.mul( radius );
  27458. const dy1 = texelSize.y.mul( radius );
  27459. const dx2 = dx0.div( 2 );
  27460. const dy2 = dy0.div( 2 );
  27461. const dx3 = dx1.div( 2 );
  27462. const dy3 = dy1.div( 2 );
  27463. return add(
  27464. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  27465. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  27466. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  27467. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  27468. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  27469. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  27470. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  27471. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  27472. depthCompare( shadowCoord.xy, shadowCoord.z ),
  27473. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  27474. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  27475. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  27476. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  27477. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  27478. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  27479. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  27480. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  27481. ).mul( 1 / 17 );
  27482. } );
  27483. /**
  27484. * A shadow filtering function performing PCF soft filtering.
  27485. *
  27486. * @method
  27487. * @param {Object} inputs - The input parameter object.
  27488. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27489. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27490. * @param {LightShadow} inputs.shadow - The light shadow.
  27491. * @return {Node<float>} The filtering result.
  27492. */
  27493. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  27494. const depthCompare = ( uv, compare ) => {
  27495. let depth = texture( depthTexture, uv );
  27496. if ( depthTexture.isArrayTexture ) {
  27497. depth = depth.depth( depthLayer );
  27498. }
  27499. return depth.compare( compare );
  27500. };
  27501. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27502. const texelSize = vec2( 1 ).div( mapSize );
  27503. const dx = texelSize.x;
  27504. const dy = texelSize.y;
  27505. const uv = shadowCoord.xy;
  27506. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  27507. uv.subAssign( f.mul( texelSize ) );
  27508. return add(
  27509. depthCompare( uv, shadowCoord.z ),
  27510. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  27511. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  27512. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  27513. mix(
  27514. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  27515. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  27516. f.x
  27517. ),
  27518. mix(
  27519. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  27520. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  27521. f.x
  27522. ),
  27523. mix(
  27524. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  27525. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  27526. f.y
  27527. ),
  27528. mix(
  27529. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  27530. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  27531. f.y
  27532. ),
  27533. mix(
  27534. mix(
  27535. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  27536. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  27537. f.x
  27538. ),
  27539. mix(
  27540. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  27541. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  27542. f.x
  27543. ),
  27544. f.y
  27545. )
  27546. ).mul( 1 / 9 );
  27547. } );
  27548. /**
  27549. * A shadow filtering function performing VSM filtering.
  27550. *
  27551. * @method
  27552. * @param {Object} inputs - The input parameter object.
  27553. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27554. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27555. * @return {Node<float>} The filtering result.
  27556. */
  27557. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  27558. const occlusion = float( 1 ).toVar();
  27559. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  27560. if ( depthTexture.isArrayTexture ) {
  27561. distribution = distribution.depth( depthLayer );
  27562. }
  27563. distribution = distribution.rg;
  27564. const hardShadow = step( shadowCoord.z, distribution.x );
  27565. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  27566. const distance = shadowCoord.z.sub( distribution.x );
  27567. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  27568. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  27569. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  27570. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  27571. } );
  27572. return occlusion;
  27573. } );
  27574. //
  27575. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  27576. let dist = positionWorld.sub( position ).length();
  27577. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  27578. dist = dist.saturate(); // clamp to [ 0, 1 ]
  27579. return dist;
  27580. } );
  27581. const linearShadowDistance = ( light ) => {
  27582. const camera = light.shadow.camera;
  27583. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  27584. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  27585. const referencePosition = objectPosition( light );
  27586. return linearDistance( referencePosition, nearDistance, farDistance );
  27587. };
  27588. /**
  27589. * Retrieves or creates a shadow material for the given light source.
  27590. *
  27591. * This function checks if a shadow material already exists for the provided light.
  27592. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  27593. * in the `shadowMaterialLib` for future use.
  27594. *
  27595. * @param {Light} light - The light source for which the shadow material is needed.
  27596. * If the light is a point light, a depth node is calculated
  27597. * using the linear shadow distance.
  27598. * @returns {NodeMaterial} The shadow material associated with the given light.
  27599. */
  27600. const getShadowMaterial = ( light ) => {
  27601. let material = shadowMaterialLib.get( light );
  27602. if ( material === undefined ) {
  27603. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  27604. material = new NodeMaterial();
  27605. material.colorNode = vec4( 0, 0, 0, 1 );
  27606. material.depthNode = depthNode;
  27607. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  27608. material.name = 'ShadowMaterial';
  27609. material.fog = false;
  27610. shadowMaterialLib.set( light, material );
  27611. }
  27612. return material;
  27613. };
  27614. //
  27615. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  27616. const _shadowRenderObjectKeys = [];
  27617. /**
  27618. * Creates a function to render shadow objects in a scene.
  27619. *
  27620. * @param {Renderer} renderer - The renderer.
  27621. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  27622. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  27623. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  27624. * @return {Function} A function that renders shadow objects.
  27625. *
  27626. * The returned function has the following parameters:
  27627. * @param {Object3D} object - The 3D object to render.
  27628. * @param {Scene} scene - The scene containing the object.
  27629. * @param {Camera} _camera - The camera used for rendering.
  27630. * @param {BufferGeometry} geometry - The geometry of the object.
  27631. * @param {Material} material - The material of the object.
  27632. * @param {Group} group - The group the object belongs to.
  27633. * @param {...any} params - Additional parameters for rendering.
  27634. */
  27635. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  27636. _shadowRenderObjectKeys[ 0 ] = renderer;
  27637. _shadowRenderObjectKeys[ 1 ] = shadow;
  27638. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  27639. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  27640. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  27641. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  27642. if ( useVelocity ) {
  27643. getDataFromObject( object ).useVelocity = true;
  27644. }
  27645. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27646. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  27647. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27648. }
  27649. };
  27650. renderObjectFunction.shadowType = shadowType;
  27651. renderObjectFunction.useVelocity = useVelocity;
  27652. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  27653. }
  27654. _shadowRenderObjectKeys[ 0 ] = null;
  27655. _shadowRenderObjectKeys[ 1 ] = null;
  27656. return renderObjectFunction;
  27657. };
  27658. /**
  27659. * Represents the shader code for the first VSM render pass.
  27660. *
  27661. * @method
  27662. * @param {Object} inputs - The input parameter object.
  27663. * @param {Node<float>} inputs.samples - The number of samples
  27664. * @param {Node<float>} inputs.radius - The radius.
  27665. * @param {Node<float>} inputs.size - The size.
  27666. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  27667. * @return {Node<vec2>} The VSM output.
  27668. */
  27669. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  27670. const mean = float( 0 ).toVar( 'meanVertical' );
  27671. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  27672. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  27673. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  27674. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  27675. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  27676. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  27677. if ( shadowPass.value.isArrayTexture ) {
  27678. depth = depth.depth( depthLayer );
  27679. }
  27680. depth = depth.x;
  27681. mean.addAssign( depth );
  27682. squaredMean.addAssign( depth.mul( depth ) );
  27683. } );
  27684. mean.divAssign( samples );
  27685. squaredMean.divAssign( samples );
  27686. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  27687. return vec2( mean, std_dev );
  27688. } );
  27689. /**
  27690. * Represents the shader code for the second VSM render pass.
  27691. *
  27692. * @method
  27693. * @param {Object} inputs - The input parameter object.
  27694. * @param {Node<float>} inputs.samples - The number of samples
  27695. * @param {Node<float>} inputs.radius - The radius.
  27696. * @param {Node<float>} inputs.size - The size.
  27697. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  27698. * @return {Node<vec2>} The VSM output.
  27699. */
  27700. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  27701. const mean = float( 0 ).toVar( 'meanHorizontal' );
  27702. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  27703. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  27704. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  27705. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  27706. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  27707. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  27708. if ( shadowPass.value.isArrayTexture ) {
  27709. distribution = distribution.depth( depthLayer );
  27710. }
  27711. mean.addAssign( distribution.x );
  27712. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  27713. } );
  27714. mean.divAssign( samples );
  27715. squaredMean.divAssign( samples );
  27716. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  27717. return vec2( mean, std_dev );
  27718. } );
  27719. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  27720. //
  27721. let _rendererState;
  27722. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  27723. /**
  27724. * Represents the default shadow implementation for lighting nodes.
  27725. *
  27726. * @augments ShadowBaseNode
  27727. */
  27728. class ShadowNode extends ShadowBaseNode {
  27729. static get type() {
  27730. return 'ShadowNode';
  27731. }
  27732. /**
  27733. * Constructs a new shadow node.
  27734. *
  27735. * @param {Light} light - The shadow casting light.
  27736. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  27737. */
  27738. constructor( light, shadow = null ) {
  27739. super( light );
  27740. /**
  27741. * The light shadow which defines the properties light's
  27742. * shadow.
  27743. *
  27744. * @type {?LightShadow}
  27745. * @default null
  27746. */
  27747. this.shadow = shadow || light.shadow;
  27748. /**
  27749. * A reference to the shadow map which is a render target.
  27750. *
  27751. * @type {?RenderTarget}
  27752. * @default null
  27753. */
  27754. this.shadowMap = null;
  27755. /**
  27756. * Only relevant for VSM shadows. Render target for the
  27757. * first VSM render pass.
  27758. *
  27759. * @type {?RenderTarget}
  27760. * @default null
  27761. */
  27762. this.vsmShadowMapVertical = null;
  27763. /**
  27764. * Only relevant for VSM shadows. Render target for the
  27765. * second VSM render pass.
  27766. *
  27767. * @type {?RenderTarget}
  27768. * @default null
  27769. */
  27770. this.vsmShadowMapHorizontal = null;
  27771. /**
  27772. * Only relevant for VSM shadows. Node material which
  27773. * is used to render the first VSM pass.
  27774. *
  27775. * @type {?NodeMaterial}
  27776. * @default null
  27777. */
  27778. this.vsmMaterialVertical = null;
  27779. /**
  27780. * Only relevant for VSM shadows. Node material which
  27781. * is used to render the second VSM pass.
  27782. *
  27783. * @type {?NodeMaterial}
  27784. * @default null
  27785. */
  27786. this.vsmMaterialHorizontal = null;
  27787. /**
  27788. * A reference to the output node which defines the
  27789. * final result of this shadow node.
  27790. *
  27791. * @type {?Node}
  27792. * @private
  27793. * @default null
  27794. */
  27795. this._node = null;
  27796. this._cameraFrameId = new WeakMap();
  27797. /**
  27798. * This flag can be used for type testing.
  27799. *
  27800. * @type {boolean}
  27801. * @readonly
  27802. * @default true
  27803. */
  27804. this.isShadowNode = true;
  27805. /**
  27806. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  27807. *
  27808. * @type {number}
  27809. * @readonly
  27810. * @default true
  27811. */
  27812. this.depthLayer = 0;
  27813. }
  27814. /**
  27815. * Setups the shadow filtering.
  27816. *
  27817. * @param {NodeBuilder} builder - A reference to the current node builder.
  27818. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  27819. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  27820. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27821. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  27822. * @param {LightShadow} inputs.shadow - The light shadow.
  27823. * @return {Node<float>} The result node of the shadow filtering.
  27824. */
  27825. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  27826. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  27827. .and( shadowCoord.x.lessThanEqual( 1 ) )
  27828. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  27829. .and( shadowCoord.y.lessThanEqual( 1 ) )
  27830. .and( shadowCoord.z.lessThanEqual( 1 ) );
  27831. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  27832. return frustumTest.select( shadowNode, float( 1 ) );
  27833. }
  27834. /**
  27835. * Setups the shadow coordinates.
  27836. *
  27837. * @param {NodeBuilder} builder - A reference to the current node builder.
  27838. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  27839. * @return {Node<vec3>} The shadow coordinates.
  27840. */
  27841. setupShadowCoord( builder, shadowPosition ) {
  27842. const { shadow } = this;
  27843. const { renderer } = builder;
  27844. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  27845. let shadowCoord = shadowPosition;
  27846. let coordZ;
  27847. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  27848. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  27849. coordZ = shadowCoord.z;
  27850. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  27851. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  27852. }
  27853. } else {
  27854. const w = shadowCoord.w;
  27855. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  27856. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  27857. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  27858. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  27859. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  27860. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  27861. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  27862. }
  27863. shadowCoord = vec3(
  27864. shadowCoord.x,
  27865. shadowCoord.y.oneMinus(), // follow webgpu standards
  27866. coordZ.add( bias )
  27867. );
  27868. return shadowCoord;
  27869. }
  27870. /**
  27871. * Returns the shadow filtering function for the given shadow type.
  27872. *
  27873. * @param {number} type - The shadow type.
  27874. * @return {Function} The filtering function.
  27875. */
  27876. getShadowFilterFn( type ) {
  27877. return _shadowFilterLib[ type ];
  27878. }
  27879. setupRenderTarget( shadow, builder ) {
  27880. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  27881. depthTexture.name = 'ShadowDepthTexture';
  27882. depthTexture.compareFunction = LessCompare;
  27883. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  27884. shadowMap.texture.name = 'ShadowMap';
  27885. shadowMap.texture.type = shadow.mapType;
  27886. shadowMap.depthTexture = depthTexture;
  27887. return { shadowMap, depthTexture };
  27888. }
  27889. /**
  27890. * Setups the shadow output node.
  27891. *
  27892. * @param {NodeBuilder} builder - A reference to the current node builder.
  27893. * @return {Node<vec3>} The shadow output node.
  27894. */
  27895. setupShadow( builder ) {
  27896. const { renderer } = builder;
  27897. const { light, shadow } = this;
  27898. const shadowMapType = renderer.shadowMap.type;
  27899. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  27900. shadow.camera.updateProjectionMatrix();
  27901. // VSM
  27902. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  27903. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  27904. if ( shadowMap.depth > 1 ) {
  27905. if ( ! shadowMap._vsmShadowMapVertical ) {
  27906. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  27907. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  27908. }
  27909. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  27910. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  27911. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  27912. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  27913. }
  27914. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  27915. } else {
  27916. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  27917. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  27918. }
  27919. let shadowPassVertical = texture( depthTexture );
  27920. if ( depthTexture.isArrayTexture ) {
  27921. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  27922. }
  27923. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  27924. if ( depthTexture.isArrayTexture ) {
  27925. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  27926. }
  27927. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  27928. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27929. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27930. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  27931. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  27932. material.name = 'VSMVertical';
  27933. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  27934. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  27935. material.name = 'VSMHorizontal';
  27936. }
  27937. //
  27938. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  27939. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  27940. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  27941. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  27942. //
  27943. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  27944. if ( filterFn === null ) {
  27945. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  27946. }
  27947. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  27948. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  27949. let shadowColor = texture( shadowMap.texture, shadowCoord );
  27950. if ( depthTexture.isArrayTexture ) {
  27951. shadowColor = shadowColor.depth( this.depthLayer );
  27952. }
  27953. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  27954. this.shadowMap = shadowMap;
  27955. this.shadow.map = shadowMap;
  27956. return shadowOutput;
  27957. }
  27958. /**
  27959. * The implementation performs the setup of the output node. An output is only
  27960. * produces if shadow mapping is globally enabled in the renderer.
  27961. *
  27962. * @param {NodeBuilder} builder - A reference to the current node builder.
  27963. * @return {ShaderCallNodeInternal} The output node.
  27964. */
  27965. setup( builder ) {
  27966. if ( builder.renderer.shadowMap.enabled === false ) return;
  27967. return Fn( () => {
  27968. let node = this._node;
  27969. this.setupShadowPosition( builder );
  27970. if ( node === null ) {
  27971. this._node = node = this.setupShadow( builder );
  27972. }
  27973. if ( builder.material.shadowNode ) { // @deprecated, r171
  27974. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  27975. }
  27976. if ( builder.material.receivedShadowNode ) {
  27977. node = builder.material.receivedShadowNode( node );
  27978. }
  27979. return node;
  27980. } )();
  27981. }
  27982. /**
  27983. * Renders the shadow. The logic of this function could be included
  27984. * into {@link ShadowNode#updateShadow} however more specialized shadow
  27985. * nodes might require a custom shadow map rendering. By having a
  27986. * dedicated method, it's easier to overwrite the default behavior.
  27987. *
  27988. * @param {NodeFrame} frame - A reference to the current node frame.
  27989. */
  27990. renderShadow( frame ) {
  27991. const { shadow, shadowMap, light } = this;
  27992. const { renderer, scene } = frame;
  27993. shadow.updateMatrices( light );
  27994. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  27995. renderer.render( scene, shadow.camera );
  27996. }
  27997. /**
  27998. * Updates the shadow.
  27999. *
  28000. * @param {NodeFrame} frame - A reference to the current node frame.
  28001. */
  28002. updateShadow( frame ) {
  28003. const { shadowMap, light, shadow } = this;
  28004. const { renderer, scene, camera } = frame;
  28005. const shadowType = renderer.shadowMap.type;
  28006. const depthVersion = shadowMap.depthTexture.version;
  28007. this._depthVersionCached = depthVersion;
  28008. const _shadowCameraLayer = shadow.camera.layers.mask;
  28009. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  28010. shadow.camera.layers.mask = camera.layers.mask;
  28011. }
  28012. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  28013. const currentMRT = renderer.getMRT();
  28014. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  28015. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  28016. scene.overrideMaterial = getShadowMaterial( light );
  28017. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  28018. renderer.setClearColor( 0x000000, 0 );
  28019. renderer.setRenderTarget( shadowMap );
  28020. this.renderShadow( frame );
  28021. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  28022. // vsm blur pass
  28023. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  28024. this.vsmPass( renderer );
  28025. }
  28026. shadow.camera.layers.mask = _shadowCameraLayer;
  28027. restoreRendererAndSceneState( renderer, scene, _rendererState );
  28028. }
  28029. /**
  28030. * For VSM additional render passes are required.
  28031. *
  28032. * @param {Renderer} renderer - A reference to the current renderer.
  28033. */
  28034. vsmPass( renderer ) {
  28035. const { shadow } = this;
  28036. const depth = this.shadowMap.depth;
  28037. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  28038. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  28039. renderer.setRenderTarget( this.vsmShadowMapVertical );
  28040. _quadMesh.material = this.vsmMaterialVertical;
  28041. _quadMesh.render( renderer );
  28042. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  28043. _quadMesh.material = this.vsmMaterialHorizontal;
  28044. _quadMesh.render( renderer );
  28045. }
  28046. /**
  28047. * Frees the internal resources of this shadow node.
  28048. */
  28049. dispose() {
  28050. this.shadowMap.dispose();
  28051. this.shadowMap = null;
  28052. if ( this.vsmShadowMapVertical !== null ) {
  28053. this.vsmShadowMapVertical.dispose();
  28054. this.vsmShadowMapVertical = null;
  28055. this.vsmMaterialVertical.dispose();
  28056. this.vsmMaterialVertical = null;
  28057. }
  28058. if ( this.vsmShadowMapHorizontal !== null ) {
  28059. this.vsmShadowMapHorizontal.dispose();
  28060. this.vsmShadowMapHorizontal = null;
  28061. this.vsmMaterialHorizontal.dispose();
  28062. this.vsmMaterialHorizontal = null;
  28063. }
  28064. super.dispose();
  28065. }
  28066. /**
  28067. * The implementation performs the update of the shadow map if necessary.
  28068. *
  28069. * @param {NodeFrame} frame - A reference to the current node frame.
  28070. */
  28071. updateBefore( frame ) {
  28072. const { shadow } = this;
  28073. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  28074. if ( needsUpdate ) {
  28075. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  28076. needsUpdate = false;
  28077. }
  28078. this._cameraFrameId[ frame.camera ] = frame.frameId;
  28079. }
  28080. if ( needsUpdate ) {
  28081. this.updateShadow( frame );
  28082. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  28083. shadow.needsUpdate = false;
  28084. }
  28085. }
  28086. }
  28087. }
  28088. /**
  28089. * TSL function for creating an instance of `ShadowNode`.
  28090. *
  28091. * @tsl
  28092. * @function
  28093. * @param {Light} light - The shadow casting light.
  28094. * @param {?LightShadow} [shadow] - The light shadow.
  28095. * @return {ShadowNode} The created shadow node.
  28096. */
  28097. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  28098. const _clearColor$1 = /*@__PURE__*/ new Color();
  28099. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  28100. // vector suitable for 2D texture mapping. This code uses the following layout for the
  28101. // 2D texture:
  28102. //
  28103. // xzXZ
  28104. // y Y
  28105. //
  28106. // Y - Positive y direction
  28107. // y - Negative y direction
  28108. // X - Positive x direction
  28109. // x - Negative x direction
  28110. // Z - Positive z direction
  28111. // z - Negative z direction
  28112. //
  28113. // Source and test bed:
  28114. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  28115. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  28116. const v = pos.toVar();
  28117. // Number of texels to avoid at the edge of each square
  28118. const absV = abs( v );
  28119. // Intersect unit cube
  28120. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  28121. absV.mulAssign( scaleToCube );
  28122. // Apply scale to avoid seams
  28123. // two texels less per square (one texel will do for NEAREST)
  28124. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  28125. // Unwrap
  28126. // space: -1 ... 1 range for each square
  28127. //
  28128. // #X## dim := ( 4 , 2 )
  28129. // # # center := ( 1 , 1 )
  28130. const planar = vec2( v.xy ).toVar();
  28131. const almostATexel = texelSizeY.mul( 1.5 );
  28132. const almostOne = almostATexel.oneMinus();
  28133. If( absV.z.greaterThanEqual( almostOne ), () => {
  28134. If( v.z.greaterThan( 0.0 ), () => {
  28135. planar.x.assign( sub( 4.0, v.x ) );
  28136. } );
  28137. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  28138. const signX = sign( v.x );
  28139. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  28140. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  28141. const signY = sign( v.y );
  28142. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  28143. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  28144. } );
  28145. // Transform to UV space
  28146. // scale := 0.5 / dim
  28147. // translate := ( center + 0.5 ) / dim
  28148. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  28149. } ).setLayout( {
  28150. name: 'cubeToUV',
  28151. type: 'vec2',
  28152. inputs: [
  28153. { name: 'pos', type: 'vec3' },
  28154. { name: 'texelSizeY', type: 'float' }
  28155. ]
  28156. } );
  28157. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  28158. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  28159. } );
  28160. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  28161. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28162. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  28163. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  28164. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  28165. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  28166. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  28167. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  28168. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  28169. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  28170. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  28171. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  28172. .mul( 1.0 / 9.0 );
  28173. } );
  28174. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  28175. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  28176. // the vector from the light to the world-space position of the fragment.
  28177. const lightToPosition = shadowCoord.xyz.toVar();
  28178. const lightToPositionLength = lightToPosition.length();
  28179. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  28180. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  28181. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  28182. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  28183. const result = float( 1.0 ).toVar();
  28184. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  28185. // dp = normalized distance from light to fragment position
  28186. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  28187. dp.addAssign( bias );
  28188. // bd3D = base direction 3D
  28189. const bd3D = lightToPosition.normalize();
  28190. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  28191. // percentage-closer filtering
  28192. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  28193. } );
  28194. return result;
  28195. } );
  28196. const _viewport = /*@__PURE__*/ new Vector4();
  28197. const _viewportSize = /*@__PURE__*/ new Vector2();
  28198. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  28199. /**
  28200. * Represents the shadow implementation for point light nodes.
  28201. *
  28202. * @augments ShadowNode
  28203. */
  28204. class PointShadowNode extends ShadowNode {
  28205. static get type() {
  28206. return 'PointShadowNode';
  28207. }
  28208. /**
  28209. * Constructs a new point shadow node.
  28210. *
  28211. * @param {PointLight} light - The shadow casting point light.
  28212. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  28213. */
  28214. constructor( light, shadow = null ) {
  28215. super( light, shadow );
  28216. }
  28217. /**
  28218. * Overwrites the default implementation to return point light shadow specific
  28219. * filtering functions.
  28220. *
  28221. * @param {number} type - The shadow type.
  28222. * @return {Function} The filtering function.
  28223. */
  28224. getShadowFilterFn( type ) {
  28225. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  28226. }
  28227. /**
  28228. * Overwrites the default implementation so the unaltered shadow position is used.
  28229. *
  28230. * @param {NodeBuilder} builder - A reference to the current node builder.
  28231. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  28232. * @return {Node<vec3>} The shadow coordinates.
  28233. */
  28234. setupShadowCoord( builder, shadowPosition ) {
  28235. return shadowPosition;
  28236. }
  28237. /**
  28238. * Overwrites the default implementation to only use point light specific
  28239. * shadow filter functions.
  28240. *
  28241. * @param {NodeBuilder} builder - A reference to the current node builder.
  28242. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  28243. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  28244. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  28245. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28246. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  28247. * @param {LightShadow} inputs.shadow - The light shadow.
  28248. * @return {Node<float>} The result node of the shadow filtering.
  28249. */
  28250. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  28251. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  28252. }
  28253. /**
  28254. * Overwrites the default implementation with point light specific
  28255. * rendering code.
  28256. *
  28257. * @param {NodeFrame} frame - A reference to the current node frame.
  28258. */
  28259. renderShadow( frame ) {
  28260. const { shadow, shadowMap, light } = this;
  28261. const { renderer, scene } = frame;
  28262. const shadowFrameExtents = shadow.getFrameExtents();
  28263. _shadowMapSize.copy( shadow.mapSize );
  28264. _shadowMapSize.multiply( shadowFrameExtents );
  28265. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  28266. _viewportSize.copy( shadow.mapSize );
  28267. //
  28268. const previousAutoClear = renderer.autoClear;
  28269. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  28270. const previousClearAlpha = renderer.getClearAlpha();
  28271. renderer.autoClear = false;
  28272. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  28273. renderer.clear();
  28274. const viewportCount = shadow.getViewportCount();
  28275. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  28276. const viewport = shadow.getViewport( vp );
  28277. const x = _viewportSize.x * viewport.x;
  28278. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  28279. _viewport.set(
  28280. x,
  28281. y,
  28282. _viewportSize.x * viewport.z,
  28283. _viewportSize.y * viewport.w
  28284. );
  28285. shadowMap.viewport.copy( _viewport );
  28286. shadow.updateMatrices( light, vp );
  28287. renderer.render( scene, shadow.camera );
  28288. }
  28289. //
  28290. renderer.autoClear = previousAutoClear;
  28291. renderer.setClearColor( previousClearColor, previousClearAlpha );
  28292. }
  28293. }
  28294. /**
  28295. * TSL function for creating an instance of `PointShadowNode`.
  28296. *
  28297. * @tsl
  28298. * @function
  28299. * @param {PointLight} light - The shadow casting point light.
  28300. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  28301. * @return {PointShadowNode} The created point shadow node.
  28302. */
  28303. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  28304. /**
  28305. * Base class for analytic light nodes.
  28306. *
  28307. * @augments LightingNode
  28308. */
  28309. class AnalyticLightNode extends LightingNode {
  28310. static get type() {
  28311. return 'AnalyticLightNode';
  28312. }
  28313. /**
  28314. * Constructs a new analytic light node.
  28315. *
  28316. * @param {?Light} [light=null] - The light source.
  28317. */
  28318. constructor( light = null ) {
  28319. super();
  28320. /**
  28321. * The light source.
  28322. *
  28323. * @type {?Light}
  28324. * @default null
  28325. */
  28326. this.light = light;
  28327. /**
  28328. * The light's color value.
  28329. *
  28330. * @type {Color}
  28331. */
  28332. this.color = new Color();
  28333. /**
  28334. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  28335. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  28336. *
  28337. * @type {Node}
  28338. */
  28339. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  28340. /**
  28341. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  28342. * The final color node is represented by a different node when using shadows.
  28343. *
  28344. * @type {?Node}
  28345. * @default null
  28346. */
  28347. this.baseColorNode = null;
  28348. /**
  28349. * Represents the light's shadow.
  28350. *
  28351. * @type {?ShadowNode}
  28352. * @default null
  28353. */
  28354. this.shadowNode = null;
  28355. /**
  28356. * Represents the light's shadow color.
  28357. *
  28358. * @type {?Node}
  28359. * @default null
  28360. */
  28361. this.shadowColorNode = null;
  28362. /**
  28363. * This flag can be used for type testing.
  28364. *
  28365. * @type {boolean}
  28366. * @readonly
  28367. * @default true
  28368. */
  28369. this.isAnalyticLightNode = true;
  28370. /**
  28371. * Overwritten since analytic light nodes are updated
  28372. * once per frame.
  28373. *
  28374. * @type {string}
  28375. * @default 'frame'
  28376. */
  28377. this.updateType = NodeUpdateType.FRAME;
  28378. }
  28379. getHash() {
  28380. return this.light.uuid;
  28381. }
  28382. /**
  28383. * Returns a node representing a direction vector which points from the current
  28384. * position in view space to the light's position in view space.
  28385. *
  28386. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28387. * @return {Node<vec3>} The light vector node.
  28388. */
  28389. getLightVector( builder ) {
  28390. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  28391. }
  28392. /**
  28393. * Sets up the direct lighting for the analytic light node.
  28394. *
  28395. * @abstract
  28396. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28397. * @return {Object|undefined} The direct light data (color and direction).
  28398. */
  28399. setupDirect( /*builder*/ ) { }
  28400. /**
  28401. * Sets up the direct rect area lighting for the analytic light node.
  28402. *
  28403. * @abstract
  28404. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28405. * @return {Object|undefined} The direct rect area light data.
  28406. */
  28407. setupDirectRectArea( /*builder*/ ) { }
  28408. /**
  28409. * Setups the shadow node for this light. The method exists so concrete light classes
  28410. * can setup different types of shadow nodes.
  28411. *
  28412. * @return {ShadowNode} The created shadow node.
  28413. */
  28414. setupShadowNode() {
  28415. return shadow( this.light );
  28416. }
  28417. /**
  28418. * Setups the shadow for this light. This method is only executed if the light
  28419. * cast shadows and the current build object receives shadows. It incorporates
  28420. * shadows into the lighting computation.
  28421. *
  28422. * @param {NodeBuilder} builder - The current node builder.
  28423. */
  28424. setupShadow( builder ) {
  28425. const { renderer } = builder;
  28426. if ( renderer.shadowMap.enabled === false ) return;
  28427. let shadowColorNode = this.shadowColorNode;
  28428. if ( shadowColorNode === null ) {
  28429. const customShadowNode = this.light.shadow.shadowNode;
  28430. let shadowNode;
  28431. if ( customShadowNode !== undefined ) {
  28432. shadowNode = nodeObject( customShadowNode );
  28433. } else {
  28434. shadowNode = this.setupShadowNode();
  28435. }
  28436. this.shadowNode = shadowNode;
  28437. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  28438. this.baseColorNode = this.colorNode;
  28439. }
  28440. //
  28441. this.colorNode = shadowColorNode;
  28442. }
  28443. /**
  28444. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  28445. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  28446. * invocate the respective interface methods.
  28447. *
  28448. * @param {NodeBuilder} builder - The current node builder.
  28449. */
  28450. setup( builder ) {
  28451. this.colorNode = this.baseColorNode || this.colorNode;
  28452. if ( this.light.castShadow ) {
  28453. if ( builder.object.receiveShadow ) {
  28454. this.setupShadow( builder );
  28455. }
  28456. } else if ( this.shadowNode !== null ) {
  28457. this.shadowNode.dispose();
  28458. this.shadowNode = null;
  28459. this.shadowColorNode = null;
  28460. }
  28461. const directLightData = this.setupDirect( builder );
  28462. const directRectAreaLightData = this.setupDirectRectArea( builder );
  28463. if ( directLightData ) {
  28464. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  28465. }
  28466. if ( directRectAreaLightData ) {
  28467. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  28468. }
  28469. }
  28470. /**
  28471. * The update method is used to update light uniforms per frame.
  28472. * Potentially overwritten in concrete light nodes to update light
  28473. * specific uniforms.
  28474. *
  28475. * @param {NodeFrame} frame - A reference to the current node frame.
  28476. */
  28477. update( /*frame*/ ) {
  28478. const { light } = this;
  28479. this.color.copy( light.color ).multiplyScalar( light.intensity );
  28480. }
  28481. }
  28482. /**
  28483. * Represents a `discard` shader operation in TSL.
  28484. *
  28485. * @method
  28486. * @param {Object} inputs - The input parameter object.
  28487. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  28488. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  28489. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  28490. * @return {Node<float>} The distance falloff.
  28491. */
  28492. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  28493. // based upon Frostbite 3 Moving to Physically-based Rendering
  28494. // page 32, equation 26: E[window1]
  28495. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  28496. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  28497. return cutoffDistance.greaterThan( 0 ).select(
  28498. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  28499. distanceFalloff
  28500. );
  28501. } ); // validated
  28502. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  28503. const lightDirection = lightVector.normalize();
  28504. const lightDistance = lightVector.length();
  28505. const attenuation = getDistanceAttenuation( {
  28506. lightDistance,
  28507. cutoffDistance,
  28508. decayExponent
  28509. } );
  28510. const lightColor = color.mul( attenuation );
  28511. return { lightDirection, lightColor };
  28512. };
  28513. /**
  28514. * Module for representing point lights as nodes.
  28515. *
  28516. * @augments AnalyticLightNode
  28517. */
  28518. class PointLightNode extends AnalyticLightNode {
  28519. static get type() {
  28520. return 'PointLightNode';
  28521. }
  28522. /**
  28523. * Constructs a new point light node.
  28524. *
  28525. * @param {?PointLight} [light=null] - The point light source.
  28526. */
  28527. constructor( light = null ) {
  28528. super( light );
  28529. /**
  28530. * Uniform node representing the cutoff distance.
  28531. *
  28532. * @type {UniformNode<float>}
  28533. */
  28534. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  28535. /**
  28536. * Uniform node representing the decay exponent.
  28537. *
  28538. * @type {UniformNode<float>}
  28539. */
  28540. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  28541. }
  28542. /**
  28543. * Overwritten to updated point light specific uniforms.
  28544. *
  28545. * @param {NodeFrame} frame - A reference to the current node frame.
  28546. */
  28547. update( frame ) {
  28548. const { light } = this;
  28549. super.update( frame );
  28550. this.cutoffDistanceNode.value = light.distance;
  28551. this.decayExponentNode.value = light.decay;
  28552. }
  28553. /**
  28554. * Overwritten to setup point light specific shadow.
  28555. *
  28556. * @return {PointShadowNode}
  28557. */
  28558. setupShadowNode() {
  28559. return pointShadow( this.light );
  28560. }
  28561. setupDirect( builder ) {
  28562. return directPointLight( {
  28563. color: this.colorNode,
  28564. lightVector: this.getLightVector( builder ),
  28565. cutoffDistance: this.cutoffDistanceNode,
  28566. decayExponent: this.decayExponentNode
  28567. } );
  28568. }
  28569. }
  28570. /**
  28571. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  28572. *
  28573. * @tsl
  28574. * @function
  28575. * @param {Node<vec2>} coord - The uv coordinates.
  28576. * @return {Node<float>} The result data.
  28577. */
  28578. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  28579. const uv = coord.mul( 2.0 );
  28580. const cx = uv.x.floor();
  28581. const cy = uv.y.floor();
  28582. const result = cx.add( cy ).mod( 2.0 );
  28583. return result.sign();
  28584. } );
  28585. /**
  28586. * Generates a circle based on the uv coordinates.
  28587. *
  28588. * @tsl
  28589. * @function
  28590. * @param {Node<vec2>} coord - The uv to generate the circle.
  28591. * @return {Node<float>} The circle shape.
  28592. */
  28593. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  28594. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  28595. let alpha;
  28596. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  28597. const dlen = float( len2.fwidth() ).toVar();
  28598. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  28599. } else {
  28600. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  28601. }
  28602. return alpha;
  28603. } );
  28604. // Three.js Transpiler
  28605. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  28606. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  28607. const f = float( f_immutable ).toVar();
  28608. const t = float( t_immutable ).toVar();
  28609. const b = bool( b_immutable ).toVar();
  28610. return select( b, t, f );
  28611. } ).setLayout( {
  28612. name: 'mx_select',
  28613. type: 'float',
  28614. inputs: [
  28615. { name: 'b', type: 'bool' },
  28616. { name: 't', type: 'float' },
  28617. { name: 'f', type: 'float' }
  28618. ]
  28619. } );
  28620. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  28621. const b = bool( b_immutable ).toVar();
  28622. const val = float( val_immutable ).toVar();
  28623. return select( b, val.negate(), val );
  28624. } ).setLayout( {
  28625. name: 'mx_negate_if',
  28626. type: 'float',
  28627. inputs: [
  28628. { name: 'val', type: 'float' },
  28629. { name: 'b', type: 'bool' }
  28630. ]
  28631. } );
  28632. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28633. const x = float( x_immutable ).toVar();
  28634. return int( floor( x ) );
  28635. } ).setLayout( {
  28636. name: 'mx_floor',
  28637. type: 'int',
  28638. inputs: [
  28639. { name: 'x', type: 'float' }
  28640. ]
  28641. } );
  28642. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  28643. const x = float( x_immutable ).toVar();
  28644. i.assign( mx_floor( x ) );
  28645. return x.sub( float( i ) );
  28646. } );
  28647. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  28648. const t = float( t_immutable ).toVar();
  28649. const s = float( s_immutable ).toVar();
  28650. const v3 = float( v3_immutable ).toVar();
  28651. const v2 = float( v2_immutable ).toVar();
  28652. const v1 = float( v1_immutable ).toVar();
  28653. const v0 = float( v0_immutable ).toVar();
  28654. const s1 = float( sub( 1.0, s ) ).toVar();
  28655. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  28656. } ).setLayout( {
  28657. name: 'mx_bilerp_0',
  28658. type: 'float',
  28659. inputs: [
  28660. { name: 'v0', type: 'float' },
  28661. { name: 'v1', type: 'float' },
  28662. { name: 'v2', type: 'float' },
  28663. { name: 'v3', type: 'float' },
  28664. { name: 's', type: 'float' },
  28665. { name: 't', type: 'float' }
  28666. ]
  28667. } );
  28668. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  28669. const t = float( t_immutable ).toVar();
  28670. const s = float( s_immutable ).toVar();
  28671. const v3 = vec3( v3_immutable ).toVar();
  28672. const v2 = vec3( v2_immutable ).toVar();
  28673. const v1 = vec3( v1_immutable ).toVar();
  28674. const v0 = vec3( v0_immutable ).toVar();
  28675. const s1 = float( sub( 1.0, s ) ).toVar();
  28676. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  28677. } ).setLayout( {
  28678. name: 'mx_bilerp_1',
  28679. type: 'vec3',
  28680. inputs: [
  28681. { name: 'v0', type: 'vec3' },
  28682. { name: 'v1', type: 'vec3' },
  28683. { name: 'v2', type: 'vec3' },
  28684. { name: 'v3', type: 'vec3' },
  28685. { name: 's', type: 'float' },
  28686. { name: 't', type: 'float' }
  28687. ]
  28688. } );
  28689. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  28690. const mx_trilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  28691. const r = float( r_immutable ).toVar();
  28692. const t = float( t_immutable ).toVar();
  28693. const s = float( s_immutable ).toVar();
  28694. const v7 = float( v7_immutable ).toVar();
  28695. const v6 = float( v6_immutable ).toVar();
  28696. const v5 = float( v5_immutable ).toVar();
  28697. const v4 = float( v4_immutable ).toVar();
  28698. const v3 = float( v3_immutable ).toVar();
  28699. const v2 = float( v2_immutable ).toVar();
  28700. const v1 = float( v1_immutable ).toVar();
  28701. const v0 = float( v0_immutable ).toVar();
  28702. const s1 = float( sub( 1.0, s ) ).toVar();
  28703. const t1 = float( sub( 1.0, t ) ).toVar();
  28704. const r1 = float( sub( 1.0, r ) ).toVar();
  28705. return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) );
  28706. } ).setLayout( {
  28707. name: 'mx_trilerp_0',
  28708. type: 'float',
  28709. inputs: [
  28710. { name: 'v0', type: 'float' },
  28711. { name: 'v1', type: 'float' },
  28712. { name: 'v2', type: 'float' },
  28713. { name: 'v3', type: 'float' },
  28714. { name: 'v4', type: 'float' },
  28715. { name: 'v5', type: 'float' },
  28716. { name: 'v6', type: 'float' },
  28717. { name: 'v7', type: 'float' },
  28718. { name: 's', type: 'float' },
  28719. { name: 't', type: 'float' },
  28720. { name: 'r', type: 'float' }
  28721. ]
  28722. } );
  28723. const mx_trilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  28724. const r = float( r_immutable ).toVar();
  28725. const t = float( t_immutable ).toVar();
  28726. const s = float( s_immutable ).toVar();
  28727. const v7 = vec3( v7_immutable ).toVar();
  28728. const v6 = vec3( v6_immutable ).toVar();
  28729. const v5 = vec3( v5_immutable ).toVar();
  28730. const v4 = vec3( v4_immutable ).toVar();
  28731. const v3 = vec3( v3_immutable ).toVar();
  28732. const v2 = vec3( v2_immutable ).toVar();
  28733. const v1 = vec3( v1_immutable ).toVar();
  28734. const v0 = vec3( v0_immutable ).toVar();
  28735. const s1 = float( sub( 1.0, s ) ).toVar();
  28736. const t1 = float( sub( 1.0, t ) ).toVar();
  28737. const r1 = float( sub( 1.0, r ) ).toVar();
  28738. return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) );
  28739. } ).setLayout( {
  28740. name: 'mx_trilerp_1',
  28741. type: 'vec3',
  28742. inputs: [
  28743. { name: 'v0', type: 'vec3' },
  28744. { name: 'v1', type: 'vec3' },
  28745. { name: 'v2', type: 'vec3' },
  28746. { name: 'v3', type: 'vec3' },
  28747. { name: 'v4', type: 'vec3' },
  28748. { name: 'v5', type: 'vec3' },
  28749. { name: 'v6', type: 'vec3' },
  28750. { name: 'v7', type: 'vec3' },
  28751. { name: 's', type: 'float' },
  28752. { name: 't', type: 'float' },
  28753. { name: 'r', type: 'float' }
  28754. ]
  28755. } );
  28756. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  28757. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  28758. const y = float( y_immutable ).toVar();
  28759. const x = float( x_immutable ).toVar();
  28760. const hash = uint( hash_immutable ).toVar();
  28761. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  28762. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  28763. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  28764. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  28765. } ).setLayout( {
  28766. name: 'mx_gradient_float_0',
  28767. type: 'float',
  28768. inputs: [
  28769. { name: 'hash', type: 'uint' },
  28770. { name: 'x', type: 'float' },
  28771. { name: 'y', type: 'float' }
  28772. ]
  28773. } );
  28774. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  28775. const z = float( z_immutable ).toVar();
  28776. const y = float( y_immutable ).toVar();
  28777. const x = float( x_immutable ).toVar();
  28778. const hash = uint( hash_immutable ).toVar();
  28779. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  28780. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  28781. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  28782. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  28783. } ).setLayout( {
  28784. name: 'mx_gradient_float_1',
  28785. type: 'float',
  28786. inputs: [
  28787. { name: 'hash', type: 'uint' },
  28788. { name: 'x', type: 'float' },
  28789. { name: 'y', type: 'float' },
  28790. { name: 'z', type: 'float' }
  28791. ]
  28792. } );
  28793. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  28794. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  28795. const y = float( y_immutable ).toVar();
  28796. const x = float( x_immutable ).toVar();
  28797. const hash = uvec3( hash_immutable ).toVar();
  28798. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  28799. } ).setLayout( {
  28800. name: 'mx_gradient_vec3_0',
  28801. type: 'vec3',
  28802. inputs: [
  28803. { name: 'hash', type: 'uvec3' },
  28804. { name: 'x', type: 'float' },
  28805. { name: 'y', type: 'float' }
  28806. ]
  28807. } );
  28808. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  28809. const z = float( z_immutable ).toVar();
  28810. const y = float( y_immutable ).toVar();
  28811. const x = float( x_immutable ).toVar();
  28812. const hash = uvec3( hash_immutable ).toVar();
  28813. return vec3( mx_gradient_float( hash.x, x, y, z ), mx_gradient_float( hash.y, x, y, z ), mx_gradient_float( hash.z, x, y, z ) );
  28814. } ).setLayout( {
  28815. name: 'mx_gradient_vec3_1',
  28816. type: 'vec3',
  28817. inputs: [
  28818. { name: 'hash', type: 'uvec3' },
  28819. { name: 'x', type: 'float' },
  28820. { name: 'y', type: 'float' },
  28821. { name: 'z', type: 'float' }
  28822. ]
  28823. } );
  28824. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  28825. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28826. const v = float( v_immutable ).toVar();
  28827. return mul( 0.6616, v );
  28828. } ).setLayout( {
  28829. name: 'mx_gradient_scale2d_0',
  28830. type: 'float',
  28831. inputs: [
  28832. { name: 'v', type: 'float' }
  28833. ]
  28834. } );
  28835. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28836. const v = float( v_immutable ).toVar();
  28837. return mul( 0.9820, v );
  28838. } ).setLayout( {
  28839. name: 'mx_gradient_scale3d_0',
  28840. type: 'float',
  28841. inputs: [
  28842. { name: 'v', type: 'float' }
  28843. ]
  28844. } );
  28845. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28846. const v = vec3( v_immutable ).toVar();
  28847. return mul( 0.6616, v );
  28848. } ).setLayout( {
  28849. name: 'mx_gradient_scale2d_1',
  28850. type: 'vec3',
  28851. inputs: [
  28852. { name: 'v', type: 'vec3' }
  28853. ]
  28854. } );
  28855. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  28856. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28857. const v = vec3( v_immutable ).toVar();
  28858. return mul( 0.9820, v );
  28859. } ).setLayout( {
  28860. name: 'mx_gradient_scale3d_1',
  28861. type: 'vec3',
  28862. inputs: [
  28863. { name: 'v', type: 'vec3' }
  28864. ]
  28865. } );
  28866. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  28867. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  28868. const k = int( k_immutable ).toVar();
  28869. const x = uint( x_immutable ).toVar();
  28870. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  28871. } ).setLayout( {
  28872. name: 'mx_rotl32',
  28873. type: 'uint',
  28874. inputs: [
  28875. { name: 'x', type: 'uint' },
  28876. { name: 'k', type: 'int' }
  28877. ]
  28878. } );
  28879. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  28880. a.subAssign( c );
  28881. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  28882. c.addAssign( b );
  28883. b.subAssign( a );
  28884. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  28885. a.addAssign( c );
  28886. c.subAssign( b );
  28887. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  28888. b.addAssign( a );
  28889. a.subAssign( c );
  28890. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  28891. c.addAssign( b );
  28892. b.subAssign( a );
  28893. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  28894. a.addAssign( c );
  28895. c.subAssign( b );
  28896. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  28897. b.addAssign( a );
  28898. } );
  28899. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  28900. const c = uint( c_immutable ).toVar();
  28901. const b = uint( b_immutable ).toVar();
  28902. const a = uint( a_immutable ).toVar();
  28903. c.bitXorAssign( b );
  28904. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  28905. a.bitXorAssign( c );
  28906. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  28907. b.bitXorAssign( a );
  28908. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  28909. c.bitXorAssign( b );
  28910. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  28911. a.bitXorAssign( c );
  28912. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  28913. b.bitXorAssign( a );
  28914. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  28915. c.bitXorAssign( b );
  28916. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  28917. return c;
  28918. } ).setLayout( {
  28919. name: 'mx_bjfinal',
  28920. type: 'uint',
  28921. inputs: [
  28922. { name: 'a', type: 'uint' },
  28923. { name: 'b', type: 'uint' },
  28924. { name: 'c', type: 'uint' }
  28925. ]
  28926. } );
  28927. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  28928. const bits = uint( bits_immutable ).toVar();
  28929. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  28930. } ).setLayout( {
  28931. name: 'mx_bits_to_01',
  28932. type: 'float',
  28933. inputs: [
  28934. { name: 'bits', type: 'uint' }
  28935. ]
  28936. } );
  28937. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  28938. const t = float( t_immutable ).toVar();
  28939. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  28940. } ).setLayout( {
  28941. name: 'mx_fade',
  28942. type: 'float',
  28943. inputs: [
  28944. { name: 't', type: 'float' }
  28945. ]
  28946. } );
  28947. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28948. const x = int( x_immutable ).toVar();
  28949. const len = uint( uint( 1 ) ).toVar();
  28950. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  28951. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  28952. } ).setLayout( {
  28953. name: 'mx_hash_int_0',
  28954. type: 'uint',
  28955. inputs: [
  28956. { name: 'x', type: 'int' }
  28957. ]
  28958. } );
  28959. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  28960. const y = int( y_immutable ).toVar();
  28961. const x = int( x_immutable ).toVar();
  28962. const len = uint( uint( 2 ) ).toVar();
  28963. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28964. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28965. a.addAssign( uint( x ) );
  28966. b.addAssign( uint( y ) );
  28967. return mx_bjfinal( a, b, c );
  28968. } ).setLayout( {
  28969. name: 'mx_hash_int_1',
  28970. type: 'uint',
  28971. inputs: [
  28972. { name: 'x', type: 'int' },
  28973. { name: 'y', type: 'int' }
  28974. ]
  28975. } );
  28976. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  28977. const z = int( z_immutable ).toVar();
  28978. const y = int( y_immutable ).toVar();
  28979. const x = int( x_immutable ).toVar();
  28980. const len = uint( uint( 3 ) ).toVar();
  28981. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28982. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28983. a.addAssign( uint( x ) );
  28984. b.addAssign( uint( y ) );
  28985. c.addAssign( uint( z ) );
  28986. return mx_bjfinal( a, b, c );
  28987. } ).setLayout( {
  28988. name: 'mx_hash_int_2',
  28989. type: 'uint',
  28990. inputs: [
  28991. { name: 'x', type: 'int' },
  28992. { name: 'y', type: 'int' },
  28993. { name: 'z', type: 'int' }
  28994. ]
  28995. } );
  28996. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  28997. const xx = int( xx_immutable ).toVar();
  28998. const z = int( z_immutable ).toVar();
  28999. const y = int( y_immutable ).toVar();
  29000. const x = int( x_immutable ).toVar();
  29001. const len = uint( uint( 4 ) ).toVar();
  29002. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29003. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29004. a.addAssign( uint( x ) );
  29005. b.addAssign( uint( y ) );
  29006. c.addAssign( uint( z ) );
  29007. mx_bjmix( a, b, c );
  29008. a.addAssign( uint( xx ) );
  29009. return mx_bjfinal( a, b, c );
  29010. } ).setLayout( {
  29011. name: 'mx_hash_int_3',
  29012. type: 'uint',
  29013. inputs: [
  29014. { name: 'x', type: 'int' },
  29015. { name: 'y', type: 'int' },
  29016. { name: 'z', type: 'int' },
  29017. { name: 'xx', type: 'int' }
  29018. ]
  29019. } );
  29020. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  29021. const yy = int( yy_immutable ).toVar();
  29022. const xx = int( xx_immutable ).toVar();
  29023. const z = int( z_immutable ).toVar();
  29024. const y = int( y_immutable ).toVar();
  29025. const x = int( x_immutable ).toVar();
  29026. const len = uint( uint( 5 ) ).toVar();
  29027. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29028. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29029. a.addAssign( uint( x ) );
  29030. b.addAssign( uint( y ) );
  29031. c.addAssign( uint( z ) );
  29032. mx_bjmix( a, b, c );
  29033. a.addAssign( uint( xx ) );
  29034. b.addAssign( uint( yy ) );
  29035. return mx_bjfinal( a, b, c );
  29036. } ).setLayout( {
  29037. name: 'mx_hash_int_4',
  29038. type: 'uint',
  29039. inputs: [
  29040. { name: 'x', type: 'int' },
  29041. { name: 'y', type: 'int' },
  29042. { name: 'z', type: 'int' },
  29043. { name: 'xx', type: 'int' },
  29044. { name: 'yy', type: 'int' }
  29045. ]
  29046. } );
  29047. const mx_hash_int = /*@__PURE__*/ overloadingFn( [ mx_hash_int_0, mx_hash_int_1, mx_hash_int_2, mx_hash_int_3, mx_hash_int_4 ] );
  29048. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  29049. const y = int( y_immutable ).toVar();
  29050. const x = int( x_immutable ).toVar();
  29051. const h = uint( mx_hash_int( x, y ) ).toVar();
  29052. const result = uvec3().toVar();
  29053. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  29054. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  29055. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  29056. return result;
  29057. } ).setLayout( {
  29058. name: 'mx_hash_vec3_0',
  29059. type: 'uvec3',
  29060. inputs: [
  29061. { name: 'x', type: 'int' },
  29062. { name: 'y', type: 'int' }
  29063. ]
  29064. } );
  29065. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  29066. const z = int( z_immutable ).toVar();
  29067. const y = int( y_immutable ).toVar();
  29068. const x = int( x_immutable ).toVar();
  29069. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  29070. const result = uvec3().toVar();
  29071. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  29072. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  29073. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  29074. return result;
  29075. } ).setLayout( {
  29076. name: 'mx_hash_vec3_1',
  29077. type: 'uvec3',
  29078. inputs: [
  29079. { name: 'x', type: 'int' },
  29080. { name: 'y', type: 'int' },
  29081. { name: 'z', type: 'int' }
  29082. ]
  29083. } );
  29084. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  29085. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29086. const p = vec2( p_immutable ).toVar();
  29087. const X = int().toVar(), Y = int().toVar();
  29088. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29089. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29090. const u = float( mx_fade( fx ) ).toVar();
  29091. const v = float( mx_fade( fy ) ).toVar();
  29092. const result = float( mx_bilerp( mx_gradient_float( mx_hash_int( X, Y ), fx, fy ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar();
  29093. return mx_gradient_scale2d( result );
  29094. } ).setLayout( {
  29095. name: 'mx_perlin_noise_float_0',
  29096. type: 'float',
  29097. inputs: [
  29098. { name: 'p', type: 'vec2' }
  29099. ]
  29100. } );
  29101. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29102. const p = vec3( p_immutable ).toVar();
  29103. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29104. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29105. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29106. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  29107. const u = float( mx_fade( fx ) ).toVar();
  29108. const v = float( mx_fade( fy ) ).toVar();
  29109. const w = float( mx_fade( fz ) ).toVar();
  29110. const result = float( mx_trilerp( mx_gradient_float( mx_hash_int( X, Y, Z ), fx, fy, fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar();
  29111. return mx_gradient_scale3d( result );
  29112. } ).setLayout( {
  29113. name: 'mx_perlin_noise_float_1',
  29114. type: 'float',
  29115. inputs: [
  29116. { name: 'p', type: 'vec3' }
  29117. ]
  29118. } );
  29119. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  29120. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29121. const p = vec2( p_immutable ).toVar();
  29122. const X = int().toVar(), Y = int().toVar();
  29123. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29124. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29125. const u = float( mx_fade( fx ) ).toVar();
  29126. const v = float( mx_fade( fy ) ).toVar();
  29127. const result = vec3( mx_bilerp( mx_gradient_vec3( mx_hash_vec3( X, Y ), fx, fy ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar();
  29128. return mx_gradient_scale2d( result );
  29129. } ).setLayout( {
  29130. name: 'mx_perlin_noise_vec3_0',
  29131. type: 'vec3',
  29132. inputs: [
  29133. { name: 'p', type: 'vec2' }
  29134. ]
  29135. } );
  29136. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29137. const p = vec3( p_immutable ).toVar();
  29138. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29139. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29140. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29141. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  29142. const u = float( mx_fade( fx ) ).toVar();
  29143. const v = float( mx_fade( fy ) ).toVar();
  29144. const w = float( mx_fade( fz ) ).toVar();
  29145. const result = vec3( mx_trilerp( mx_gradient_vec3( mx_hash_vec3( X, Y, Z ), fx, fy, fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar();
  29146. return mx_gradient_scale3d( result );
  29147. } ).setLayout( {
  29148. name: 'mx_perlin_noise_vec3_1',
  29149. type: 'vec3',
  29150. inputs: [
  29151. { name: 'p', type: 'vec3' }
  29152. ]
  29153. } );
  29154. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  29155. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29156. const p = float( p_immutable ).toVar();
  29157. const ix = int( mx_floor( p ) ).toVar();
  29158. return mx_bits_to_01( mx_hash_int( ix ) );
  29159. } ).setLayout( {
  29160. name: 'mx_cell_noise_float_0',
  29161. type: 'float',
  29162. inputs: [
  29163. { name: 'p', type: 'float' }
  29164. ]
  29165. } );
  29166. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29167. const p = vec2( p_immutable ).toVar();
  29168. const ix = int( mx_floor( p.x ) ).toVar();
  29169. const iy = int( mx_floor( p.y ) ).toVar();
  29170. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  29171. } ).setLayout( {
  29172. name: 'mx_cell_noise_float_1',
  29173. type: 'float',
  29174. inputs: [
  29175. { name: 'p', type: 'vec2' }
  29176. ]
  29177. } );
  29178. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29179. const p = vec3( p_immutable ).toVar();
  29180. const ix = int( mx_floor( p.x ) ).toVar();
  29181. const iy = int( mx_floor( p.y ) ).toVar();
  29182. const iz = int( mx_floor( p.z ) ).toVar();
  29183. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  29184. } ).setLayout( {
  29185. name: 'mx_cell_noise_float_2',
  29186. type: 'float',
  29187. inputs: [
  29188. { name: 'p', type: 'vec3' }
  29189. ]
  29190. } );
  29191. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29192. const p = vec4( p_immutable ).toVar();
  29193. const ix = int( mx_floor( p.x ) ).toVar();
  29194. const iy = int( mx_floor( p.y ) ).toVar();
  29195. const iz = int( mx_floor( p.z ) ).toVar();
  29196. const iw = int( mx_floor( p.w ) ).toVar();
  29197. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  29198. } ).setLayout( {
  29199. name: 'mx_cell_noise_float_3',
  29200. type: 'float',
  29201. inputs: [
  29202. { name: 'p', type: 'vec4' }
  29203. ]
  29204. } );
  29205. const mx_cell_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_float_0, mx_cell_noise_float_1, mx_cell_noise_float_2, mx_cell_noise_float_3 ] );
  29206. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29207. const p = float( p_immutable ).toVar();
  29208. const ix = int( mx_floor( p ) ).toVar();
  29209. return vec3( mx_bits_to_01( mx_hash_int( ix, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 2 ) ) ) );
  29210. } ).setLayout( {
  29211. name: 'mx_cell_noise_vec3_0',
  29212. type: 'vec3',
  29213. inputs: [
  29214. { name: 'p', type: 'float' }
  29215. ]
  29216. } );
  29217. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29218. const p = vec2( p_immutable ).toVar();
  29219. const ix = int( mx_floor( p.x ) ).toVar();
  29220. const iy = int( mx_floor( p.y ) ).toVar();
  29221. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 2 ) ) ) );
  29222. } ).setLayout( {
  29223. name: 'mx_cell_noise_vec3_1',
  29224. type: 'vec3',
  29225. inputs: [
  29226. { name: 'p', type: 'vec2' }
  29227. ]
  29228. } );
  29229. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29230. const p = vec3( p_immutable ).toVar();
  29231. const ix = int( mx_floor( p.x ) ).toVar();
  29232. const iy = int( mx_floor( p.y ) ).toVar();
  29233. const iz = int( mx_floor( p.z ) ).toVar();
  29234. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 2 ) ) ) );
  29235. } ).setLayout( {
  29236. name: 'mx_cell_noise_vec3_2',
  29237. type: 'vec3',
  29238. inputs: [
  29239. { name: 'p', type: 'vec3' }
  29240. ]
  29241. } );
  29242. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29243. const p = vec4( p_immutable ).toVar();
  29244. const ix = int( mx_floor( p.x ) ).toVar();
  29245. const iy = int( mx_floor( p.y ) ).toVar();
  29246. const iz = int( mx_floor( p.z ) ).toVar();
  29247. const iw = int( mx_floor( p.w ) ).toVar();
  29248. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 2 ) ) ) );
  29249. } ).setLayout( {
  29250. name: 'mx_cell_noise_vec3_3',
  29251. type: 'vec3',
  29252. inputs: [
  29253. { name: 'p', type: 'vec4' }
  29254. ]
  29255. } );
  29256. const mx_cell_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_vec3_0, mx_cell_noise_vec3_1, mx_cell_noise_vec3_2, mx_cell_noise_vec3_3 ] );
  29257. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29258. const diminish = float( diminish_immutable ).toVar();
  29259. const lacunarity = float( lacunarity_immutable ).toVar();
  29260. const octaves = int( octaves_immutable ).toVar();
  29261. const p = vec3( p_immutable ).toVar();
  29262. const result = float( 0.0 ).toVar();
  29263. const amplitude = float( 1.0 ).toVar();
  29264. Loop( octaves, () => {
  29265. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  29266. amplitude.mulAssign( diminish );
  29267. p.mulAssign( lacunarity );
  29268. } );
  29269. return result;
  29270. } ).setLayout( {
  29271. name: 'mx_fractal_noise_float',
  29272. type: 'float',
  29273. inputs: [
  29274. { name: 'p', type: 'vec3' },
  29275. { name: 'octaves', type: 'int' },
  29276. { name: 'lacunarity', type: 'float' },
  29277. { name: 'diminish', type: 'float' }
  29278. ]
  29279. } );
  29280. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29281. const diminish = float( diminish_immutable ).toVar();
  29282. const lacunarity = float( lacunarity_immutable ).toVar();
  29283. const octaves = int( octaves_immutable ).toVar();
  29284. const p = vec3( p_immutable ).toVar();
  29285. const result = vec3( 0.0 ).toVar();
  29286. const amplitude = float( 1.0 ).toVar();
  29287. Loop( octaves, () => {
  29288. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  29289. amplitude.mulAssign( diminish );
  29290. p.mulAssign( lacunarity );
  29291. } );
  29292. return result;
  29293. } ).setLayout( {
  29294. name: 'mx_fractal_noise_vec3',
  29295. type: 'vec3',
  29296. inputs: [
  29297. { name: 'p', type: 'vec3' },
  29298. { name: 'octaves', type: 'int' },
  29299. { name: 'lacunarity', type: 'float' },
  29300. { name: 'diminish', type: 'float' }
  29301. ]
  29302. } );
  29303. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29304. const diminish = float( diminish_immutable ).toVar();
  29305. const lacunarity = float( lacunarity_immutable ).toVar();
  29306. const octaves = int( octaves_immutable ).toVar();
  29307. const p = vec3( p_immutable ).toVar();
  29308. return vec2( mx_fractal_noise_float$1( p, octaves, lacunarity, diminish ), mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) );
  29309. } ).setLayout( {
  29310. name: 'mx_fractal_noise_vec2',
  29311. type: 'vec2',
  29312. inputs: [
  29313. { name: 'p', type: 'vec3' },
  29314. { name: 'octaves', type: 'int' },
  29315. { name: 'lacunarity', type: 'float' },
  29316. { name: 'diminish', type: 'float' }
  29317. ]
  29318. } );
  29319. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29320. const diminish = float( diminish_immutable ).toVar();
  29321. const lacunarity = float( lacunarity_immutable ).toVar();
  29322. const octaves = int( octaves_immutable ).toVar();
  29323. const p = vec3( p_immutable ).toVar();
  29324. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  29325. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  29326. return vec4( c, f );
  29327. } ).setLayout( {
  29328. name: 'mx_fractal_noise_vec4',
  29329. type: 'vec4',
  29330. inputs: [
  29331. { name: 'p', type: 'vec3' },
  29332. { name: 'octaves', type: 'int' },
  29333. { name: 'lacunarity', type: 'float' },
  29334. { name: 'diminish', type: 'float' }
  29335. ]
  29336. } );
  29337. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  29338. const metric = int( metric_immutable ).toVar();
  29339. const jitter = float( jitter_immutable ).toVar();
  29340. const yoff = int( yoff_immutable ).toVar();
  29341. const xoff = int( xoff_immutable ).toVar();
  29342. const y = int( y_immutable ).toVar();
  29343. const x = int( x_immutable ).toVar();
  29344. const p = vec2( p_immutable ).toVar();
  29345. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  29346. const off = vec2( tmp.x, tmp.y ).toVar();
  29347. off.subAssign( 0.5 );
  29348. off.mulAssign( jitter );
  29349. off.addAssign( 0.5 );
  29350. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  29351. const diff = vec2( cellpos.sub( p ) ).toVar();
  29352. If( metric.equal( int( 2 ) ), () => {
  29353. return abs( diff.x ).add( abs( diff.y ) );
  29354. } );
  29355. If( metric.equal( int( 3 ) ), () => {
  29356. return max$1( abs( diff.x ), abs( diff.y ) );
  29357. } );
  29358. return dot( diff, diff );
  29359. } ).setLayout( {
  29360. name: 'mx_worley_distance_0',
  29361. type: 'float',
  29362. inputs: [
  29363. { name: 'p', type: 'vec2' },
  29364. { name: 'x', type: 'int' },
  29365. { name: 'y', type: 'int' },
  29366. { name: 'xoff', type: 'int' },
  29367. { name: 'yoff', type: 'int' },
  29368. { name: 'jitter', type: 'float' },
  29369. { name: 'metric', type: 'int' }
  29370. ]
  29371. } );
  29372. const mx_worley_distance_1 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => {
  29373. const metric = int( metric_immutable ).toVar();
  29374. const jitter = float( jitter_immutable ).toVar();
  29375. const zoff = int( zoff_immutable ).toVar();
  29376. const yoff = int( yoff_immutable ).toVar();
  29377. const xoff = int( xoff_immutable ).toVar();
  29378. const z = int( z_immutable ).toVar();
  29379. const y = int( y_immutable ).toVar();
  29380. const x = int( x_immutable ).toVar();
  29381. const p = vec3( p_immutable ).toVar();
  29382. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  29383. off.subAssign( 0.5 );
  29384. off.mulAssign( jitter );
  29385. off.addAssign( 0.5 );
  29386. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  29387. const diff = vec3( cellpos.sub( p ) ).toVar();
  29388. If( metric.equal( int( 2 ) ), () => {
  29389. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  29390. } );
  29391. If( metric.equal( int( 3 ) ), () => {
  29392. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  29393. } );
  29394. return dot( diff, diff );
  29395. } ).setLayout( {
  29396. name: 'mx_worley_distance_1',
  29397. type: 'float',
  29398. inputs: [
  29399. { name: 'p', type: 'vec3' },
  29400. { name: 'x', type: 'int' },
  29401. { name: 'y', type: 'int' },
  29402. { name: 'z', type: 'int' },
  29403. { name: 'xoff', type: 'int' },
  29404. { name: 'yoff', type: 'int' },
  29405. { name: 'zoff', type: 'int' },
  29406. { name: 'jitter', type: 'float' },
  29407. { name: 'metric', type: 'int' }
  29408. ]
  29409. } );
  29410. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  29411. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29412. const metric = int( metric_immutable ).toVar();
  29413. const jitter = float( jitter_immutable ).toVar();
  29414. const p = vec2( p_immutable ).toVar();
  29415. const X = int().toVar(), Y = int().toVar();
  29416. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29417. const sqdist = float( 1e6 ).toVar();
  29418. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29419. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29420. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29421. sqdist.assign( min$1( sqdist, dist ) );
  29422. } );
  29423. } );
  29424. If( metric.equal( int( 0 ) ), () => {
  29425. sqdist.assign( sqrt( sqdist ) );
  29426. } );
  29427. return sqdist;
  29428. } ).setLayout( {
  29429. name: 'mx_worley_noise_float_0',
  29430. type: 'float',
  29431. inputs: [
  29432. { name: 'p', type: 'vec2' },
  29433. { name: 'jitter', type: 'float' },
  29434. { name: 'metric', type: 'int' }
  29435. ]
  29436. } );
  29437. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29438. const metric = int( metric_immutable ).toVar();
  29439. const jitter = float( jitter_immutable ).toVar();
  29440. const p = vec2( p_immutable ).toVar();
  29441. const X = int().toVar(), Y = int().toVar();
  29442. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29443. const sqdist = vec2( 1e6, 1e6 ).toVar();
  29444. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29445. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29446. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29447. If( dist.lessThan( sqdist.x ), () => {
  29448. sqdist.y.assign( sqdist.x );
  29449. sqdist.x.assign( dist );
  29450. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29451. sqdist.y.assign( dist );
  29452. } );
  29453. } );
  29454. } );
  29455. If( metric.equal( int( 0 ) ), () => {
  29456. sqdist.assign( sqrt( sqdist ) );
  29457. } );
  29458. return sqdist;
  29459. } ).setLayout( {
  29460. name: 'mx_worley_noise_vec2_0',
  29461. type: 'vec2',
  29462. inputs: [
  29463. { name: 'p', type: 'vec2' },
  29464. { name: 'jitter', type: 'float' },
  29465. { name: 'metric', type: 'int' }
  29466. ]
  29467. } );
  29468. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29469. const metric = int( metric_immutable ).toVar();
  29470. const jitter = float( jitter_immutable ).toVar();
  29471. const p = vec2( p_immutable ).toVar();
  29472. const X = int().toVar(), Y = int().toVar();
  29473. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29474. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  29475. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29476. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29477. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29478. If( dist.lessThan( sqdist.x ), () => {
  29479. sqdist.z.assign( sqdist.y );
  29480. sqdist.y.assign( sqdist.x );
  29481. sqdist.x.assign( dist );
  29482. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29483. sqdist.z.assign( sqdist.y );
  29484. sqdist.y.assign( dist );
  29485. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  29486. sqdist.z.assign( dist );
  29487. } );
  29488. } );
  29489. } );
  29490. If( metric.equal( int( 0 ) ), () => {
  29491. sqdist.assign( sqrt( sqdist ) );
  29492. } );
  29493. return sqdist;
  29494. } ).setLayout( {
  29495. name: 'mx_worley_noise_vec3_0',
  29496. type: 'vec3',
  29497. inputs: [
  29498. { name: 'p', type: 'vec2' },
  29499. { name: 'jitter', type: 'float' },
  29500. { name: 'metric', type: 'int' }
  29501. ]
  29502. } );
  29503. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29504. const metric = int( metric_immutable ).toVar();
  29505. const jitter = float( jitter_immutable ).toVar();
  29506. const p = vec3( p_immutable ).toVar();
  29507. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29508. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29509. const sqdist = float( 1e6 ).toVar();
  29510. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29511. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29512. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29513. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29514. sqdist.assign( min$1( sqdist, dist ) );
  29515. } );
  29516. } );
  29517. } );
  29518. If( metric.equal( int( 0 ) ), () => {
  29519. sqdist.assign( sqrt( sqdist ) );
  29520. } );
  29521. return sqdist;
  29522. } ).setLayout( {
  29523. name: 'mx_worley_noise_float_1',
  29524. type: 'float',
  29525. inputs: [
  29526. { name: 'p', type: 'vec3' },
  29527. { name: 'jitter', type: 'float' },
  29528. { name: 'metric', type: 'int' }
  29529. ]
  29530. } );
  29531. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  29532. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29533. const metric = int( metric_immutable ).toVar();
  29534. const jitter = float( jitter_immutable ).toVar();
  29535. const p = vec3( p_immutable ).toVar();
  29536. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29537. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29538. const sqdist = vec2( 1e6, 1e6 ).toVar();
  29539. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29540. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29541. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29542. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29543. If( dist.lessThan( sqdist.x ), () => {
  29544. sqdist.y.assign( sqdist.x );
  29545. sqdist.x.assign( dist );
  29546. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29547. sqdist.y.assign( dist );
  29548. } );
  29549. } );
  29550. } );
  29551. } );
  29552. If( metric.equal( int( 0 ) ), () => {
  29553. sqdist.assign( sqrt( sqdist ) );
  29554. } );
  29555. return sqdist;
  29556. } ).setLayout( {
  29557. name: 'mx_worley_noise_vec2_1',
  29558. type: 'vec2',
  29559. inputs: [
  29560. { name: 'p', type: 'vec3' },
  29561. { name: 'jitter', type: 'float' },
  29562. { name: 'metric', type: 'int' }
  29563. ]
  29564. } );
  29565. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  29566. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29567. const metric = int( metric_immutable ).toVar();
  29568. const jitter = float( jitter_immutable ).toVar();
  29569. const p = vec3( p_immutable ).toVar();
  29570. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29571. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29572. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  29573. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29574. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29575. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29576. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29577. If( dist.lessThan( sqdist.x ), () => {
  29578. sqdist.z.assign( sqdist.y );
  29579. sqdist.y.assign( sqdist.x );
  29580. sqdist.x.assign( dist );
  29581. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29582. sqdist.z.assign( sqdist.y );
  29583. sqdist.y.assign( dist );
  29584. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  29585. sqdist.z.assign( dist );
  29586. } );
  29587. } );
  29588. } );
  29589. } );
  29590. If( metric.equal( int( 0 ) ), () => {
  29591. sqdist.assign( sqrt( sqdist ) );
  29592. } );
  29593. return sqdist;
  29594. } ).setLayout( {
  29595. name: 'mx_worley_noise_vec3_1',
  29596. type: 'vec3',
  29597. inputs: [
  29598. { name: 'p', type: 'vec3' },
  29599. { name: 'jitter', type: 'float' },
  29600. { name: 'metric', type: 'int' }
  29601. ]
  29602. } );
  29603. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  29604. // Three.js Transpiler
  29605. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  29606. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  29607. const s = hsv.y;
  29608. const v = hsv.z;
  29609. const result = vec3().toVar();
  29610. If( s.lessThan( 0.0001 ), () => {
  29611. result.assign( vec3( v, v, v ) );
  29612. } ).Else( () => {
  29613. let h = hsv.x;
  29614. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  29615. const hi = int( trunc( h ) );
  29616. const f = h.sub( float( hi ) );
  29617. const p = v.mul( s.oneMinus() );
  29618. const q = v.mul( s.mul( f ).oneMinus() );
  29619. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  29620. If( hi.equal( int( 0 ) ), () => {
  29621. result.assign( vec3( v, t, p ) );
  29622. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  29623. result.assign( vec3( q, v, p ) );
  29624. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  29625. result.assign( vec3( p, v, t ) );
  29626. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  29627. result.assign( vec3( p, q, v ) );
  29628. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  29629. result.assign( vec3( t, p, v ) );
  29630. } ).Else( () => {
  29631. result.assign( vec3( v, p, q ) );
  29632. } );
  29633. } );
  29634. return result;
  29635. } ).setLayout( {
  29636. name: 'mx_hsvtorgb',
  29637. type: 'vec3',
  29638. inputs: [
  29639. { name: 'hsv', type: 'vec3' }
  29640. ]
  29641. } );
  29642. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  29643. const c = vec3( c_immutable ).toVar();
  29644. const r = float( c.x ).toVar();
  29645. const g = float( c.y ).toVar();
  29646. const b = float( c.z ).toVar();
  29647. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  29648. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  29649. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  29650. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  29651. v.assign( maxcomp );
  29652. If( maxcomp.greaterThan( 0.0 ), () => {
  29653. s.assign( delta.div( maxcomp ) );
  29654. } ).Else( () => {
  29655. s.assign( 0.0 );
  29656. } );
  29657. If( s.lessThanEqual( 0.0 ), () => {
  29658. h.assign( 0.0 );
  29659. } ).Else( () => {
  29660. If( r.greaterThanEqual( maxcomp ), () => {
  29661. h.assign( g.sub( b ).div( delta ) );
  29662. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  29663. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  29664. } ).Else( () => {
  29665. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  29666. } );
  29667. h.mulAssign( 1.0 / 6.0 );
  29668. If( h.lessThan( 0.0 ), () => {
  29669. h.addAssign( 1.0 );
  29670. } );
  29671. } );
  29672. return vec3( h, s, v );
  29673. } ).setLayout( {
  29674. name: 'mx_rgbtohsv',
  29675. type: 'vec3',
  29676. inputs: [
  29677. { name: 'c', type: 'vec3' }
  29678. ]
  29679. } );
  29680. // Three.js Transpiler
  29681. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  29682. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  29683. const color = vec3( color_immutable ).toVar();
  29684. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  29685. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  29686. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  29687. return mix( linSeg, powSeg, isAbove );
  29688. } ).setLayout( {
  29689. name: 'mx_srgb_texture_to_lin_rec709',
  29690. type: 'vec3',
  29691. inputs: [
  29692. { name: 'color', type: 'vec3' }
  29693. ]
  29694. } );
  29695. const mx_aastep = ( threshold, value ) => {
  29696. threshold = float( threshold );
  29697. value = float( value );
  29698. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  29699. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  29700. };
  29701. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  29702. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  29703. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  29704. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  29705. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  29706. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  29707. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  29708. const mx_safepower = ( in1, in2 = 1 ) => {
  29709. in1 = float( in1 );
  29710. return in1.abs().pow( in2 ).mul( in1.sign() );
  29711. };
  29712. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  29713. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29714. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29715. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29716. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  29717. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  29718. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  29719. return noise_vec4.mul( amplitude ).add( pivot );
  29720. };
  29721. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29722. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29723. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29724. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  29725. const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29726. const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29727. const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29728. const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29729. /**
  29730. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  29731. *
  29732. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  29733. *
  29734. * ```js
  29735. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  29736. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  29737. * ```
  29738. *
  29739. * @tsl
  29740. * @function
  29741. * @param {Node<vec3>} normal - The normal to correct.
  29742. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  29743. * @param {Node<vec3>} cubePos - The cube position.
  29744. * @return {Node<vec3>} The parallax corrected normal.
  29745. */
  29746. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  29747. const nDir = normalize( normal ).toVar();
  29748. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  29749. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  29750. const rbminmax = vec3().toVar();
  29751. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  29752. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  29753. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  29754. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar();
  29755. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  29756. return boxIntersection.sub( cubePos );
  29757. } );
  29758. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  29759. // normal is assumed to have unit length
  29760. const x = normal.x, y = normal.y, z = normal.z;
  29761. // band 0
  29762. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  29763. // band 1
  29764. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  29765. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  29766. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  29767. // band 2
  29768. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  29769. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  29770. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  29771. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  29772. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  29773. return result;
  29774. } );
  29775. // constants
  29776. var TSL = /*#__PURE__*/Object.freeze({
  29777. __proto__: null,
  29778. BRDF_GGX: BRDF_GGX,
  29779. BRDF_Lambert: BRDF_Lambert,
  29780. BasicPointShadowFilter: BasicPointShadowFilter,
  29781. BasicShadowFilter: BasicShadowFilter,
  29782. Break: Break,
  29783. Const: Const,
  29784. Continue: Continue,
  29785. DFGApprox: DFGApprox,
  29786. D_GGX: D_GGX,
  29787. Discard: Discard,
  29788. EPSILON: EPSILON,
  29789. F_Schlick: F_Schlick,
  29790. Fn: Fn,
  29791. INFINITY: INFINITY,
  29792. If: If,
  29793. Loop: Loop,
  29794. NodeAccess: NodeAccess,
  29795. NodeShaderStage: NodeShaderStage,
  29796. NodeType: NodeType,
  29797. NodeUpdateType: NodeUpdateType,
  29798. PCFShadowFilter: PCFShadowFilter,
  29799. PCFSoftShadowFilter: PCFSoftShadowFilter,
  29800. PI: PI,
  29801. PI2: PI2,
  29802. PointShadowFilter: PointShadowFilter,
  29803. Return: Return,
  29804. Schlick_to_F0: Schlick_to_F0,
  29805. ScriptableNodeResources: ScriptableNodeResources,
  29806. ShaderNode: ShaderNode,
  29807. Stack: Stack,
  29808. Switch: Switch,
  29809. TBNViewMatrix: TBNViewMatrix,
  29810. VSMShadowFilter: VSMShadowFilter,
  29811. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  29812. Var: Var,
  29813. abs: abs,
  29814. acesFilmicToneMapping: acesFilmicToneMapping,
  29815. acos: acos,
  29816. add: add,
  29817. addMethodChaining: addMethodChaining,
  29818. addNodeElement: addNodeElement,
  29819. agxToneMapping: agxToneMapping,
  29820. all: all,
  29821. alphaT: alphaT,
  29822. and: and,
  29823. anisotropy: anisotropy,
  29824. anisotropyB: anisotropyB,
  29825. anisotropyT: anisotropyT,
  29826. any: any,
  29827. append: append,
  29828. array: array,
  29829. arrayBuffer: arrayBuffer,
  29830. asin: asin,
  29831. assign: assign,
  29832. atan: atan,
  29833. atan2: atan2,
  29834. atomicAdd: atomicAdd,
  29835. atomicAnd: atomicAnd,
  29836. atomicFunc: atomicFunc,
  29837. atomicLoad: atomicLoad,
  29838. atomicMax: atomicMax,
  29839. atomicMin: atomicMin,
  29840. atomicOr: atomicOr,
  29841. atomicStore: atomicStore,
  29842. atomicSub: atomicSub,
  29843. atomicXor: atomicXor,
  29844. attenuationColor: attenuationColor,
  29845. attenuationDistance: attenuationDistance,
  29846. attribute: attribute,
  29847. attributeArray: attributeArray,
  29848. backgroundBlurriness: backgroundBlurriness,
  29849. backgroundIntensity: backgroundIntensity,
  29850. backgroundRotation: backgroundRotation,
  29851. batch: batch,
  29852. billboarding: billboarding,
  29853. bitAnd: bitAnd,
  29854. bitNot: bitNot,
  29855. bitOr: bitOr,
  29856. bitXor: bitXor,
  29857. bitangentGeometry: bitangentGeometry,
  29858. bitangentLocal: bitangentLocal,
  29859. bitangentView: bitangentView,
  29860. bitangentWorld: bitangentWorld,
  29861. bitcast: bitcast,
  29862. blendBurn: blendBurn,
  29863. blendColor: blendColor,
  29864. blendDodge: blendDodge,
  29865. blendOverlay: blendOverlay,
  29866. blendScreen: blendScreen,
  29867. blur: blur,
  29868. bool: bool,
  29869. buffer: buffer,
  29870. bufferAttribute: bufferAttribute,
  29871. bumpMap: bumpMap,
  29872. burn: burn,
  29873. bvec2: bvec2,
  29874. bvec3: bvec3,
  29875. bvec4: bvec4,
  29876. bypass: bypass,
  29877. cache: cache,
  29878. call: call,
  29879. cameraFar: cameraFar,
  29880. cameraIndex: cameraIndex,
  29881. cameraNear: cameraNear,
  29882. cameraNormalMatrix: cameraNormalMatrix,
  29883. cameraPosition: cameraPosition,
  29884. cameraProjectionMatrix: cameraProjectionMatrix,
  29885. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  29886. cameraViewMatrix: cameraViewMatrix,
  29887. cameraWorldMatrix: cameraWorldMatrix,
  29888. cbrt: cbrt,
  29889. cdl: cdl,
  29890. ceil: ceil,
  29891. checker: checker,
  29892. cineonToneMapping: cineonToneMapping,
  29893. clamp: clamp,
  29894. clearcoat: clearcoat,
  29895. clearcoatRoughness: clearcoatRoughness,
  29896. code: code,
  29897. color: color,
  29898. colorSpaceToWorking: colorSpaceToWorking,
  29899. colorToDirection: colorToDirection,
  29900. compute: compute,
  29901. computeSkinning: computeSkinning,
  29902. cond: cond,
  29903. context: context,
  29904. convert: convert,
  29905. convertColorSpace: convertColorSpace,
  29906. convertToTexture: convertToTexture,
  29907. cos: cos,
  29908. cross: cross,
  29909. cubeTexture: cubeTexture,
  29910. cubeToUV: cubeToUV,
  29911. dFdx: dFdx,
  29912. dFdy: dFdy,
  29913. dashSize: dashSize,
  29914. debug: debug,
  29915. decrement: decrement,
  29916. decrementBefore: decrementBefore,
  29917. defaultBuildStages: defaultBuildStages,
  29918. defaultShaderStages: defaultShaderStages,
  29919. defined: defined,
  29920. degrees: degrees,
  29921. deltaTime: deltaTime,
  29922. densityFog: densityFog,
  29923. densityFogFactor: densityFogFactor,
  29924. depth: depth,
  29925. depthPass: depthPass,
  29926. difference: difference,
  29927. diffuseColor: diffuseColor,
  29928. directPointLight: directPointLight,
  29929. directionToColor: directionToColor,
  29930. dispersion: dispersion,
  29931. distance: distance,
  29932. div: div,
  29933. dodge: dodge,
  29934. dot: dot,
  29935. drawIndex: drawIndex,
  29936. dynamicBufferAttribute: dynamicBufferAttribute,
  29937. element: element,
  29938. emissive: emissive,
  29939. equal: equal,
  29940. equals: equals,
  29941. equirectUV: equirectUV,
  29942. exp: exp,
  29943. exp2: exp2,
  29944. expression: expression,
  29945. faceDirection: faceDirection,
  29946. faceForward: faceForward,
  29947. faceforward: faceforward,
  29948. float: float,
  29949. floor: floor,
  29950. fog: fog,
  29951. fract: fract,
  29952. frameGroup: frameGroup,
  29953. frameId: frameId,
  29954. frontFacing: frontFacing,
  29955. fwidth: fwidth,
  29956. gain: gain,
  29957. gapSize: gapSize,
  29958. getConstNodeType: getConstNodeType,
  29959. getCurrentStack: getCurrentStack,
  29960. getDirection: getDirection,
  29961. getDistanceAttenuation: getDistanceAttenuation,
  29962. getGeometryRoughness: getGeometryRoughness,
  29963. getNormalFromDepth: getNormalFromDepth,
  29964. getParallaxCorrectNormal: getParallaxCorrectNormal,
  29965. getRoughness: getRoughness,
  29966. getScreenPosition: getScreenPosition,
  29967. getShIrradianceAt: getShIrradianceAt,
  29968. getShadowMaterial: getShadowMaterial,
  29969. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  29970. getTextureIndex: getTextureIndex,
  29971. getViewPosition: getViewPosition,
  29972. globalId: globalId,
  29973. glsl: glsl,
  29974. glslFn: glslFn,
  29975. grayscale: grayscale,
  29976. greaterThan: greaterThan,
  29977. greaterThanEqual: greaterThanEqual,
  29978. hash: hash,
  29979. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  29980. highpModelViewMatrix: highpModelViewMatrix,
  29981. hue: hue,
  29982. increment: increment,
  29983. incrementBefore: incrementBefore,
  29984. instance: instance,
  29985. instanceIndex: instanceIndex,
  29986. instancedArray: instancedArray,
  29987. instancedBufferAttribute: instancedBufferAttribute,
  29988. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  29989. instancedMesh: instancedMesh,
  29990. int: int,
  29991. inverseSqrt: inverseSqrt,
  29992. inversesqrt: inversesqrt,
  29993. invocationLocalIndex: invocationLocalIndex,
  29994. invocationSubgroupIndex: invocationSubgroupIndex,
  29995. ior: ior,
  29996. iridescence: iridescence,
  29997. iridescenceIOR: iridescenceIOR,
  29998. iridescenceThickness: iridescenceThickness,
  29999. ivec2: ivec2,
  30000. ivec3: ivec3,
  30001. ivec4: ivec4,
  30002. js: js,
  30003. label: label,
  30004. length: length,
  30005. lengthSq: lengthSq,
  30006. lessThan: lessThan,
  30007. lessThanEqual: lessThanEqual,
  30008. lightPosition: lightPosition,
  30009. lightProjectionUV: lightProjectionUV,
  30010. lightShadowMatrix: lightShadowMatrix,
  30011. lightTargetDirection: lightTargetDirection,
  30012. lightTargetPosition: lightTargetPosition,
  30013. lightViewPosition: lightViewPosition,
  30014. lightingContext: lightingContext,
  30015. lights: lights,
  30016. linearDepth: linearDepth,
  30017. linearToneMapping: linearToneMapping,
  30018. localId: localId,
  30019. log: log,
  30020. log2: log2,
  30021. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  30022. loop: loop,
  30023. luminance: luminance,
  30024. mat2: mat2,
  30025. mat3: mat3,
  30026. mat4: mat4,
  30027. matcapUV: matcapUV,
  30028. materialAO: materialAO,
  30029. materialAlphaTest: materialAlphaTest,
  30030. materialAnisotropy: materialAnisotropy,
  30031. materialAnisotropyVector: materialAnisotropyVector,
  30032. materialAttenuationColor: materialAttenuationColor,
  30033. materialAttenuationDistance: materialAttenuationDistance,
  30034. materialClearcoat: materialClearcoat,
  30035. materialClearcoatNormal: materialClearcoatNormal,
  30036. materialClearcoatRoughness: materialClearcoatRoughness,
  30037. materialColor: materialColor,
  30038. materialDispersion: materialDispersion,
  30039. materialEmissive: materialEmissive,
  30040. materialEnvIntensity: materialEnvIntensity,
  30041. materialEnvRotation: materialEnvRotation,
  30042. materialIOR: materialIOR,
  30043. materialIridescence: materialIridescence,
  30044. materialIridescenceIOR: materialIridescenceIOR,
  30045. materialIridescenceThickness: materialIridescenceThickness,
  30046. materialLightMap: materialLightMap,
  30047. materialLineDashOffset: materialLineDashOffset,
  30048. materialLineDashSize: materialLineDashSize,
  30049. materialLineGapSize: materialLineGapSize,
  30050. materialLineScale: materialLineScale,
  30051. materialLineWidth: materialLineWidth,
  30052. materialMetalness: materialMetalness,
  30053. materialNormal: materialNormal,
  30054. materialOpacity: materialOpacity,
  30055. materialPointSize: materialPointSize,
  30056. materialReference: materialReference,
  30057. materialReflectivity: materialReflectivity,
  30058. materialRefractionRatio: materialRefractionRatio,
  30059. materialRotation: materialRotation,
  30060. materialRoughness: materialRoughness,
  30061. materialSheen: materialSheen,
  30062. materialSheenRoughness: materialSheenRoughness,
  30063. materialShininess: materialShininess,
  30064. materialSpecular: materialSpecular,
  30065. materialSpecularColor: materialSpecularColor,
  30066. materialSpecularIntensity: materialSpecularIntensity,
  30067. materialSpecularStrength: materialSpecularStrength,
  30068. materialThickness: materialThickness,
  30069. materialTransmission: materialTransmission,
  30070. max: max$1,
  30071. maxMipLevel: maxMipLevel,
  30072. mediumpModelViewMatrix: mediumpModelViewMatrix,
  30073. metalness: metalness,
  30074. min: min$1,
  30075. mix: mix,
  30076. mixElement: mixElement,
  30077. mod: mod,
  30078. modInt: modInt,
  30079. modelDirection: modelDirection,
  30080. modelNormalMatrix: modelNormalMatrix,
  30081. modelPosition: modelPosition,
  30082. modelRadius: modelRadius,
  30083. modelScale: modelScale,
  30084. modelViewMatrix: modelViewMatrix,
  30085. modelViewPosition: modelViewPosition,
  30086. modelViewProjection: modelViewProjection,
  30087. modelWorldMatrix: modelWorldMatrix,
  30088. modelWorldMatrixInverse: modelWorldMatrixInverse,
  30089. morphReference: morphReference,
  30090. mrt: mrt,
  30091. mul: mul,
  30092. mx_aastep: mx_aastep,
  30093. mx_cell_noise_float: mx_cell_noise_float,
  30094. mx_contrast: mx_contrast,
  30095. mx_fractal_noise_float: mx_fractal_noise_float,
  30096. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  30097. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  30098. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  30099. mx_hsvtorgb: mx_hsvtorgb,
  30100. mx_noise_float: mx_noise_float,
  30101. mx_noise_vec3: mx_noise_vec3,
  30102. mx_noise_vec4: mx_noise_vec4,
  30103. mx_ramplr: mx_ramplr,
  30104. mx_ramptb: mx_ramptb,
  30105. mx_rgbtohsv: mx_rgbtohsv,
  30106. mx_safepower: mx_safepower,
  30107. mx_splitlr: mx_splitlr,
  30108. mx_splittb: mx_splittb,
  30109. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  30110. mx_transform_uv: mx_transform_uv,
  30111. mx_worley_noise_float: mx_worley_noise_float,
  30112. mx_worley_noise_vec2: mx_worley_noise_vec2,
  30113. mx_worley_noise_vec3: mx_worley_noise_vec3,
  30114. namespace: namespace,
  30115. negate: negate,
  30116. neutralToneMapping: neutralToneMapping,
  30117. nodeArray: nodeArray,
  30118. nodeImmutable: nodeImmutable,
  30119. nodeObject: nodeObject,
  30120. nodeObjects: nodeObjects,
  30121. nodeProxy: nodeProxy,
  30122. normalFlat: normalFlat,
  30123. normalGeometry: normalGeometry,
  30124. normalLocal: normalLocal,
  30125. normalMap: normalMap,
  30126. normalView: normalView,
  30127. normalWorld: normalWorld,
  30128. normalize: normalize,
  30129. not: not,
  30130. notEqual: notEqual,
  30131. numWorkgroups: numWorkgroups,
  30132. objectDirection: objectDirection,
  30133. objectGroup: objectGroup,
  30134. objectPosition: objectPosition,
  30135. objectRadius: objectRadius,
  30136. objectScale: objectScale,
  30137. objectViewPosition: objectViewPosition,
  30138. objectWorldMatrix: objectWorldMatrix,
  30139. oneMinus: oneMinus,
  30140. or: or,
  30141. orthographicDepthToViewZ: orthographicDepthToViewZ,
  30142. oscSawtooth: oscSawtooth,
  30143. oscSine: oscSine,
  30144. oscSquare: oscSquare,
  30145. oscTriangle: oscTriangle,
  30146. output: output,
  30147. outputStruct: outputStruct,
  30148. overlay: overlay,
  30149. overloadingFn: overloadingFn,
  30150. parabola: parabola,
  30151. parallaxDirection: parallaxDirection,
  30152. parallaxUV: parallaxUV,
  30153. parameter: parameter,
  30154. pass: pass,
  30155. passTexture: passTexture,
  30156. pcurve: pcurve,
  30157. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  30158. pmremTexture: pmremTexture,
  30159. pointShadow: pointShadow,
  30160. pointUV: pointUV,
  30161. pointWidth: pointWidth,
  30162. positionGeometry: positionGeometry,
  30163. positionLocal: positionLocal,
  30164. positionPrevious: positionPrevious,
  30165. positionView: positionView,
  30166. positionViewDirection: positionViewDirection,
  30167. positionWorld: positionWorld,
  30168. positionWorldDirection: positionWorldDirection,
  30169. posterize: posterize,
  30170. pow: pow,
  30171. pow2: pow2,
  30172. pow3: pow3,
  30173. pow4: pow4,
  30174. premult: premult,
  30175. property: property,
  30176. radians: radians,
  30177. rand: rand,
  30178. range: range,
  30179. rangeFog: rangeFog,
  30180. rangeFogFactor: rangeFogFactor,
  30181. reciprocal: reciprocal,
  30182. reference: reference,
  30183. referenceBuffer: referenceBuffer,
  30184. reflect: reflect,
  30185. reflectVector: reflectVector,
  30186. reflectView: reflectView,
  30187. reflector: reflector,
  30188. refract: refract,
  30189. refractVector: refractVector,
  30190. refractView: refractView,
  30191. reinhardToneMapping: reinhardToneMapping,
  30192. remainder: remainder,
  30193. remap: remap,
  30194. remapClamp: remapClamp,
  30195. renderGroup: renderGroup,
  30196. renderOutput: renderOutput,
  30197. rendererReference: rendererReference,
  30198. rotate: rotate,
  30199. rotateUV: rotateUV,
  30200. roughness: roughness,
  30201. round: round,
  30202. rtt: rtt,
  30203. sRGBTransferEOTF: sRGBTransferEOTF,
  30204. sRGBTransferOETF: sRGBTransferOETF,
  30205. sampler: sampler,
  30206. samplerComparison: samplerComparison,
  30207. saturate: saturate,
  30208. saturation: saturation,
  30209. screen: screen,
  30210. screenCoordinate: screenCoordinate,
  30211. screenSize: screenSize,
  30212. screenUV: screenUV,
  30213. scriptable: scriptable,
  30214. scriptableValue: scriptableValue,
  30215. select: select,
  30216. setCurrentStack: setCurrentStack,
  30217. shaderStages: shaderStages,
  30218. shadow: shadow,
  30219. shadowPositionWorld: shadowPositionWorld,
  30220. shapeCircle: shapeCircle,
  30221. sharedUniformGroup: sharedUniformGroup,
  30222. sheen: sheen,
  30223. sheenRoughness: sheenRoughness,
  30224. shiftLeft: shiftLeft,
  30225. shiftRight: shiftRight,
  30226. shininess: shininess,
  30227. sign: sign,
  30228. sin: sin,
  30229. sinc: sinc,
  30230. skinning: skinning,
  30231. smoothstep: smoothstep,
  30232. smoothstepElement: smoothstepElement,
  30233. specularColor: specularColor,
  30234. specularF90: specularF90,
  30235. spherizeUV: spherizeUV,
  30236. split: split,
  30237. spritesheetUV: spritesheetUV,
  30238. sqrt: sqrt,
  30239. stack: stack,
  30240. step: step,
  30241. storage: storage,
  30242. storageBarrier: storageBarrier,
  30243. storageObject: storageObject,
  30244. storageTexture: storageTexture,
  30245. string: string,
  30246. struct: struct,
  30247. sub: sub,
  30248. subgroupIndex: subgroupIndex,
  30249. subgroupSize: subgroupSize,
  30250. tan: tan,
  30251. tangentGeometry: tangentGeometry,
  30252. tangentLocal: tangentLocal,
  30253. tangentView: tangentView,
  30254. tangentWorld: tangentWorld,
  30255. temp: temp,
  30256. texture: texture,
  30257. texture3D: texture3D,
  30258. textureBarrier: textureBarrier,
  30259. textureBicubic: textureBicubic,
  30260. textureCubeUV: textureCubeUV,
  30261. textureLoad: textureLoad,
  30262. textureSize: textureSize,
  30263. textureStore: textureStore,
  30264. thickness: thickness,
  30265. time: time,
  30266. timerDelta: timerDelta,
  30267. timerGlobal: timerGlobal,
  30268. timerLocal: timerLocal,
  30269. toneMapping: toneMapping,
  30270. toneMappingExposure: toneMappingExposure,
  30271. toonOutlinePass: toonOutlinePass,
  30272. transformDirection: transformDirection,
  30273. transformNormal: transformNormal,
  30274. transformNormalToView: transformNormalToView,
  30275. transformedBentNormalView: transformedBentNormalView,
  30276. transformedBitangentView: transformedBitangentView,
  30277. transformedBitangentWorld: transformedBitangentWorld,
  30278. transformedClearcoatNormalView: transformedClearcoatNormalView,
  30279. transformedNormalView: transformedNormalView,
  30280. transformedNormalWorld: transformedNormalWorld,
  30281. transformedTangentView: transformedTangentView,
  30282. transformedTangentWorld: transformedTangentWorld,
  30283. transmission: transmission,
  30284. transpose: transpose,
  30285. triNoise3D: triNoise3D,
  30286. triplanarTexture: triplanarTexture,
  30287. triplanarTextures: triplanarTextures,
  30288. trunc: trunc,
  30289. tslFn: tslFn,
  30290. uint: uint,
  30291. uniform: uniform,
  30292. uniformArray: uniformArray,
  30293. uniformGroup: uniformGroup,
  30294. uniforms: uniforms,
  30295. unpremult: unpremult,
  30296. userData: userData,
  30297. uv: uv,
  30298. uvec2: uvec2,
  30299. uvec3: uvec3,
  30300. uvec4: uvec4,
  30301. varying: varying,
  30302. varyingProperty: varyingProperty,
  30303. vec2: vec2,
  30304. vec3: vec3,
  30305. vec4: vec4,
  30306. vectorComponents: vectorComponents,
  30307. velocity: velocity,
  30308. vertexColor: vertexColor,
  30309. vertexIndex: vertexIndex,
  30310. vertexStage: vertexStage,
  30311. vibrance: vibrance,
  30312. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  30313. viewZToOrthographicDepth: viewZToOrthographicDepth,
  30314. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  30315. viewport: viewport,
  30316. viewportBottomLeft: viewportBottomLeft,
  30317. viewportCoordinate: viewportCoordinate,
  30318. viewportDepthTexture: viewportDepthTexture,
  30319. viewportLinearDepth: viewportLinearDepth,
  30320. viewportMipTexture: viewportMipTexture,
  30321. viewportResolution: viewportResolution,
  30322. viewportSafeUV: viewportSafeUV,
  30323. viewportSharedTexture: viewportSharedTexture,
  30324. viewportSize: viewportSize,
  30325. viewportTexture: viewportTexture,
  30326. viewportTopLeft: viewportTopLeft,
  30327. viewportUV: viewportUV,
  30328. wgsl: wgsl,
  30329. wgslFn: wgslFn,
  30330. workgroupArray: workgroupArray,
  30331. workgroupBarrier: workgroupBarrier,
  30332. workgroupId: workgroupId,
  30333. workingToColorSpace: workingToColorSpace,
  30334. xor: xor
  30335. });
  30336. const _clearColor = /*@__PURE__*/ new Color4();
  30337. /**
  30338. * This renderer module manages the background.
  30339. *
  30340. * @private
  30341. * @augments DataMap
  30342. */
  30343. class Background extends DataMap {
  30344. /**
  30345. * Constructs a new background management component.
  30346. *
  30347. * @param {Renderer} renderer - The renderer.
  30348. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  30349. */
  30350. constructor( renderer, nodes ) {
  30351. super();
  30352. /**
  30353. * The renderer.
  30354. *
  30355. * @type {Renderer}
  30356. */
  30357. this.renderer = renderer;
  30358. /**
  30359. * Renderer component for managing nodes related logic.
  30360. *
  30361. * @type {Nodes}
  30362. */
  30363. this.nodes = nodes;
  30364. }
  30365. /**
  30366. * Updates the background for the given scene. Depending on how `Scene.background`
  30367. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  30368. * or add a mesh to the render list for rendering the background as a textured plane
  30369. * or skybox.
  30370. *
  30371. * @param {Scene} scene - The scene.
  30372. * @param {RenderList} renderList - The current render list.
  30373. * @param {RenderContext} renderContext - The current render context.
  30374. */
  30375. update( scene, renderList, renderContext ) {
  30376. const renderer = this.renderer;
  30377. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  30378. let forceClear = false;
  30379. if ( background === null ) {
  30380. // no background settings, use clear color configuration from the renderer
  30381. renderer._clearColor.getRGB( _clearColor );
  30382. _clearColor.a = renderer._clearColor.a;
  30383. } else if ( background.isColor === true ) {
  30384. // background is an opaque color
  30385. background.getRGB( _clearColor );
  30386. _clearColor.a = 1;
  30387. forceClear = true;
  30388. } else if ( background.isNode === true ) {
  30389. const sceneData = this.get( scene );
  30390. const backgroundNode = background;
  30391. _clearColor.copy( renderer._clearColor );
  30392. let backgroundMesh = sceneData.backgroundMesh;
  30393. if ( backgroundMesh === undefined ) {
  30394. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  30395. // @TODO: Add Texture2D support using node context
  30396. getUV: () => backgroundRotation.mul( normalWorld ),
  30397. getTextureLevel: () => backgroundBlurriness
  30398. } );
  30399. let viewProj = modelViewProjection;
  30400. viewProj = viewProj.setZ( viewProj.w );
  30401. const nodeMaterial = new NodeMaterial();
  30402. nodeMaterial.name = 'Background.material';
  30403. nodeMaterial.side = BackSide;
  30404. nodeMaterial.depthTest = false;
  30405. nodeMaterial.depthWrite = false;
  30406. nodeMaterial.allowOverride = false;
  30407. nodeMaterial.fog = false;
  30408. nodeMaterial.lights = false;
  30409. nodeMaterial.vertexNode = viewProj;
  30410. nodeMaterial.colorNode = backgroundMeshNode;
  30411. sceneData.backgroundMeshNode = backgroundMeshNode;
  30412. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  30413. backgroundMesh.frustumCulled = false;
  30414. backgroundMesh.name = 'Background.mesh';
  30415. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  30416. this.matrixWorld.copyPosition( camera.matrixWorld );
  30417. };
  30418. function onBackgroundDispose() {
  30419. background.removeEventListener( 'dispose', onBackgroundDispose );
  30420. backgroundMesh.material.dispose();
  30421. backgroundMesh.geometry.dispose();
  30422. }
  30423. background.addEventListener( 'dispose', onBackgroundDispose );
  30424. }
  30425. const backgroundCacheKey = backgroundNode.getCacheKey();
  30426. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  30427. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  30428. sceneData.backgroundMeshNode.needsUpdate = true;
  30429. backgroundMesh.material.needsUpdate = true;
  30430. sceneData.backgroundCacheKey = backgroundCacheKey;
  30431. }
  30432. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  30433. } else {
  30434. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  30435. }
  30436. //
  30437. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  30438. if ( environmentBlendMode === 'additive' ) {
  30439. _clearColor.set( 0, 0, 0, 1 );
  30440. } else if ( environmentBlendMode === 'alpha-blend' ) {
  30441. _clearColor.set( 0, 0, 0, 0 );
  30442. }
  30443. //
  30444. if ( renderer.autoClear === true || forceClear === true ) {
  30445. const clearColorValue = renderContext.clearColorValue;
  30446. clearColorValue.r = _clearColor.r;
  30447. clearColorValue.g = _clearColor.g;
  30448. clearColorValue.b = _clearColor.b;
  30449. clearColorValue.a = _clearColor.a;
  30450. // premultiply alpha
  30451. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  30452. clearColorValue.r *= clearColorValue.a;
  30453. clearColorValue.g *= clearColorValue.a;
  30454. clearColorValue.b *= clearColorValue.a;
  30455. }
  30456. //
  30457. renderContext.depthClearValue = renderer._clearDepth;
  30458. renderContext.stencilClearValue = renderer._clearStencil;
  30459. renderContext.clearColor = renderer.autoClearColor === true;
  30460. renderContext.clearDepth = renderer.autoClearDepth === true;
  30461. renderContext.clearStencil = renderer.autoClearStencil === true;
  30462. } else {
  30463. renderContext.clearColor = false;
  30464. renderContext.clearDepth = false;
  30465. renderContext.clearStencil = false;
  30466. }
  30467. }
  30468. }
  30469. let _id$6 = 0;
  30470. /**
  30471. * A bind group represents a collection of bindings and thus a collection
  30472. * or resources. Bind groups are assigned to pipelines to provide them
  30473. * with the required resources (like uniform buffers or textures).
  30474. *
  30475. * @private
  30476. */
  30477. class BindGroup {
  30478. /**
  30479. * Constructs a new bind group.
  30480. *
  30481. * @param {string} name - The bind group's name.
  30482. * @param {Array<Binding>} bindings - An array of bindings.
  30483. * @param {number} index - The group index.
  30484. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  30485. */
  30486. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  30487. /**
  30488. * The bind group's name.
  30489. *
  30490. * @type {string}
  30491. */
  30492. this.name = name;
  30493. /**
  30494. * An array of bindings.
  30495. *
  30496. * @type {Array<Binding>}
  30497. */
  30498. this.bindings = bindings;
  30499. /**
  30500. * The group index.
  30501. *
  30502. * @type {number}
  30503. */
  30504. this.index = index;
  30505. /**
  30506. * An array of reference bindings.
  30507. *
  30508. * @type {Array<Binding>}
  30509. */
  30510. this.bindingsReference = bindingsReference;
  30511. /**
  30512. * The group's ID.
  30513. *
  30514. * @type {number}
  30515. */
  30516. this.id = _id$6 ++;
  30517. }
  30518. }
  30519. /**
  30520. * This module represents the state of a node builder after it was
  30521. * used to build the nodes for a render object. The state holds the
  30522. * results of the build for further processing in the renderer.
  30523. *
  30524. * Render objects with identical cache keys share the same node builder state.
  30525. *
  30526. * @private
  30527. */
  30528. class NodeBuilderState {
  30529. /**
  30530. * Constructs a new node builder state.
  30531. *
  30532. * @param {string} vertexShader - The native vertex shader code.
  30533. * @param {string} fragmentShader - The native fragment shader code.
  30534. * @param {string} computeShader - The native compute shader code.
  30535. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  30536. * @param {Array<BindGroup>} bindings - An array of bind groups.
  30537. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  30538. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  30539. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  30540. * @param {NodeMaterialObserver} observer - A node material observer.
  30541. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  30542. */
  30543. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  30544. /**
  30545. * The native vertex shader code.
  30546. *
  30547. * @type {string}
  30548. */
  30549. this.vertexShader = vertexShader;
  30550. /**
  30551. * The native fragment shader code.
  30552. *
  30553. * @type {string}
  30554. */
  30555. this.fragmentShader = fragmentShader;
  30556. /**
  30557. * The native compute shader code.
  30558. *
  30559. * @type {string}
  30560. */
  30561. this.computeShader = computeShader;
  30562. /**
  30563. * An array with transform attribute objects.
  30564. * Only relevant when using compute shaders with WebGL 2.
  30565. *
  30566. * @type {Array<Object>}
  30567. */
  30568. this.transforms = transforms;
  30569. /**
  30570. * An array of node attributes representing
  30571. * the attributes of the shaders.
  30572. *
  30573. * @type {Array<NodeAttribute>}
  30574. */
  30575. this.nodeAttributes = nodeAttributes;
  30576. /**
  30577. * An array of bind groups representing the uniform or storage
  30578. * buffers, texture or samplers of the shader.
  30579. *
  30580. * @type {Array<BindGroup>}
  30581. */
  30582. this.bindings = bindings;
  30583. /**
  30584. * An array of nodes that implement their `update()` method.
  30585. *
  30586. * @type {Array<Node>}
  30587. */
  30588. this.updateNodes = updateNodes;
  30589. /**
  30590. * An array of nodes that implement their `updateBefore()` method.
  30591. *
  30592. * @type {Array<Node>}
  30593. */
  30594. this.updateBeforeNodes = updateBeforeNodes;
  30595. /**
  30596. * An array of nodes that implement their `updateAfter()` method.
  30597. *
  30598. * @type {Array<Node>}
  30599. */
  30600. this.updateAfterNodes = updateAfterNodes;
  30601. /**
  30602. * A node material observer.
  30603. *
  30604. * @type {NodeMaterialObserver}
  30605. */
  30606. this.observer = observer;
  30607. /**
  30608. * How often this state is used by render objects.
  30609. *
  30610. * @type {number}
  30611. */
  30612. this.usedTimes = 0;
  30613. }
  30614. /**
  30615. * This method is used to create a array of bind groups based
  30616. * on the existing bind groups of this state. Shared groups are
  30617. * not cloned.
  30618. *
  30619. * @return {Array<BindGroup>} A array of bind groups.
  30620. */
  30621. createBindings() {
  30622. const bindings = [];
  30623. for ( const instanceGroup of this.bindings ) {
  30624. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  30625. if ( shared !== true ) {
  30626. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  30627. bindings.push( bindingsGroup );
  30628. for ( const instanceBinding of instanceGroup.bindings ) {
  30629. bindingsGroup.bindings.push( instanceBinding.clone() );
  30630. }
  30631. } else {
  30632. bindings.push( instanceGroup );
  30633. }
  30634. }
  30635. return bindings;
  30636. }
  30637. }
  30638. /**
  30639. * {@link NodeBuilder} is going to create instances of this class during the build process
  30640. * of nodes. They represent the final shader attributes that are going to be generated
  30641. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  30642. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  30643. */
  30644. class NodeAttribute {
  30645. /**
  30646. * Constructs a new node attribute.
  30647. *
  30648. * @param {string} name - The name of the attribute.
  30649. * @param {string} type - The type of the attribute.
  30650. * @param {?Node} node - An optional reference to the node.
  30651. */
  30652. constructor( name, type, node = null ) {
  30653. /**
  30654. * This flag can be used for type testing.
  30655. *
  30656. * @type {boolean}
  30657. * @readonly
  30658. * @default true
  30659. */
  30660. this.isNodeAttribute = true;
  30661. /**
  30662. * The name of the attribute.
  30663. *
  30664. * @type {string}
  30665. */
  30666. this.name = name;
  30667. /**
  30668. * The type of the attribute.
  30669. *
  30670. * @type {string}
  30671. */
  30672. this.type = type;
  30673. /**
  30674. * An optional reference to the node.
  30675. *
  30676. * @type {?Node}
  30677. * @default null
  30678. */
  30679. this.node = node;
  30680. }
  30681. }
  30682. /**
  30683. * {@link NodeBuilder} is going to create instances of this class during the build process
  30684. * of nodes. They represent the final shader uniforms that are going to be generated
  30685. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  30686. * for this purpose.
  30687. */
  30688. class NodeUniform {
  30689. /**
  30690. * Constructs a new node uniform.
  30691. *
  30692. * @param {string} name - The name of the uniform.
  30693. * @param {string} type - The type of the uniform.
  30694. * @param {UniformNode} node - An reference to the node.
  30695. */
  30696. constructor( name, type, node ) {
  30697. /**
  30698. * This flag can be used for type testing.
  30699. *
  30700. * @type {boolean}
  30701. * @readonly
  30702. * @default true
  30703. */
  30704. this.isNodeUniform = true;
  30705. /**
  30706. * The name of the uniform.
  30707. *
  30708. * @type {string}
  30709. */
  30710. this.name = name;
  30711. /**
  30712. * The type of the uniform.
  30713. *
  30714. * @type {string}
  30715. */
  30716. this.type = type;
  30717. /**
  30718. * An reference to the node.
  30719. *
  30720. * @type {UniformNode}
  30721. */
  30722. this.node = node.getSelf();
  30723. }
  30724. /**
  30725. * The value of the uniform node.
  30726. *
  30727. * @type {any}
  30728. */
  30729. get value() {
  30730. return this.node.value;
  30731. }
  30732. set value( val ) {
  30733. this.node.value = val;
  30734. }
  30735. /**
  30736. * The id of the uniform node.
  30737. *
  30738. * @type {number}
  30739. */
  30740. get id() {
  30741. return this.node.id;
  30742. }
  30743. /**
  30744. * The uniform node's group.
  30745. *
  30746. * @type {UniformGroupNode}
  30747. */
  30748. get groupNode() {
  30749. return this.node.groupNode;
  30750. }
  30751. }
  30752. /**
  30753. * {@link NodeBuilder} is going to create instances of this class during the build process
  30754. * of nodes. They represent the final shader variables that are going to be generated
  30755. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  30756. * this purpose.
  30757. */
  30758. class NodeVar {
  30759. /**
  30760. * Constructs a new node variable.
  30761. *
  30762. * @param {string} name - The name of the variable.
  30763. * @param {string} type - The type of the variable.
  30764. * @param {boolean} [readOnly=false] - The read-only flag.
  30765. * @param {?number} [count=null] - The size.
  30766. */
  30767. constructor( name, type, readOnly = false, count = null ) {
  30768. /**
  30769. * This flag can be used for type testing.
  30770. *
  30771. * @type {boolean}
  30772. * @readonly
  30773. * @default true
  30774. */
  30775. this.isNodeVar = true;
  30776. /**
  30777. * The name of the variable.
  30778. *
  30779. * @type {string}
  30780. */
  30781. this.name = name;
  30782. /**
  30783. * The type of the variable.
  30784. *
  30785. * @type {string}
  30786. */
  30787. this.type = type;
  30788. /**
  30789. * The read-only flag.
  30790. *
  30791. * @type {boolean}
  30792. */
  30793. this.readOnly = readOnly;
  30794. /**
  30795. * The size.
  30796. *
  30797. * @type {?number}
  30798. */
  30799. this.count = count;
  30800. }
  30801. }
  30802. /**
  30803. * {@link NodeBuilder} is going to create instances of this class during the build process
  30804. * of nodes. They represent the final shader varyings that are going to be generated
  30805. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  30806. * this purpose.
  30807. *
  30808. * @augments NodeVar
  30809. */
  30810. class NodeVarying extends NodeVar {
  30811. /**
  30812. * Constructs a new node varying.
  30813. *
  30814. * @param {string} name - The name of the varying.
  30815. * @param {string} type - The type of the varying.
  30816. * @param {?string} interpolationType - The interpolation type of the varying.
  30817. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  30818. */
  30819. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  30820. super( name, type );
  30821. /**
  30822. * Whether this varying requires interpolation or not. This property can be used
  30823. * to check if the varying can be optimized for a variable.
  30824. *
  30825. * @type {boolean}
  30826. * @default false
  30827. */
  30828. this.needsInterpolation = false;
  30829. /**
  30830. * This flag can be used for type testing.
  30831. *
  30832. * @type {boolean}
  30833. * @readonly
  30834. * @default true
  30835. */
  30836. this.isNodeVarying = true;
  30837. /**
  30838. * The interpolation type of the varying data.
  30839. *
  30840. * @type {?string}
  30841. * @default null
  30842. */
  30843. this.interpolationType = interpolationType;
  30844. /**
  30845. * The interpolation sampling type of varying data.
  30846. *
  30847. * @type {?string}
  30848. * @default null
  30849. */
  30850. this.interpolationSampling = interpolationSampling;
  30851. }
  30852. }
  30853. /**
  30854. * {@link NodeBuilder} is going to create instances of this class during the build process
  30855. * of nodes. They represent user-defined, native shader code portions that are going to be
  30856. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  30857. * for this purpose.
  30858. */
  30859. class NodeCode {
  30860. /**
  30861. * Constructs a new code node.
  30862. *
  30863. * @param {string} name - The name of the code.
  30864. * @param {string} type - The node type.
  30865. * @param {string} [code=''] - The native shader code.
  30866. */
  30867. constructor( name, type, code = '' ) {
  30868. /**
  30869. * The name of the code.
  30870. *
  30871. * @type {string}
  30872. */
  30873. this.name = name;
  30874. /**
  30875. * The node type.
  30876. *
  30877. * @type {string}
  30878. */
  30879. this.type = type;
  30880. /**
  30881. * The native shader code.
  30882. *
  30883. * @type {string}
  30884. * @default ''
  30885. */
  30886. this.code = code;
  30887. Object.defineProperty( this, 'isNodeCode', { value: true } );
  30888. }
  30889. }
  30890. let _id$5 = 0;
  30891. /**
  30892. * This utility class is used in {@link NodeBuilder} as an internal
  30893. * cache data structure for node data.
  30894. */
  30895. class NodeCache {
  30896. /**
  30897. * Constructs a new node cache.
  30898. *
  30899. * @param {?NodeCache} parent - A reference to a parent cache.
  30900. */
  30901. constructor( parent = null ) {
  30902. /**
  30903. * The id of the cache.
  30904. *
  30905. * @type {number}
  30906. * @readonly
  30907. */
  30908. this.id = _id$5 ++;
  30909. /**
  30910. * A weak map for managing node data.
  30911. *
  30912. * @type {WeakMap<Node, Object>}
  30913. */
  30914. this.nodesData = new WeakMap();
  30915. /**
  30916. * Reference to a parent node cache.
  30917. *
  30918. * @type {?NodeCache}
  30919. * @default null
  30920. */
  30921. this.parent = parent;
  30922. }
  30923. /**
  30924. * Returns the data for the given node.
  30925. *
  30926. * @param {Node} node - The node.
  30927. * @return {?Object} The data for the node.
  30928. */
  30929. getData( node ) {
  30930. let data = this.nodesData.get( node );
  30931. if ( data === undefined && this.parent !== null ) {
  30932. data = this.parent.getData( node );
  30933. }
  30934. return data;
  30935. }
  30936. /**
  30937. * Sets the data for a given node.
  30938. *
  30939. * @param {Node} node - The node.
  30940. * @param {Object} data - The data that should be cached.
  30941. */
  30942. setData( node, data ) {
  30943. this.nodesData.set( node, data );
  30944. }
  30945. }
  30946. class StructType {
  30947. constructor( name, members ) {
  30948. this.name = name;
  30949. this.members = members;
  30950. this.output = false;
  30951. }
  30952. }
  30953. /**
  30954. * Abstract base class for uniforms.
  30955. *
  30956. * @abstract
  30957. * @private
  30958. */
  30959. class Uniform {
  30960. /**
  30961. * Constructs a new uniform.
  30962. *
  30963. * @param {string} name - The uniform's name.
  30964. * @param {any} value - The uniform's value.
  30965. */
  30966. constructor( name, value ) {
  30967. /**
  30968. * The uniform's name.
  30969. *
  30970. * @type {string}
  30971. */
  30972. this.name = name;
  30973. /**
  30974. * The uniform's value.
  30975. *
  30976. * @type {any}
  30977. */
  30978. this.value = value;
  30979. /**
  30980. * Used to build the uniform buffer according to the STD140 layout.
  30981. * Derived uniforms will set this property to a data type specific
  30982. * value.
  30983. *
  30984. * @type {number}
  30985. */
  30986. this.boundary = 0;
  30987. /**
  30988. * The item size. Derived uniforms will set this property to a data
  30989. * type specific value.
  30990. *
  30991. * @type {number}
  30992. */
  30993. this.itemSize = 0;
  30994. /**
  30995. * This property is set by {@link UniformsGroup} and marks
  30996. * the start position in the uniform buffer.
  30997. *
  30998. * @type {number}
  30999. */
  31000. this.offset = 0;
  31001. }
  31002. /**
  31003. * Sets the uniform's value.
  31004. *
  31005. * @param {any} value - The value to set.
  31006. */
  31007. setValue( value ) {
  31008. this.value = value;
  31009. }
  31010. /**
  31011. * Returns the uniform's value.
  31012. *
  31013. * @return {any} The value.
  31014. */
  31015. getValue() {
  31016. return this.value;
  31017. }
  31018. }
  31019. /**
  31020. * Represents a Number uniform.
  31021. *
  31022. * @private
  31023. * @augments Uniform
  31024. */
  31025. class NumberUniform extends Uniform {
  31026. /**
  31027. * Constructs a new Number uniform.
  31028. *
  31029. * @param {string} name - The uniform's name.
  31030. * @param {number} value - The uniform's value.
  31031. */
  31032. constructor( name, value = 0 ) {
  31033. super( name, value );
  31034. /**
  31035. * This flag can be used for type testing.
  31036. *
  31037. * @type {boolean}
  31038. * @readonly
  31039. * @default true
  31040. */
  31041. this.isNumberUniform = true;
  31042. this.boundary = 4;
  31043. this.itemSize = 1;
  31044. }
  31045. }
  31046. /**
  31047. * Represents a Vector2 uniform.
  31048. *
  31049. * @private
  31050. * @augments Uniform
  31051. */
  31052. class Vector2Uniform extends Uniform {
  31053. /**
  31054. * Constructs a new Number uniform.
  31055. *
  31056. * @param {string} name - The uniform's name.
  31057. * @param {Vector2} value - The uniform's value.
  31058. */
  31059. constructor( name, value = new Vector2() ) {
  31060. super( name, value );
  31061. /**
  31062. * This flag can be used for type testing.
  31063. *
  31064. * @type {boolean}
  31065. * @readonly
  31066. * @default true
  31067. */
  31068. this.isVector2Uniform = true;
  31069. this.boundary = 8;
  31070. this.itemSize = 2;
  31071. }
  31072. }
  31073. /**
  31074. * Represents a Vector3 uniform.
  31075. *
  31076. * @private
  31077. * @augments Uniform
  31078. */
  31079. class Vector3Uniform extends Uniform {
  31080. /**
  31081. * Constructs a new Number uniform.
  31082. *
  31083. * @param {string} name - The uniform's name.
  31084. * @param {Vector3} value - The uniform's value.
  31085. */
  31086. constructor( name, value = new Vector3() ) {
  31087. super( name, value );
  31088. /**
  31089. * This flag can be used for type testing.
  31090. *
  31091. * @type {boolean}
  31092. * @readonly
  31093. * @default true
  31094. */
  31095. this.isVector3Uniform = true;
  31096. this.boundary = 16;
  31097. this.itemSize = 3;
  31098. }
  31099. }
  31100. /**
  31101. * Represents a Vector4 uniform.
  31102. *
  31103. * @private
  31104. * @augments Uniform
  31105. */
  31106. class Vector4Uniform extends Uniform {
  31107. /**
  31108. * Constructs a new Number uniform.
  31109. *
  31110. * @param {string} name - The uniform's name.
  31111. * @param {Vector4} value - The uniform's value.
  31112. */
  31113. constructor( name, value = new Vector4() ) {
  31114. super( name, value );
  31115. /**
  31116. * This flag can be used for type testing.
  31117. *
  31118. * @type {boolean}
  31119. * @readonly
  31120. * @default true
  31121. */
  31122. this.isVector4Uniform = true;
  31123. this.boundary = 16;
  31124. this.itemSize = 4;
  31125. }
  31126. }
  31127. /**
  31128. * Represents a Color uniform.
  31129. *
  31130. * @private
  31131. * @augments Uniform
  31132. */
  31133. class ColorUniform extends Uniform {
  31134. /**
  31135. * Constructs a new Number uniform.
  31136. *
  31137. * @param {string} name - The uniform's name.
  31138. * @param {Color} value - The uniform's value.
  31139. */
  31140. constructor( name, value = new Color() ) {
  31141. super( name, value );
  31142. /**
  31143. * This flag can be used for type testing.
  31144. *
  31145. * @type {boolean}
  31146. * @readonly
  31147. * @default true
  31148. */
  31149. this.isColorUniform = true;
  31150. this.boundary = 16;
  31151. this.itemSize = 3;
  31152. }
  31153. }
  31154. /**
  31155. * Represents a Matrix2 uniform.
  31156. *
  31157. * @private
  31158. * @augments Uniform
  31159. */
  31160. class Matrix2Uniform extends Uniform {
  31161. /**
  31162. * Constructs a new Number uniform.
  31163. *
  31164. * @param {string} name - The uniform's name.
  31165. * @param {Matrix2} value - The uniform's value.
  31166. */
  31167. constructor( name, value = new Matrix2() ) {
  31168. super( name, value );
  31169. /**
  31170. * This flag can be used for type testing.
  31171. *
  31172. * @type {boolean}
  31173. * @readonly
  31174. * @default true
  31175. */
  31176. this.isMatrix2Uniform = true;
  31177. this.boundary = 8;
  31178. this.itemSize = 4;
  31179. }
  31180. }
  31181. /**
  31182. * Represents a Matrix3 uniform.
  31183. *
  31184. * @private
  31185. * @augments Uniform
  31186. */
  31187. class Matrix3Uniform extends Uniform {
  31188. /**
  31189. * Constructs a new Number uniform.
  31190. *
  31191. * @param {string} name - The uniform's name.
  31192. * @param {Matrix3} value - The uniform's value.
  31193. */
  31194. constructor( name, value = new Matrix3() ) {
  31195. super( name, value );
  31196. /**
  31197. * This flag can be used for type testing.
  31198. *
  31199. * @type {boolean}
  31200. * @readonly
  31201. * @default true
  31202. */
  31203. this.isMatrix3Uniform = true;
  31204. this.boundary = 48;
  31205. this.itemSize = 12;
  31206. }
  31207. }
  31208. /**
  31209. * Represents a Matrix4 uniform.
  31210. *
  31211. * @private
  31212. * @augments Uniform
  31213. */
  31214. class Matrix4Uniform extends Uniform {
  31215. /**
  31216. * Constructs a new Number uniform.
  31217. *
  31218. * @param {string} name - The uniform's name.
  31219. * @param {Matrix4} value - The uniform's value.
  31220. */
  31221. constructor( name, value = new Matrix4() ) {
  31222. super( name, value );
  31223. /**
  31224. * This flag can be used for type testing.
  31225. *
  31226. * @type {boolean}
  31227. * @readonly
  31228. * @default true
  31229. */
  31230. this.isMatrix4Uniform = true;
  31231. this.boundary = 64;
  31232. this.itemSize = 16;
  31233. }
  31234. }
  31235. /**
  31236. * A special form of Number uniform binding type.
  31237. * It's value is managed by a node object.
  31238. *
  31239. * @private
  31240. * @augments NumberUniform
  31241. */
  31242. class NumberNodeUniform extends NumberUniform {
  31243. /**
  31244. * Constructs a new node-based Number uniform.
  31245. *
  31246. * @param {NodeUniform} nodeUniform - The node uniform.
  31247. */
  31248. constructor( nodeUniform ) {
  31249. super( nodeUniform.name, nodeUniform.value );
  31250. /**
  31251. * The node uniform.
  31252. *
  31253. * @type {NodeUniform}
  31254. */
  31255. this.nodeUniform = nodeUniform;
  31256. }
  31257. /**
  31258. * Overwritten to return the value of the node uniform.
  31259. *
  31260. * @return {number} The value.
  31261. */
  31262. getValue() {
  31263. return this.nodeUniform.value;
  31264. }
  31265. /**
  31266. * Returns the node uniform data type.
  31267. *
  31268. * @return {string} The data type.
  31269. */
  31270. getType() {
  31271. return this.nodeUniform.type;
  31272. }
  31273. }
  31274. /**
  31275. * A special form of Vector2 uniform binding type.
  31276. * It's value is managed by a node object.
  31277. *
  31278. * @private
  31279. * @augments Vector2Uniform
  31280. */
  31281. class Vector2NodeUniform extends Vector2Uniform {
  31282. /**
  31283. * Constructs a new node-based Vector2 uniform.
  31284. *
  31285. * @param {NodeUniform} nodeUniform - The node uniform.
  31286. */
  31287. constructor( nodeUniform ) {
  31288. super( nodeUniform.name, nodeUniform.value );
  31289. /**
  31290. * The node uniform.
  31291. *
  31292. * @type {NodeUniform}
  31293. */
  31294. this.nodeUniform = nodeUniform;
  31295. }
  31296. /**
  31297. * Overwritten to return the value of the node uniform.
  31298. *
  31299. * @return {Vector2} The value.
  31300. */
  31301. getValue() {
  31302. return this.nodeUniform.value;
  31303. }
  31304. /**
  31305. * Returns the node uniform data type.
  31306. *
  31307. * @return {string} The data type.
  31308. */
  31309. getType() {
  31310. return this.nodeUniform.type;
  31311. }
  31312. }
  31313. /**
  31314. * A special form of Vector3 uniform binding type.
  31315. * It's value is managed by a node object.
  31316. *
  31317. * @private
  31318. * @augments Vector3Uniform
  31319. */
  31320. class Vector3NodeUniform extends Vector3Uniform {
  31321. /**
  31322. * Constructs a new node-based Vector3 uniform.
  31323. *
  31324. * @param {NodeUniform} nodeUniform - The node uniform.
  31325. */
  31326. constructor( nodeUniform ) {
  31327. super( nodeUniform.name, nodeUniform.value );
  31328. /**
  31329. * The node uniform.
  31330. *
  31331. * @type {NodeUniform}
  31332. */
  31333. this.nodeUniform = nodeUniform;
  31334. }
  31335. /**
  31336. * Overwritten to return the value of the node uniform.
  31337. *
  31338. * @return {Vector3} The value.
  31339. */
  31340. getValue() {
  31341. return this.nodeUniform.value;
  31342. }
  31343. /**
  31344. * Returns the node uniform data type.
  31345. *
  31346. * @return {string} The data type.
  31347. */
  31348. getType() {
  31349. return this.nodeUniform.type;
  31350. }
  31351. }
  31352. /**
  31353. * A special form of Vector4 uniform binding type.
  31354. * It's value is managed by a node object.
  31355. *
  31356. * @private
  31357. * @augments Vector4Uniform
  31358. */
  31359. class Vector4NodeUniform extends Vector4Uniform {
  31360. /**
  31361. * Constructs a new node-based Vector4 uniform.
  31362. *
  31363. * @param {NodeUniform} nodeUniform - The node uniform.
  31364. */
  31365. constructor( nodeUniform ) {
  31366. super( nodeUniform.name, nodeUniform.value );
  31367. /**
  31368. * The node uniform.
  31369. *
  31370. * @type {NodeUniform}
  31371. */
  31372. this.nodeUniform = nodeUniform;
  31373. }
  31374. /**
  31375. * Overwritten to return the value of the node uniform.
  31376. *
  31377. * @return {Vector4} The value.
  31378. */
  31379. getValue() {
  31380. return this.nodeUniform.value;
  31381. }
  31382. /**
  31383. * Returns the node uniform data type.
  31384. *
  31385. * @return {string} The data type.
  31386. */
  31387. getType() {
  31388. return this.nodeUniform.type;
  31389. }
  31390. }
  31391. /**
  31392. * A special form of Color uniform binding type.
  31393. * It's value is managed by a node object.
  31394. *
  31395. * @private
  31396. * @augments ColorUniform
  31397. */
  31398. class ColorNodeUniform extends ColorUniform {
  31399. /**
  31400. * Constructs a new node-based Color uniform.
  31401. *
  31402. * @param {NodeUniform} nodeUniform - The node uniform.
  31403. */
  31404. constructor( nodeUniform ) {
  31405. super( nodeUniform.name, nodeUniform.value );
  31406. /**
  31407. * The node uniform.
  31408. *
  31409. * @type {NodeUniform}
  31410. */
  31411. this.nodeUniform = nodeUniform;
  31412. }
  31413. /**
  31414. * Overwritten to return the value of the node uniform.
  31415. *
  31416. * @return {Color} The value.
  31417. */
  31418. getValue() {
  31419. return this.nodeUniform.value;
  31420. }
  31421. /**
  31422. * Returns the node uniform data type.
  31423. *
  31424. * @return {string} The data type.
  31425. */
  31426. getType() {
  31427. return this.nodeUniform.type;
  31428. }
  31429. }
  31430. /**
  31431. * A special form of Matrix2 uniform binding type.
  31432. * It's value is managed by a node object.
  31433. *
  31434. * @private
  31435. * @augments Matrix2Uniform
  31436. */
  31437. class Matrix2NodeUniform extends Matrix2Uniform {
  31438. /**
  31439. * Constructs a new node-based Matrix2 uniform.
  31440. *
  31441. * @param {NodeUniform} nodeUniform - The node uniform.
  31442. */
  31443. constructor( nodeUniform ) {
  31444. super( nodeUniform.name, nodeUniform.value );
  31445. /**
  31446. * The node uniform.
  31447. *
  31448. * @type {NodeUniform}
  31449. */
  31450. this.nodeUniform = nodeUniform;
  31451. }
  31452. /**
  31453. * Overwritten to return the value of the node uniform.
  31454. *
  31455. * @return {Matrix2} The value.
  31456. */
  31457. getValue() {
  31458. return this.nodeUniform.value;
  31459. }
  31460. /**
  31461. * Returns the node uniform data type.
  31462. *
  31463. * @return {string} The data type.
  31464. */
  31465. getType() {
  31466. return this.nodeUniform.type;
  31467. }
  31468. }
  31469. /**
  31470. * A special form of Matrix3 uniform binding type.
  31471. * It's value is managed by a node object.
  31472. *
  31473. * @private
  31474. * @augments Matrix3Uniform
  31475. */
  31476. class Matrix3NodeUniform extends Matrix3Uniform {
  31477. /**
  31478. * Constructs a new node-based Matrix3 uniform.
  31479. *
  31480. * @param {NodeUniform} nodeUniform - The node uniform.
  31481. */
  31482. constructor( nodeUniform ) {
  31483. super( nodeUniform.name, nodeUniform.value );
  31484. /**
  31485. * The node uniform.
  31486. *
  31487. * @type {NodeUniform}
  31488. */
  31489. this.nodeUniform = nodeUniform;
  31490. }
  31491. /**
  31492. * Overwritten to return the value of the node uniform.
  31493. *
  31494. * @return {Matrix3} The value.
  31495. */
  31496. getValue() {
  31497. return this.nodeUniform.value;
  31498. }
  31499. /**
  31500. * Returns the node uniform data type.
  31501. *
  31502. * @return {string} The data type.
  31503. */
  31504. getType() {
  31505. return this.nodeUniform.type;
  31506. }
  31507. }
  31508. /**
  31509. * A special form of Matrix4 uniform binding type.
  31510. * It's value is managed by a node object.
  31511. *
  31512. * @private
  31513. * @augments Matrix4Uniform
  31514. */
  31515. class Matrix4NodeUniform extends Matrix4Uniform {
  31516. /**
  31517. * Constructs a new node-based Matrix4 uniform.
  31518. *
  31519. * @param {NodeUniform} nodeUniform - The node uniform.
  31520. */
  31521. constructor( nodeUniform ) {
  31522. super( nodeUniform.name, nodeUniform.value );
  31523. /**
  31524. * The node uniform.
  31525. *
  31526. * @type {NodeUniform}
  31527. */
  31528. this.nodeUniform = nodeUniform;
  31529. }
  31530. /**
  31531. * Overwritten to return the value of the node uniform.
  31532. *
  31533. * @return {Matrix4} The value.
  31534. */
  31535. getValue() {
  31536. return this.nodeUniform.value;
  31537. }
  31538. /**
  31539. * Returns the node uniform data type.
  31540. *
  31541. * @return {string} The data type.
  31542. */
  31543. getType() {
  31544. return this.nodeUniform.type;
  31545. }
  31546. }
  31547. const rendererCache = new WeakMap();
  31548. const typeFromArray = new Map( [
  31549. [ Int8Array, 'int' ],
  31550. [ Int16Array, 'int' ],
  31551. [ Int32Array, 'int' ],
  31552. [ Uint8Array, 'uint' ],
  31553. [ Uint16Array, 'uint' ],
  31554. [ Uint32Array, 'uint' ],
  31555. [ Float32Array, 'float' ]
  31556. ] );
  31557. const toFloat = ( value ) => {
  31558. if ( /e/g.test( value ) ) {
  31559. return String( value ).replace( /\+/g, '' );
  31560. } else {
  31561. value = Number( value );
  31562. return value + ( value % 1 ? '' : '.0' );
  31563. }
  31564. };
  31565. /**
  31566. * Base class for builders which generate a shader program based
  31567. * on a 3D object and its node material definition.
  31568. */
  31569. class NodeBuilder {
  31570. /**
  31571. * Constructs a new node builder.
  31572. *
  31573. * @param {Object3D} object - The 3D object.
  31574. * @param {Renderer} renderer - The current renderer.
  31575. * @param {NodeParser} parser - A reference to a node parser.
  31576. */
  31577. constructor( object, renderer, parser ) {
  31578. /**
  31579. * The 3D object.
  31580. *
  31581. * @type {Object3D}
  31582. */
  31583. this.object = object;
  31584. /**
  31585. * The material of the 3D object.
  31586. *
  31587. * @type {?Material}
  31588. */
  31589. this.material = ( object && object.material ) || null;
  31590. /**
  31591. * The geometry of the 3D object.
  31592. *
  31593. * @type {?BufferGeometry}
  31594. */
  31595. this.geometry = ( object && object.geometry ) || null;
  31596. /**
  31597. * The current renderer.
  31598. *
  31599. * @type {Renderer}
  31600. */
  31601. this.renderer = renderer;
  31602. /**
  31603. * A reference to a node parser.
  31604. *
  31605. * @type {NodeParser}
  31606. */
  31607. this.parser = parser;
  31608. /**
  31609. * The scene the 3D object belongs to.
  31610. *
  31611. * @type {?Scene}
  31612. * @default null
  31613. */
  31614. this.scene = null;
  31615. /**
  31616. * The camera the 3D object is rendered with.
  31617. *
  31618. * @type {?Camera}
  31619. * @default null
  31620. */
  31621. this.camera = null;
  31622. /**
  31623. * A list of all nodes the builder is processing
  31624. * for this 3D object.
  31625. *
  31626. * @type {Array<Node>}
  31627. */
  31628. this.nodes = [];
  31629. /**
  31630. * A list of all sequential nodes.
  31631. *
  31632. * @type {Array<Node>}
  31633. */
  31634. this.sequentialNodes = [];
  31635. /**
  31636. * A list of all nodes which {@link Node#update} method should be executed.
  31637. *
  31638. * @type {Array<Node>}
  31639. */
  31640. this.updateNodes = [];
  31641. /**
  31642. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  31643. *
  31644. * @type {Array<Node>}
  31645. */
  31646. this.updateBeforeNodes = [];
  31647. /**
  31648. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  31649. *
  31650. * @type {Array<Node>}
  31651. */
  31652. this.updateAfterNodes = [];
  31653. /**
  31654. * A dictionary that assigns each node to a unique hash.
  31655. *
  31656. * @type {Object<number,Node>}
  31657. */
  31658. this.hashNodes = {};
  31659. /**
  31660. * A reference to a node material observer.
  31661. *
  31662. * @type {?NodeMaterialObserver}
  31663. * @default null
  31664. */
  31665. this.observer = null;
  31666. /**
  31667. * A reference to the current lights node.
  31668. *
  31669. * @type {?LightsNode}
  31670. * @default null
  31671. */
  31672. this.lightsNode = null;
  31673. /**
  31674. * A reference to the current environment node.
  31675. *
  31676. * @type {?Node}
  31677. * @default null
  31678. */
  31679. this.environmentNode = null;
  31680. /**
  31681. * A reference to the current fog node.
  31682. *
  31683. * @type {?FogNode}
  31684. * @default null
  31685. */
  31686. this.fogNode = null;
  31687. /**
  31688. * The current clipping context.
  31689. *
  31690. * @type {?ClippingContext}
  31691. */
  31692. this.clippingContext = null;
  31693. /**
  31694. * The generated vertex shader.
  31695. *
  31696. * @type {?string}
  31697. */
  31698. this.vertexShader = null;
  31699. /**
  31700. * The generated fragment shader.
  31701. *
  31702. * @type {?string}
  31703. */
  31704. this.fragmentShader = null;
  31705. /**
  31706. * The generated compute shader.
  31707. *
  31708. * @type {?string}
  31709. */
  31710. this.computeShader = null;
  31711. /**
  31712. * Nodes used in the primary flow of code generation.
  31713. *
  31714. * @type {Object<string,Array<Node>>}
  31715. */
  31716. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  31717. /**
  31718. * Nodes code from `.flowNodes`.
  31719. *
  31720. * @type {Object<string,string>}
  31721. */
  31722. this.flowCode = { vertex: '', fragment: '', compute: '' };
  31723. /**
  31724. * This dictionary holds the node uniforms of the builder.
  31725. * The uniforms are maintained in an array for each shader stage.
  31726. *
  31727. * @type {Object}
  31728. */
  31729. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  31730. /**
  31731. * This dictionary holds the output structs of the builder.
  31732. * The structs are maintained in an array for each shader stage.
  31733. *
  31734. * @type {Object}
  31735. */
  31736. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  31737. /**
  31738. * This dictionary holds the bindings for each shader stage.
  31739. *
  31740. * @type {Object}
  31741. */
  31742. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  31743. /**
  31744. * This dictionary maintains the binding indices per bind group.
  31745. *
  31746. * @type {Object}
  31747. */
  31748. this.bindingsIndexes = {};
  31749. /**
  31750. * Reference to the array of bind groups.
  31751. *
  31752. * @type {?Array<BindGroup>}
  31753. */
  31754. this.bindGroups = null;
  31755. /**
  31756. * This array holds the node attributes of this builder
  31757. * created via {@link AttributeNode}.
  31758. *
  31759. * @type {Array<NodeAttribute>}
  31760. */
  31761. this.attributes = [];
  31762. /**
  31763. * This array holds the node attributes of this builder
  31764. * created via {@link BufferAttributeNode}.
  31765. *
  31766. * @type {Array<NodeAttribute>}
  31767. */
  31768. this.bufferAttributes = [];
  31769. /**
  31770. * This array holds the node varyings of this builder.
  31771. *
  31772. * @type {Array<NodeVarying>}
  31773. */
  31774. this.varyings = [];
  31775. /**
  31776. * This dictionary holds the (native) node codes of this builder.
  31777. * The codes are maintained in an array for each shader stage.
  31778. *
  31779. * @type {Object<string,Array<NodeCode>>}
  31780. */
  31781. this.codes = {};
  31782. /**
  31783. * This dictionary holds the node variables of this builder.
  31784. * The variables are maintained in an array for each shader stage.
  31785. * This dictionary is also used to count the number of variables
  31786. * according to their type (const, vars).
  31787. *
  31788. * @type {Object<string,Array<NodeVar>|number>}
  31789. */
  31790. this.vars = {};
  31791. /**
  31792. * This dictionary holds the declarations for each shader stage.
  31793. *
  31794. * @type {Object}
  31795. */
  31796. this.declarations = {};
  31797. /**
  31798. * Current code flow.
  31799. * All code generated in this stack will be stored in `.flow`.
  31800. *
  31801. * @type {{code: string}}
  31802. */
  31803. this.flow = { code: '' };
  31804. /**
  31805. * A chain of nodes.
  31806. * Used to check recursive calls in node-graph.
  31807. *
  31808. * @type {Array<Node>}
  31809. */
  31810. this.chaining = [];
  31811. /**
  31812. * The current stack.
  31813. * This reflects the current process in the code block hierarchy,
  31814. * it is useful to know if the current process is inside a conditional for example.
  31815. *
  31816. * @type {StackNode}
  31817. */
  31818. this.stack = stack();
  31819. /**
  31820. * List of stack nodes.
  31821. * The current stack hierarchy is stored in an array.
  31822. *
  31823. * @type {Array<StackNode>}
  31824. */
  31825. this.stacks = [];
  31826. /**
  31827. * A tab value. Used for shader string generation.
  31828. *
  31829. * @type {string}
  31830. * @default '\t'
  31831. */
  31832. this.tab = '\t';
  31833. /**
  31834. * Reference to the current function node.
  31835. *
  31836. * @type {?FunctionNode}
  31837. * @default null
  31838. */
  31839. this.currentFunctionNode = null;
  31840. /**
  31841. * The builder's context.
  31842. *
  31843. * @type {Object}
  31844. */
  31845. this.context = {
  31846. material: this.material
  31847. };
  31848. /**
  31849. * The builder's cache.
  31850. *
  31851. * @type {NodeCache}
  31852. */
  31853. this.cache = new NodeCache();
  31854. /**
  31855. * Since the {@link NodeBuilder#cache} might be temporarily
  31856. * overwritten by other caches, this member retains the reference
  31857. * to the builder's own cache.
  31858. *
  31859. * @type {NodeCache}
  31860. * @default this.cache
  31861. */
  31862. this.globalCache = this.cache;
  31863. this.flowsData = new WeakMap();
  31864. /**
  31865. * The current shader stage.
  31866. *
  31867. * @type {?('vertex'|'fragment'|'compute'|'any')}
  31868. */
  31869. this.shaderStage = null;
  31870. /**
  31871. * The current build stage.
  31872. *
  31873. * @type {?('setup'|'analyze'|'generate')}
  31874. */
  31875. this.buildStage = null;
  31876. }
  31877. /**
  31878. * Returns the bind groups of the current renderer.
  31879. *
  31880. * @return {ChainMap} The cache.
  31881. */
  31882. getBindGroupsCache() {
  31883. let bindGroupsCache = rendererCache.get( this.renderer );
  31884. if ( bindGroupsCache === undefined ) {
  31885. bindGroupsCache = new ChainMap();
  31886. rendererCache.set( this.renderer, bindGroupsCache );
  31887. }
  31888. return bindGroupsCache;
  31889. }
  31890. /**
  31891. * Factory method for creating an instance of {@link RenderTarget} with the given
  31892. * dimensions and options.
  31893. *
  31894. * @param {number} width - The width of the render target.
  31895. * @param {number} height - The height of the render target.
  31896. * @param {Object} options - The options of the render target.
  31897. * @return {RenderTarget} The render target.
  31898. */
  31899. createRenderTarget( width, height, options ) {
  31900. return new RenderTarget( width, height, options );
  31901. }
  31902. /**
  31903. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  31904. * dimensions and options.
  31905. *
  31906. * @param {number} size - The size of the cube render target.
  31907. * @param {Object} options - The options of the cube render target.
  31908. * @return {CubeRenderTarget} The cube render target.
  31909. */
  31910. createCubeRenderTarget( size, options ) {
  31911. return new CubeRenderTarget( size, options );
  31912. }
  31913. /**
  31914. * Whether the given node is included in the internal array of nodes or not.
  31915. *
  31916. * @param {Node} node - The node to test.
  31917. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  31918. */
  31919. includes( node ) {
  31920. return this.nodes.includes( node );
  31921. }
  31922. /**
  31923. * Returns the output struct name which is required by
  31924. * {@link OutputStructNode}.
  31925. *
  31926. * @abstract
  31927. * @return {string} The name of the output struct.
  31928. */
  31929. getOutputStructName() {}
  31930. /**
  31931. * Returns a bind group for the given group name and binding.
  31932. *
  31933. * @private
  31934. * @param {string} groupName - The group name.
  31935. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  31936. * @return {BindGroup} The bind group
  31937. */
  31938. _getBindGroup( groupName, bindings ) {
  31939. const bindGroupsCache = this.getBindGroupsCache();
  31940. //
  31941. const bindingsArray = [];
  31942. let sharedGroup = true;
  31943. for ( const binding of bindings ) {
  31944. bindingsArray.push( binding );
  31945. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  31946. }
  31947. //
  31948. let bindGroup;
  31949. if ( sharedGroup ) {
  31950. bindGroup = bindGroupsCache.get( bindingsArray );
  31951. if ( bindGroup === undefined ) {
  31952. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31953. bindGroupsCache.set( bindingsArray, bindGroup );
  31954. }
  31955. } else {
  31956. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31957. }
  31958. return bindGroup;
  31959. }
  31960. /**
  31961. * Returns an array of node uniform groups for the given group name and shader stage.
  31962. *
  31963. * @param {string} groupName - The group name.
  31964. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31965. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  31966. */
  31967. getBindGroupArray( groupName, shaderStage ) {
  31968. const bindings = this.bindings[ shaderStage ];
  31969. let bindGroup = bindings[ groupName ];
  31970. if ( bindGroup === undefined ) {
  31971. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  31972. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  31973. }
  31974. bindings[ groupName ] = bindGroup = [];
  31975. }
  31976. return bindGroup;
  31977. }
  31978. /**
  31979. * Returns a list bindings of all shader stages separated by groups.
  31980. *
  31981. * @return {Array<BindGroup>} The list of bindings.
  31982. */
  31983. getBindings() {
  31984. let bindingsGroups = this.bindGroups;
  31985. if ( bindingsGroups === null ) {
  31986. const groups = {};
  31987. const bindings = this.bindings;
  31988. for ( const shaderStage of shaderStages ) {
  31989. for ( const groupName in bindings[ shaderStage ] ) {
  31990. const uniforms = bindings[ shaderStage ][ groupName ];
  31991. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  31992. groupUniforms.push( ...uniforms );
  31993. }
  31994. }
  31995. bindingsGroups = [];
  31996. for ( const groupName in groups ) {
  31997. const group = groups[ groupName ];
  31998. const bindingsGroup = this._getBindGroup( groupName, group );
  31999. bindingsGroups.push( bindingsGroup );
  32000. }
  32001. this.bindGroups = bindingsGroups;
  32002. }
  32003. return bindingsGroups;
  32004. }
  32005. /**
  32006. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  32007. */
  32008. sortBindingGroups() {
  32009. const bindingsGroups = this.getBindings();
  32010. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  32011. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  32012. const bindingGroup = bindingsGroups[ i ];
  32013. this.bindingsIndexes[ bindingGroup.name ].group = i;
  32014. bindingGroup.index = i;
  32015. }
  32016. }
  32017. /**
  32018. * The builder maintains each node in a hash-based dictionary.
  32019. * This method sets the given node (value) with the given hash (key) into this dictionary.
  32020. *
  32021. * @param {Node} node - The node to add.
  32022. * @param {number} hash - The hash of the node.
  32023. */
  32024. setHashNode( node, hash ) {
  32025. this.hashNodes[ hash ] = node;
  32026. }
  32027. /**
  32028. * Adds a node to this builder.
  32029. *
  32030. * @param {Node} node - The node to add.
  32031. */
  32032. addNode( node ) {
  32033. if ( this.nodes.includes( node ) === false ) {
  32034. this.nodes.push( node );
  32035. this.setHashNode( node, node.getHash( this ) );
  32036. }
  32037. }
  32038. /**
  32039. * It is used to add Nodes that will be used as FRAME and RENDER events,
  32040. * and need to follow a certain sequence in the calls to work correctly.
  32041. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  32042. *
  32043. * @param {Node} node - The node to add.
  32044. */
  32045. addSequentialNode( node ) {
  32046. if ( this.sequentialNodes.includes( node ) === false ) {
  32047. this.sequentialNodes.push( node );
  32048. }
  32049. }
  32050. /**
  32051. * Checks the update types of nodes
  32052. */
  32053. buildUpdateNodes() {
  32054. for ( const node of this.nodes ) {
  32055. const updateType = node.getUpdateType();
  32056. if ( updateType !== NodeUpdateType.NONE ) {
  32057. this.updateNodes.push( node.getSelf() );
  32058. }
  32059. }
  32060. for ( const node of this.sequentialNodes ) {
  32061. const updateBeforeType = node.getUpdateBeforeType();
  32062. const updateAfterType = node.getUpdateAfterType();
  32063. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  32064. this.updateBeforeNodes.push( node.getSelf() );
  32065. }
  32066. if ( updateAfterType !== NodeUpdateType.NONE ) {
  32067. this.updateAfterNodes.push( node.getSelf() );
  32068. }
  32069. }
  32070. }
  32071. /**
  32072. * A reference the current node which is the
  32073. * last node in the chain of nodes.
  32074. *
  32075. * @type {Node}
  32076. */
  32077. get currentNode() {
  32078. return this.chaining[ this.chaining.length - 1 ];
  32079. }
  32080. /**
  32081. * Whether the given texture is filtered or not.
  32082. *
  32083. * @param {Texture} texture - The texture to check.
  32084. * @return {boolean} Whether the given texture is filtered or not.
  32085. */
  32086. isFilteredTexture( texture ) {
  32087. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  32088. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  32089. }
  32090. /**
  32091. * Adds the given node to the internal node chain.
  32092. * This is used to check recursive calls in node-graph.
  32093. *
  32094. * @param {Node} node - The node to add.
  32095. */
  32096. addChain( node ) {
  32097. /*
  32098. if ( this.chaining.indexOf( node ) !== - 1 ) {
  32099. console.warn( 'Recursive node: ', node );
  32100. }
  32101. */
  32102. this.chaining.push( node );
  32103. }
  32104. /**
  32105. * Removes the given node from the internal node chain.
  32106. *
  32107. * @param {Node} node - The node to remove.
  32108. */
  32109. removeChain( node ) {
  32110. const lastChain = this.chaining.pop();
  32111. if ( lastChain !== node ) {
  32112. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  32113. }
  32114. }
  32115. /**
  32116. * Returns the native shader method name for a given generic name. E.g.
  32117. * the method name `textureDimensions` matches the WGSL name but must be
  32118. * resolved to `textureSize` in GLSL.
  32119. *
  32120. * @abstract
  32121. * @param {string} method - The method name to resolve.
  32122. * @return {string} The resolved method name.
  32123. */
  32124. getMethod( method ) {
  32125. return method;
  32126. }
  32127. /**
  32128. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  32129. *
  32130. * @param {number} hash - The hash of the node.
  32131. * @return {Node} The found node.
  32132. */
  32133. getNodeFromHash( hash ) {
  32134. return this.hashNodes[ hash ];
  32135. }
  32136. /**
  32137. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  32138. *
  32139. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  32140. * @param {Node} node - The node to add.
  32141. * @return {Node} The node.
  32142. */
  32143. addFlow( shaderStage, node ) {
  32144. this.flowNodes[ shaderStage ].push( node );
  32145. return node;
  32146. }
  32147. /**
  32148. * Sets builder's context.
  32149. *
  32150. * @param {Object} context - The context to set.
  32151. */
  32152. setContext( context ) {
  32153. this.context = context;
  32154. }
  32155. /**
  32156. * Returns the builder's current context.
  32157. *
  32158. * @return {Object} The builder's current context.
  32159. */
  32160. getContext() {
  32161. return this.context;
  32162. }
  32163. /**
  32164. * Gets a context used in shader construction that can be shared across different materials.
  32165. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  32166. *
  32167. * @return {Object} The builder's current context without material.
  32168. */
  32169. getSharedContext() {
  32170. ({ ...this.context });
  32171. return this.context;
  32172. }
  32173. /**
  32174. * Sets builder's cache.
  32175. *
  32176. * @param {NodeCache} cache - The cache to set.
  32177. */
  32178. setCache( cache ) {
  32179. this.cache = cache;
  32180. }
  32181. /**
  32182. * Returns the builder's current cache.
  32183. *
  32184. * @return {NodeCache} The builder's current cache.
  32185. */
  32186. getCache() {
  32187. return this.cache;
  32188. }
  32189. /**
  32190. * Returns a cache for the given node.
  32191. *
  32192. * @param {Node} node - The node.
  32193. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  32194. * @return {NodeCache} The cache.
  32195. */
  32196. getCacheFromNode( node, parent = true ) {
  32197. const data = this.getDataFromNode( node );
  32198. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  32199. return data.cache;
  32200. }
  32201. /**
  32202. * Whether the requested feature is available or not.
  32203. *
  32204. * @abstract
  32205. * @param {string} name - The requested feature.
  32206. * @return {boolean} Whether the requested feature is supported or not.
  32207. */
  32208. isAvailable( /*name*/ ) {
  32209. return false;
  32210. }
  32211. /**
  32212. * Returns the vertexIndex input variable as a native shader string.
  32213. *
  32214. * @abstract
  32215. * @return {string} The instanceIndex shader string.
  32216. */
  32217. getVertexIndex() {
  32218. console.warn( 'Abstract function.' );
  32219. }
  32220. /**
  32221. * Returns the instanceIndex input variable as a native shader string.
  32222. *
  32223. * @abstract
  32224. * @return {string} The instanceIndex shader string.
  32225. */
  32226. getInstanceIndex() {
  32227. console.warn( 'Abstract function.' );
  32228. }
  32229. /**
  32230. * Returns the drawIndex input variable as a native shader string.
  32231. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  32232. *
  32233. * @abstract
  32234. * @return {?string} The drawIndex shader string.
  32235. */
  32236. getDrawIndex() {
  32237. console.warn( 'Abstract function.' );
  32238. }
  32239. /**
  32240. * Returns the frontFacing input variable as a native shader string.
  32241. *
  32242. * @abstract
  32243. * @return {string} The frontFacing shader string.
  32244. */
  32245. getFrontFacing() {
  32246. console.warn( 'Abstract function.' );
  32247. }
  32248. /**
  32249. * Returns the fragCoord input variable as a native shader string.
  32250. *
  32251. * @abstract
  32252. * @return {string} The fragCoord shader string.
  32253. */
  32254. getFragCoord() {
  32255. console.warn( 'Abstract function.' );
  32256. }
  32257. /**
  32258. * Whether to flip texture data along its vertical axis or not. WebGL needs
  32259. * this method evaluate to `true`, WebGPU to `false`.
  32260. *
  32261. * @abstract
  32262. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  32263. */
  32264. isFlipY() {
  32265. return false;
  32266. }
  32267. /**
  32268. * Calling this method increases the usage count for the given node by one.
  32269. *
  32270. * @param {Node} node - The node to increase the usage count for.
  32271. * @return {number} The updated usage count.
  32272. */
  32273. increaseUsage( node ) {
  32274. const nodeData = this.getDataFromNode( node );
  32275. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  32276. return nodeData.usageCount;
  32277. }
  32278. /**
  32279. * Generates a texture sample shader string for the given texture data.
  32280. *
  32281. * @abstract
  32282. * @param {Texture} texture - The texture.
  32283. * @param {string} textureProperty - The texture property name.
  32284. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  32285. * @return {string} The generated shader string.
  32286. */
  32287. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  32288. console.warn( 'Abstract function.' );
  32289. }
  32290. /**
  32291. * Generates a texture LOD shader string for the given texture data.
  32292. *
  32293. * @abstract
  32294. * @param {Texture} texture - The texture.
  32295. * @param {string} textureProperty - The texture property name.
  32296. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  32297. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  32298. * @param {string} levelSnippet - Snippet defining the mip level.
  32299. * @return {string} The generated shader string.
  32300. */
  32301. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  32302. console.warn( 'Abstract function.' );
  32303. }
  32304. /**
  32305. * Generates the array declaration string.
  32306. *
  32307. * @param {string} type - The type.
  32308. * @param {?number} [count] - The count.
  32309. * @return {string} The generated value as a shader string.
  32310. */
  32311. generateArrayDeclaration( type, count ) {
  32312. return this.getType( type ) + '[ ' + count + ' ]';
  32313. }
  32314. /**
  32315. * Generates the array shader string for the given type and value.
  32316. *
  32317. * @param {string} type - The type.
  32318. * @param {?number} [count] - The count.
  32319. * @param {?Array<Node>} [values=null] - The default values.
  32320. * @return {string} The generated value as a shader string.
  32321. */
  32322. generateArray( type, count, values = null ) {
  32323. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  32324. for ( let i = 0; i < count; i ++ ) {
  32325. const value = values ? values[ i ] : null;
  32326. if ( value !== null ) {
  32327. snippet += value.build( this, type );
  32328. } else {
  32329. snippet += this.generateConst( type );
  32330. }
  32331. if ( i < count - 1 ) snippet += ', ';
  32332. }
  32333. snippet += ' )';
  32334. return snippet;
  32335. }
  32336. /**
  32337. * Generates the struct shader string.
  32338. *
  32339. * @param {string} type - The type.
  32340. * @param {Array<Object>} [membersLayout] - The count.
  32341. * @param {?Array<Node>} [values=null] - The default values.
  32342. * @return {string} The generated value as a shader string.
  32343. */
  32344. generateStruct( type, membersLayout, values = null ) {
  32345. const snippets = [];
  32346. for ( const member of membersLayout ) {
  32347. const { name, type } = member;
  32348. if ( values && values[ name ] && values[ name ].isNode ) {
  32349. snippets.push( values[ name ].build( this, type ) );
  32350. } else {
  32351. snippets.push( this.generateConst( type ) );
  32352. }
  32353. }
  32354. return type + '( ' + snippets.join( ', ' ) + ' )';
  32355. }
  32356. /**
  32357. * Generates the shader string for the given type and value.
  32358. *
  32359. * @param {string} type - The type.
  32360. * @param {?any} [value=null] - The value.
  32361. * @return {string} The generated value as a shader string.
  32362. */
  32363. generateConst( type, value = null ) {
  32364. if ( value === null ) {
  32365. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  32366. else if ( type === 'bool' ) value = false;
  32367. else if ( type === 'color' ) value = new Color();
  32368. else if ( type === 'vec2' ) value = new Vector2();
  32369. else if ( type === 'vec3' ) value = new Vector3();
  32370. else if ( type === 'vec4' ) value = new Vector4();
  32371. }
  32372. if ( type === 'float' ) return toFloat( value );
  32373. if ( type === 'int' ) return `${ Math.round( value ) }`;
  32374. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  32375. if ( type === 'bool' ) return value ? 'true' : 'false';
  32376. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  32377. const typeLength = this.getTypeLength( type );
  32378. const componentType = this.getComponentType( type );
  32379. const generateConst = value => this.generateConst( componentType, value );
  32380. if ( typeLength === 2 ) {
  32381. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  32382. } else if ( typeLength === 3 ) {
  32383. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  32384. } else if ( typeLength === 4 && type !== 'mat2' ) {
  32385. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  32386. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  32387. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  32388. } else if ( typeLength > 4 ) {
  32389. return `${ this.getType( type ) }()`;
  32390. }
  32391. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  32392. }
  32393. /**
  32394. * It might be necessary to convert certain data types to different ones
  32395. * so this method can be used to hide the conversion.
  32396. *
  32397. * @param {string} type - The type.
  32398. * @return {string} The updated type.
  32399. */
  32400. getType( type ) {
  32401. if ( type === 'color' ) return 'vec3';
  32402. return type;
  32403. }
  32404. /**
  32405. * Whether the given attribute name is defined in the geometry or not.
  32406. *
  32407. * @param {string} name - The attribute name.
  32408. * @return {boolean} Whether the given attribute name is defined in the geometry.
  32409. */
  32410. hasGeometryAttribute( name ) {
  32411. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  32412. }
  32413. /**
  32414. * Returns a node attribute for the given name and type.
  32415. *
  32416. * @param {string} name - The attribute's name.
  32417. * @param {string} type - The attribute's type.
  32418. * @return {NodeAttribute} The node attribute.
  32419. */
  32420. getAttribute( name, type ) {
  32421. const attributes = this.attributes;
  32422. // find attribute
  32423. for ( const attribute of attributes ) {
  32424. if ( attribute.name === name ) {
  32425. return attribute;
  32426. }
  32427. }
  32428. // create a new if no exist
  32429. const attribute = new NodeAttribute( name, type );
  32430. this.registerDeclaration( attribute );
  32431. attributes.push( attribute );
  32432. return attribute;
  32433. }
  32434. /**
  32435. * Returns for the given node and shader stage the property name for the shader.
  32436. *
  32437. * @param {Node} node - The node.
  32438. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32439. * @return {string} The property name.
  32440. */
  32441. getPropertyName( node/*, shaderStage*/ ) {
  32442. return node.name;
  32443. }
  32444. /**
  32445. * Whether the given type is a vector type or not.
  32446. *
  32447. * @param {string} type - The type to check.
  32448. * @return {boolean} Whether the given type is a vector type or not.
  32449. */
  32450. isVector( type ) {
  32451. return /vec\d/.test( type );
  32452. }
  32453. /**
  32454. * Whether the given type is a matrix type or not.
  32455. *
  32456. * @param {string} type - The type to check.
  32457. * @return {boolean} Whether the given type is a matrix type or not.
  32458. */
  32459. isMatrix( type ) {
  32460. return /mat\d/.test( type );
  32461. }
  32462. /**
  32463. * Whether the given type is a reference type or not.
  32464. *
  32465. * @param {string} type - The type to check.
  32466. * @return {boolean} Whether the given type is a reference type or not.
  32467. */
  32468. isReference( type ) {
  32469. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  32470. }
  32471. /**
  32472. * Checks if the given texture requires a manual conversion to the working color space.
  32473. *
  32474. * @abstract
  32475. * @param {Texture} texture - The texture to check.
  32476. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  32477. */
  32478. needsToWorkingColorSpace( /*texture*/ ) {
  32479. return false;
  32480. }
  32481. /**
  32482. * Returns the component type of a given texture.
  32483. *
  32484. * @param {Texture} texture - The texture.
  32485. * @return {string} The component type.
  32486. */
  32487. getComponentTypeFromTexture( texture ) {
  32488. const type = texture.type;
  32489. if ( texture.isDataTexture ) {
  32490. if ( type === IntType ) return 'int';
  32491. if ( type === UnsignedIntType ) return 'uint';
  32492. }
  32493. return 'float';
  32494. }
  32495. /**
  32496. * Returns the element type for a given type.
  32497. *
  32498. * @param {string} type - The type.
  32499. * @return {string} The element type.
  32500. */
  32501. getElementType( type ) {
  32502. if ( type === 'mat2' ) return 'vec2';
  32503. if ( type === 'mat3' ) return 'vec3';
  32504. if ( type === 'mat4' ) return 'vec4';
  32505. return this.getComponentType( type );
  32506. }
  32507. /**
  32508. * Returns the component type for a given type.
  32509. *
  32510. * @param {string} type - The type.
  32511. * @return {string} The component type.
  32512. */
  32513. getComponentType( type ) {
  32514. type = this.getVectorType( type );
  32515. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  32516. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  32517. if ( componentType === null ) return null;
  32518. if ( componentType[ 1 ] === 'b' ) return 'bool';
  32519. if ( componentType[ 1 ] === 'i' ) return 'int';
  32520. if ( componentType[ 1 ] === 'u' ) return 'uint';
  32521. return 'float';
  32522. }
  32523. /**
  32524. * Returns the vector type for a given type.
  32525. *
  32526. * @param {string} type - The type.
  32527. * @return {string} The vector type.
  32528. */
  32529. getVectorType( type ) {
  32530. if ( type === 'color' ) return 'vec3';
  32531. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  32532. return type;
  32533. }
  32534. /**
  32535. * Returns the data type for the given the length and component type.
  32536. *
  32537. * @param {number} length - The length.
  32538. * @param {string} [componentType='float'] - The component type.
  32539. * @return {string} The type.
  32540. */
  32541. getTypeFromLength( length, componentType = 'float' ) {
  32542. if ( length === 1 ) return componentType;
  32543. let baseType = getTypeFromLength( length );
  32544. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  32545. // fix edge case for mat2x2 being same size as vec4
  32546. if ( /mat2/.test( componentType ) === true ) {
  32547. baseType = baseType.replace( 'vec', 'mat' );
  32548. }
  32549. return prefix + baseType;
  32550. }
  32551. /**
  32552. * Returns the type for a given typed array.
  32553. *
  32554. * @param {TypedArray} array - The typed array.
  32555. * @return {string} The type.
  32556. */
  32557. getTypeFromArray( array ) {
  32558. return typeFromArray.get( array.constructor );
  32559. }
  32560. /**
  32561. * Returns the type is an integer type.
  32562. *
  32563. * @param {string} type - The type.
  32564. * @return {boolean} Whether the type is an integer type or not.
  32565. */
  32566. isInteger( type ) {
  32567. return /int|uint|(i|u)vec/.test( type );
  32568. }
  32569. /**
  32570. * Returns the type for a given buffer attribute.
  32571. *
  32572. * @param {BufferAttribute} attribute - The buffer attribute.
  32573. * @return {string} The type.
  32574. */
  32575. getTypeFromAttribute( attribute ) {
  32576. let dataAttribute = attribute;
  32577. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  32578. const array = dataAttribute.array;
  32579. const itemSize = attribute.itemSize;
  32580. const normalized = attribute.normalized;
  32581. let arrayType;
  32582. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  32583. arrayType = this.getTypeFromArray( array );
  32584. }
  32585. return this.getTypeFromLength( itemSize, arrayType );
  32586. }
  32587. /**
  32588. * Returns the length for the given data type.
  32589. *
  32590. * @param {string} type - The data type.
  32591. * @return {number} The length.
  32592. */
  32593. getTypeLength( type ) {
  32594. const vecType = this.getVectorType( type );
  32595. const vecNum = /vec([2-4])/.exec( vecType );
  32596. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  32597. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  32598. if ( /mat2/.test( type ) === true ) return 4;
  32599. if ( /mat3/.test( type ) === true ) return 9;
  32600. if ( /mat4/.test( type ) === true ) return 16;
  32601. return 0;
  32602. }
  32603. /**
  32604. * Returns the vector type for a given matrix type.
  32605. *
  32606. * @param {string} type - The matrix type.
  32607. * @return {string} The vector type.
  32608. */
  32609. getVectorFromMatrix( type ) {
  32610. return type.replace( 'mat', 'vec' );
  32611. }
  32612. /**
  32613. * For a given type this method changes the component type to the
  32614. * given value. E.g. `vec4` should be changed to the new component type
  32615. * `uint` which results in `uvec4`.
  32616. *
  32617. * @param {string} type - The type.
  32618. * @param {string} newComponentType - The new component type.
  32619. * @return {string} The new type.
  32620. */
  32621. changeComponentType( type, newComponentType ) {
  32622. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  32623. }
  32624. /**
  32625. * Returns the integer type pendant for the given type.
  32626. *
  32627. * @param {string} type - The type.
  32628. * @return {string} The integer type.
  32629. */
  32630. getIntegerType( type ) {
  32631. const componentType = this.getComponentType( type );
  32632. if ( componentType === 'int' || componentType === 'uint' ) return type;
  32633. return this.changeComponentType( type, 'int' );
  32634. }
  32635. /**
  32636. * Adds a stack node to the internal stack.
  32637. *
  32638. * @return {StackNode} The added stack node.
  32639. */
  32640. addStack() {
  32641. this.stack = stack( this.stack );
  32642. this.stacks.push( getCurrentStack() || this.stack );
  32643. setCurrentStack( this.stack );
  32644. return this.stack;
  32645. }
  32646. /**
  32647. * Removes the last stack node from the internal stack.
  32648. *
  32649. * @return {StackNode} The removed stack node.
  32650. */
  32651. removeStack() {
  32652. const lastStack = this.stack;
  32653. this.stack = lastStack.parent;
  32654. setCurrentStack( this.stacks.pop() );
  32655. return lastStack;
  32656. }
  32657. /**
  32658. * The builder maintains (cached) data for each node during the building process. This method
  32659. * can be used to get these data for a specific shader stage and cache.
  32660. *
  32661. * @param {Node} node - The node to get the data for.
  32662. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32663. * @param {?NodeCache} cache - An optional cache.
  32664. * @return {Object} The node data.
  32665. */
  32666. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  32667. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  32668. let nodeData = cache.getData( node );
  32669. if ( nodeData === undefined ) {
  32670. nodeData = {};
  32671. cache.setData( node, nodeData );
  32672. }
  32673. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  32674. return nodeData[ shaderStage ];
  32675. }
  32676. /**
  32677. * Returns the properties for the given node and shader stage.
  32678. *
  32679. * @param {Node} node - The node to get the properties for.
  32680. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  32681. * @return {Object} The node properties.
  32682. */
  32683. getNodeProperties( node, shaderStage = 'any' ) {
  32684. const nodeData = this.getDataFromNode( node, shaderStage );
  32685. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  32686. }
  32687. /**
  32688. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  32689. *
  32690. * @param {BufferAttributeNode} node - The buffer attribute node.
  32691. * @param {string} type - The node type.
  32692. * @return {NodeAttribute} The node attribute.
  32693. */
  32694. getBufferAttributeFromNode( node, type ) {
  32695. const nodeData = this.getDataFromNode( node );
  32696. let bufferAttribute = nodeData.bufferAttribute;
  32697. if ( bufferAttribute === undefined ) {
  32698. const index = this.uniforms.index ++;
  32699. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  32700. this.bufferAttributes.push( bufferAttribute );
  32701. nodeData.bufferAttribute = bufferAttribute;
  32702. }
  32703. return bufferAttribute;
  32704. }
  32705. /**
  32706. * Returns an instance of {@link StructType} for the given output struct node.
  32707. *
  32708. * @param {OutputStructNode} node - The output struct node.
  32709. * @param {Array<Object>} membersLayout - The output struct types.
  32710. * @param {?string} [name=null] - The name of the struct.
  32711. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32712. * @return {StructType} The struct type attribute.
  32713. */
  32714. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  32715. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  32716. let structType = nodeData.structType;
  32717. if ( structType === undefined ) {
  32718. const index = this.structs.index ++;
  32719. if ( name === null ) name = 'StructType' + index;
  32720. structType = new StructType( name, membersLayout );
  32721. this.structs[ shaderStage ].push( structType );
  32722. nodeData.structType = structType;
  32723. }
  32724. return structType;
  32725. }
  32726. /**
  32727. * Returns an instance of {@link StructType} for the given output struct node.
  32728. *
  32729. * @param {OutputStructNode} node - The output struct node.
  32730. * @param {Array<Object>} membersLayout - The output struct types.
  32731. * @return {StructType} The struct type attribute.
  32732. */
  32733. getOutputStructTypeFromNode( node, membersLayout ) {
  32734. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  32735. structType.output = true;
  32736. return structType;
  32737. }
  32738. /**
  32739. * Returns an instance of {@link NodeUniform} for the given uniform node.
  32740. *
  32741. * @param {UniformNode} node - The uniform node.
  32742. * @param {string} type - The uniform type.
  32743. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32744. * @param {?string} name - The name of the uniform.
  32745. * @return {NodeUniform} The node uniform.
  32746. */
  32747. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  32748. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  32749. let nodeUniform = nodeData.uniform;
  32750. if ( nodeUniform === undefined ) {
  32751. const index = this.uniforms.index ++;
  32752. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  32753. this.uniforms[ shaderStage ].push( nodeUniform );
  32754. this.registerDeclaration( nodeUniform );
  32755. nodeData.uniform = nodeUniform;
  32756. }
  32757. return nodeUniform;
  32758. }
  32759. /**
  32760. * Returns the array length.
  32761. *
  32762. * @param {Node} node - The node.
  32763. * @return {?number} The array length.
  32764. */
  32765. getArrayCount( node ) {
  32766. let count = null;
  32767. if ( node.isArrayNode ) count = node.count;
  32768. else if ( node.isVarNode && node.node.isArrayNode ) count = node.node.count;
  32769. return count;
  32770. }
  32771. /**
  32772. * Returns an instance of {@link NodeVar} for the given variable node.
  32773. *
  32774. * @param {VarNode} node - The variable node.
  32775. * @param {?string} name - The variable's name.
  32776. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  32777. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32778. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  32779. *
  32780. * @return {NodeVar} The node variable.
  32781. */
  32782. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  32783. const nodeData = this.getDataFromNode( node, shaderStage );
  32784. let nodeVar = nodeData.variable;
  32785. if ( nodeVar === undefined ) {
  32786. const idNS = readOnly ? '_const' : '_var';
  32787. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  32788. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  32789. if ( name === null ) {
  32790. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  32791. this.vars[ idNS ] ++;
  32792. }
  32793. //
  32794. const count = this.getArrayCount( node );
  32795. nodeVar = new NodeVar( name, type, readOnly, count );
  32796. if ( ! readOnly ) {
  32797. vars.push( nodeVar );
  32798. }
  32799. this.registerDeclaration( nodeVar );
  32800. nodeData.variable = nodeVar;
  32801. }
  32802. return nodeVar;
  32803. }
  32804. /**
  32805. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  32806. *
  32807. * @param {Node} node - The varying node.
  32808. * @return {boolean} Returns true if deterministic.
  32809. */
  32810. isDeterministic( node ) {
  32811. if ( node.isMathNode ) {
  32812. return this.isDeterministic( node.aNode ) &&
  32813. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  32814. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  32815. } else if ( node.isOperatorNode ) {
  32816. return this.isDeterministic( node.aNode ) &&
  32817. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  32818. } else if ( node.isArrayNode ) {
  32819. if ( node.values !== null ) {
  32820. for ( const n of node.values ) {
  32821. if ( ! this.isDeterministic( n ) ) {
  32822. return false;
  32823. }
  32824. }
  32825. }
  32826. return true;
  32827. } else if ( node.isConstNode ) {
  32828. return true;
  32829. }
  32830. return false;
  32831. }
  32832. /**
  32833. * Returns an instance of {@link NodeVarying} for the given varying node.
  32834. *
  32835. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  32836. * @param {?string} name - The varying's name.
  32837. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  32838. * @param {?string} interpolationType - The interpolation type of the varying.
  32839. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  32840. * @return {NodeVar} The node varying.
  32841. */
  32842. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  32843. const nodeData = this.getDataFromNode( node, 'any' );
  32844. let nodeVarying = nodeData.varying;
  32845. if ( nodeVarying === undefined ) {
  32846. const varyings = this.varyings;
  32847. const index = varyings.length;
  32848. if ( name === null ) name = 'nodeVarying' + index;
  32849. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  32850. varyings.push( nodeVarying );
  32851. this.registerDeclaration( nodeVarying );
  32852. nodeData.varying = nodeVarying;
  32853. }
  32854. return nodeVarying;
  32855. }
  32856. /**
  32857. * Returns the current namespace for the node builder.
  32858. *
  32859. * @return {string} The current namespace.
  32860. */
  32861. get namespace() {
  32862. return this.context.namespace;
  32863. }
  32864. /**
  32865. * Returns the output namespace for the node builder, which is used for the current output node.
  32866. *
  32867. * @return {string} The output namespace.
  32868. */
  32869. getOutputNamespace() {
  32870. return this.getNamespace( 'outputNode' );
  32871. }
  32872. /**
  32873. * Returns the namespace for the given property.
  32874. *
  32875. * If the property name is not set, it returns the namespace only.
  32876. * If the namespace is not set, it returns the property name.
  32877. * If the namespace is set, it returns the namespace concatenated with the property name.
  32878. *
  32879. * @param {string} [property=''] - The property name.
  32880. * @return {string} The namespace for the property.
  32881. */
  32882. getNamespace( property = '' ) {
  32883. const ns = this.namespace;
  32884. let nsName;
  32885. if ( ns ) {
  32886. nsName = property ? ( ns + '_' + property ) : ns;
  32887. } else {
  32888. nsName = property;
  32889. }
  32890. return nsName;
  32891. }
  32892. /**
  32893. * Registers a node declaration in the current shader stage.
  32894. *
  32895. * @param {Object} node - The node to be registered.
  32896. */
  32897. registerDeclaration( node ) {
  32898. const shaderStage = this.shaderStage;
  32899. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  32900. const property = this.getPropertyName( node );
  32901. let index = 1;
  32902. let name = property;
  32903. // Automatically renames the property if the name is already in use.
  32904. while ( declarations[ name ] !== undefined ) {
  32905. name = property + '_' + index ++;
  32906. }
  32907. if ( index > 1 ) {
  32908. node.name = name;
  32909. console.warn( `THREE.TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  32910. }
  32911. declarations[ name ] = node;
  32912. }
  32913. /**
  32914. * Returns an instance of {@link NodeCode} for the given code node.
  32915. *
  32916. * @param {CodeNode} node - The code node.
  32917. * @param {string} type - The node type.
  32918. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32919. * @return {NodeCode} The node code.
  32920. */
  32921. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  32922. const nodeData = this.getDataFromNode( node );
  32923. let nodeCode = nodeData.code;
  32924. if ( nodeCode === undefined ) {
  32925. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  32926. const index = codes.length;
  32927. nodeCode = new NodeCode( 'nodeCode' + index, type );
  32928. codes.push( nodeCode );
  32929. nodeData.code = nodeCode;
  32930. }
  32931. return nodeCode;
  32932. }
  32933. /**
  32934. * Adds a code flow based on the code-block hierarchy.
  32935. * This is used so that code-blocks like If,Else create their variables locally if the Node
  32936. * is only used inside one of these conditionals in the current shader stage.
  32937. *
  32938. * @param {Node} node - The node to add.
  32939. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  32940. */
  32941. addFlowCodeHierarchy( node, nodeBlock ) {
  32942. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  32943. let needsFlowCode = true;
  32944. let nodeBlockHierarchy = nodeBlock;
  32945. while ( nodeBlockHierarchy ) {
  32946. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  32947. needsFlowCode = false;
  32948. break;
  32949. }
  32950. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  32951. }
  32952. if ( needsFlowCode ) {
  32953. for ( const flowCode of flowCodes ) {
  32954. this.addLineFlowCode( flowCode );
  32955. }
  32956. }
  32957. }
  32958. /**
  32959. * Add a inline-code to the current flow code-block.
  32960. *
  32961. * @param {Node} node - The node to add.
  32962. * @param {string} code - The code to add.
  32963. * @param {Node} nodeBlock - Current ConditionalNode
  32964. */
  32965. addLineFlowCodeBlock( node, code, nodeBlock ) {
  32966. const nodeData = this.getDataFromNode( node );
  32967. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  32968. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  32969. flowCodes.push( code );
  32970. codeBlock.set( nodeBlock, true );
  32971. }
  32972. /**
  32973. * Add a inline-code to the current flow.
  32974. *
  32975. * @param {string} code - The code to add.
  32976. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  32977. * @return {NodeBuilder} A reference to this node builder.
  32978. */
  32979. addLineFlowCode( code, node = null ) {
  32980. if ( code === '' ) return this;
  32981. if ( node !== null && this.context.nodeBlock ) {
  32982. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  32983. }
  32984. code = this.tab + code;
  32985. if ( ! /;\s*$/.test( code ) ) {
  32986. code = code + ';\n';
  32987. }
  32988. this.flow.code += code;
  32989. return this;
  32990. }
  32991. /**
  32992. * Adds a code to the current code flow.
  32993. *
  32994. * @param {string} code - Shader code.
  32995. * @return {NodeBuilder} A reference to this node builder.
  32996. */
  32997. addFlowCode( code ) {
  32998. this.flow.code += code;
  32999. return this;
  33000. }
  33001. /**
  33002. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  33003. * Typically used in codes with If,Else.
  33004. *
  33005. * @return {NodeBuilder} A reference to this node builder.
  33006. */
  33007. addFlowTab() {
  33008. this.tab += '\t';
  33009. return this;
  33010. }
  33011. /**
  33012. * Removes a tab.
  33013. *
  33014. * @return {NodeBuilder} A reference to this node builder.
  33015. */
  33016. removeFlowTab() {
  33017. this.tab = this.tab.slice( 0, -1 );
  33018. return this;
  33019. }
  33020. /**
  33021. * Gets the current flow data based on a Node.
  33022. *
  33023. * @param {Node} node - Node that the flow was started.
  33024. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33025. * @return {Object} The flow data.
  33026. */
  33027. getFlowData( node/*, shaderStage*/ ) {
  33028. return this.flowsData.get( node );
  33029. }
  33030. /**
  33031. * Executes the node flow based on a root node to generate the final shader code.
  33032. *
  33033. * @param {Node} node - The node to execute.
  33034. * @return {Object} The code flow.
  33035. */
  33036. flowNode( node ) {
  33037. const output = node.getNodeType( this );
  33038. const flowData = this.flowChildNode( node, output );
  33039. this.flowsData.set( node, flowData );
  33040. return flowData;
  33041. }
  33042. /**
  33043. * Includes a node in the current function node.
  33044. *
  33045. * @param {Node} node - The node to include.
  33046. * @returns {void}
  33047. */
  33048. addInclude( node ) {
  33049. if ( this.currentFunctionNode !== null ) {
  33050. this.currentFunctionNode.includes.push( node );
  33051. }
  33052. }
  33053. /**
  33054. * Returns the native shader operator name for a given generic name.
  33055. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  33056. *
  33057. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  33058. * @return {FunctionNode} The build function node.
  33059. */
  33060. buildFunctionNode( shaderNode ) {
  33061. const fn = new FunctionNode();
  33062. const previous = this.currentFunctionNode;
  33063. this.currentFunctionNode = fn;
  33064. fn.code = this.buildFunctionCode( shaderNode );
  33065. this.currentFunctionNode = previous;
  33066. return fn;
  33067. }
  33068. /**
  33069. * Generates a code flow based on a TSL function: Fn().
  33070. *
  33071. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  33072. * @return {Object}
  33073. */
  33074. flowShaderNode( shaderNode ) {
  33075. const layout = shaderNode.layout;
  33076. const inputs = {
  33077. [ Symbol.iterator ]() {
  33078. let index = 0;
  33079. const values = Object.values( this );
  33080. return {
  33081. next: () => ( {
  33082. value: values[ index ],
  33083. done: index ++ >= values.length
  33084. } )
  33085. };
  33086. }
  33087. };
  33088. for ( const input of layout.inputs ) {
  33089. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  33090. }
  33091. //
  33092. shaderNode.layout = null;
  33093. const callNode = shaderNode.call( inputs );
  33094. const flowData = this.flowStagesNode( callNode, layout.type );
  33095. shaderNode.layout = layout;
  33096. return flowData;
  33097. }
  33098. /**
  33099. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  33100. *
  33101. * @param {Node} node - The node to execute.
  33102. * @param {?string} output - Expected output type. For example 'vec3'.
  33103. * @return {Object}
  33104. */
  33105. flowStagesNode( node, output = null ) {
  33106. const previousFlow = this.flow;
  33107. const previousVars = this.vars;
  33108. const previousDeclarations = this.declarations;
  33109. const previousCache = this.cache;
  33110. const previousBuildStage = this.buildStage;
  33111. const previousStack = this.stack;
  33112. const flow = {
  33113. code: ''
  33114. };
  33115. this.flow = flow;
  33116. this.vars = {};
  33117. this.declarations = {};
  33118. this.cache = new NodeCache();
  33119. this.stack = stack();
  33120. for ( const buildStage of defaultBuildStages ) {
  33121. this.setBuildStage( buildStage );
  33122. flow.result = node.build( this, output );
  33123. }
  33124. flow.vars = this.getVars( this.shaderStage );
  33125. this.flow = previousFlow;
  33126. this.vars = previousVars;
  33127. this.declarations = previousDeclarations;
  33128. this.cache = previousCache;
  33129. this.stack = previousStack;
  33130. this.setBuildStage( previousBuildStage );
  33131. return flow;
  33132. }
  33133. /**
  33134. * Returns the native shader operator name for a given generic name.
  33135. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  33136. *
  33137. * @abstract
  33138. * @param {string} op - The operator name to resolve.
  33139. * @return {?string} The resolved operator name.
  33140. */
  33141. getFunctionOperator( /* op */ ) {
  33142. return null;
  33143. }
  33144. /**
  33145. * Builds the given shader node.
  33146. *
  33147. * @abstract
  33148. * @param {ShaderNodeInternal} shaderNode - The shader node.
  33149. * @return {string} The function code.
  33150. */
  33151. buildFunctionCode( /* shaderNode */ ) {
  33152. console.warn( 'Abstract function.' );
  33153. }
  33154. /**
  33155. * Generates a code flow based on a child Node.
  33156. *
  33157. * @param {Node} node - The node to execute.
  33158. * @param {?string} output - Expected output type. For example 'vec3'.
  33159. * @return {Object} The code flow.
  33160. */
  33161. flowChildNode( node, output = null ) {
  33162. const previousFlow = this.flow;
  33163. const flow = {
  33164. code: ''
  33165. };
  33166. this.flow = flow;
  33167. flow.result = node.build( this, output );
  33168. this.flow = previousFlow;
  33169. return flow;
  33170. }
  33171. /**
  33172. * Executes a flow of code in a different stage.
  33173. *
  33174. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  33175. * return the value in fragment-stage even if it is being executed in an input fragment.
  33176. *
  33177. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33178. * @param {Node} node - The node to execute.
  33179. * @param {?string} output - Expected output type. For example 'vec3'.
  33180. * @param {?string} propertyName - The property name to assign the result.
  33181. * @return {Object|Node|null} The code flow or node.build() result.
  33182. */
  33183. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  33184. const previousTab = this.tab;
  33185. const previousCache = this.cache;
  33186. const previousShaderStage = this.shaderStage;
  33187. const previousContext = this.context;
  33188. this.setShaderStage( shaderStage );
  33189. const context = { ...this.context };
  33190. delete context.nodeBlock;
  33191. this.cache = this.globalCache;
  33192. this.tab = '\t';
  33193. this.context = context;
  33194. let result = null;
  33195. if ( this.buildStage === 'generate' ) {
  33196. const flowData = this.flowChildNode( node, output );
  33197. if ( propertyName !== null ) {
  33198. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  33199. }
  33200. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  33201. result = flowData;
  33202. } else {
  33203. result = node.build( this );
  33204. }
  33205. this.setShaderStage( previousShaderStage );
  33206. this.cache = previousCache;
  33207. this.tab = previousTab;
  33208. this.context = previousContext;
  33209. return result;
  33210. }
  33211. /**
  33212. * Returns an array holding all node attributes of this node builder.
  33213. *
  33214. * @return {Array<NodeAttribute>} The node attributes of this builder.
  33215. */
  33216. getAttributesArray() {
  33217. return this.attributes.concat( this.bufferAttributes );
  33218. }
  33219. /**
  33220. * Returns the attribute definitions as a shader string for the given shader stage.
  33221. *
  33222. * @abstract
  33223. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33224. * @return {string} The attribute code section.
  33225. */
  33226. getAttributes( /*shaderStage*/ ) {
  33227. console.warn( 'Abstract function.' );
  33228. }
  33229. /**
  33230. * Returns the varying definitions as a shader string for the given shader stage.
  33231. *
  33232. * @abstract
  33233. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33234. * @return {string} The varying code section.
  33235. */
  33236. getVaryings( /*shaderStage*/ ) {
  33237. console.warn( 'Abstract function.' );
  33238. }
  33239. /**
  33240. * Returns a single variable definition as a shader string for the given variable type and name.
  33241. *
  33242. * @param {string} type - The variable's type.
  33243. * @param {string} name - The variable's name.
  33244. * @param {?number} [count=null] - The array length.
  33245. * @return {string} The shader string.
  33246. */
  33247. getVar( type, name, count = null ) {
  33248. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  33249. }
  33250. /**
  33251. * Returns the variable definitions as a shader string for the given shader stage.
  33252. *
  33253. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33254. * @return {string} The variable code section.
  33255. */
  33256. getVars( shaderStage ) {
  33257. let snippet = '';
  33258. const vars = this.vars[ shaderStage ];
  33259. if ( vars !== undefined ) {
  33260. for ( const variable of vars ) {
  33261. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  33262. }
  33263. }
  33264. return snippet;
  33265. }
  33266. /**
  33267. * Returns the uniform definitions as a shader string for the given shader stage.
  33268. *
  33269. * @abstract
  33270. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33271. * @return {string} The uniform code section.
  33272. */
  33273. getUniforms( /*shaderStage*/ ) {
  33274. console.warn( 'Abstract function.' );
  33275. }
  33276. /**
  33277. * Returns the native code definitions as a shader string for the given shader stage.
  33278. *
  33279. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33280. * @return {string} The native code section.
  33281. */
  33282. getCodes( shaderStage ) {
  33283. const codes = this.codes[ shaderStage ];
  33284. let code = '';
  33285. if ( codes !== undefined ) {
  33286. for ( const nodeCode of codes ) {
  33287. code += nodeCode.code + '\n';
  33288. }
  33289. }
  33290. return code;
  33291. }
  33292. /**
  33293. * Returns the hash of this node builder.
  33294. *
  33295. * @return {string} The hash.
  33296. */
  33297. getHash() {
  33298. return this.vertexShader + this.fragmentShader + this.computeShader;
  33299. }
  33300. /**
  33301. * Sets the current shader stage.
  33302. *
  33303. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  33304. */
  33305. setShaderStage( shaderStage ) {
  33306. this.shaderStage = shaderStage;
  33307. }
  33308. /**
  33309. * Returns the current shader stage.
  33310. *
  33311. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  33312. */
  33313. getShaderStage() {
  33314. return this.shaderStage;
  33315. }
  33316. /**
  33317. * Sets the current build stage.
  33318. *
  33319. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  33320. */
  33321. setBuildStage( buildStage ) {
  33322. this.buildStage = buildStage;
  33323. }
  33324. /**
  33325. * Returns the current build stage.
  33326. *
  33327. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  33328. */
  33329. getBuildStage() {
  33330. return this.buildStage;
  33331. }
  33332. /**
  33333. * Controls the code build of the shader stages.
  33334. *
  33335. * @abstract
  33336. */
  33337. buildCode() {
  33338. console.warn( 'Abstract function.' );
  33339. }
  33340. /**
  33341. * Central build method which controls the build for the given object.
  33342. *
  33343. * @return {NodeBuilder} A reference to this node builder.
  33344. */
  33345. build() {
  33346. const { object, material, renderer } = this;
  33347. if ( material !== null ) {
  33348. let nodeMaterial = renderer.library.fromMaterial( material );
  33349. if ( nodeMaterial === null ) {
  33350. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  33351. nodeMaterial = new NodeMaterial();
  33352. }
  33353. nodeMaterial.build( this );
  33354. } else {
  33355. this.addFlow( 'compute', object );
  33356. }
  33357. // setup() -> stage 1: create possible new nodes and returns an output reference node
  33358. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  33359. // generate() -> stage 3: generate shader
  33360. for ( const buildStage of defaultBuildStages ) {
  33361. this.setBuildStage( buildStage );
  33362. if ( this.context.vertex && this.context.vertex.isNode ) {
  33363. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  33364. }
  33365. for ( const shaderStage of shaderStages ) {
  33366. this.setShaderStage( shaderStage );
  33367. const flowNodes = this.flowNodes[ shaderStage ];
  33368. for ( const node of flowNodes ) {
  33369. if ( buildStage === 'generate' ) {
  33370. this.flowNode( node );
  33371. } else {
  33372. node.build( this );
  33373. }
  33374. }
  33375. }
  33376. }
  33377. this.setBuildStage( null );
  33378. this.setShaderStage( null );
  33379. // stage 4: build code for a specific output
  33380. this.buildCode();
  33381. this.buildUpdateNodes();
  33382. return this;
  33383. }
  33384. /**
  33385. * Returns a uniform representation which is later used for UBO generation and rendering.
  33386. *
  33387. * @param {NodeUniform} uniformNode - The uniform node.
  33388. * @param {string} type - The requested type.
  33389. * @return {Uniform} The uniform.
  33390. */
  33391. getNodeUniform( uniformNode, type ) {
  33392. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  33393. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  33394. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  33395. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  33396. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  33397. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  33398. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  33399. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  33400. throw new Error( `Uniform "${type}" not declared.` );
  33401. }
  33402. /**
  33403. * Formats the given shader snippet from a given type into another one. E.g.
  33404. * this method might be used to convert a simple float string `"1.0"` into a
  33405. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  33406. *
  33407. * @param {string} snippet - The shader snippet.
  33408. * @param {string} fromType - The source type.
  33409. * @param {string} toType - The target type.
  33410. * @return {string} The updated shader string.
  33411. */
  33412. format( snippet, fromType, toType ) {
  33413. fromType = this.getVectorType( fromType );
  33414. toType = this.getVectorType( toType );
  33415. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  33416. return snippet;
  33417. }
  33418. const fromTypeLength = this.getTypeLength( fromType );
  33419. const toTypeLength = this.getTypeLength( toType );
  33420. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  33421. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  33422. }
  33423. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  33424. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  33425. }
  33426. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  33427. // @TODO: ignore for now
  33428. return snippet;
  33429. }
  33430. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  33431. // @TODO: ignore for now
  33432. return snippet;
  33433. }
  33434. if ( fromTypeLength === toTypeLength ) {
  33435. return `${ this.getType( toType ) }( ${ snippet } )`;
  33436. }
  33437. if ( fromTypeLength > toTypeLength ) {
  33438. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  33439. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  33440. }
  33441. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  33442. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  33443. }
  33444. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  33445. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  33446. }
  33447. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  33448. // convert a number value to vector type, e.g:
  33449. // vec3( 1u ) -> vec3( float( 1u ) )
  33450. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  33451. }
  33452. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  33453. }
  33454. /**
  33455. * Returns a signature with the engine's current revision.
  33456. *
  33457. * @return {string} The signature.
  33458. */
  33459. getSignature() {
  33460. return `// Three.js r${ REVISION } - Node System\n`;
  33461. }
  33462. /**
  33463. * Prevents the node builder from being used as an iterable in TSL.Fn(), avoiding potential runtime errors.
  33464. */
  33465. *[ Symbol.iterator ]() { }
  33466. // Deprecated
  33467. /**
  33468. * @function
  33469. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  33470. *
  33471. * @param {string} [type='NodeMaterial'] - The node material type.
  33472. * @throws {Error}
  33473. */
  33474. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  33475. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  33476. }
  33477. }
  33478. /**
  33479. * Management class for updating nodes. The module tracks metrics like
  33480. * the elapsed time, delta time, the render and frame ID to correctly
  33481. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  33482. * and {@link Node#updateAfter} depending on the node's configuration.
  33483. */
  33484. class NodeFrame {
  33485. /**
  33486. * Constructs a new node fame.
  33487. */
  33488. constructor() {
  33489. /**
  33490. * The elapsed time in seconds.
  33491. *
  33492. * @type {number}
  33493. * @default 0
  33494. */
  33495. this.time = 0;
  33496. /**
  33497. * The delta time in seconds.
  33498. *
  33499. * @type {number}
  33500. * @default 0
  33501. */
  33502. this.deltaTime = 0;
  33503. /**
  33504. * The frame ID.
  33505. *
  33506. * @type {number}
  33507. * @default 0
  33508. */
  33509. this.frameId = 0;
  33510. /**
  33511. * The render ID.
  33512. *
  33513. * @type {number}
  33514. * @default 0
  33515. */
  33516. this.renderId = 0;
  33517. /**
  33518. * Used to control the {@link Node#update} call.
  33519. *
  33520. * @type {WeakMap<Node, Object>}
  33521. */
  33522. this.updateMap = new WeakMap();
  33523. /**
  33524. * Used to control the {@link Node#updateBefore} call.
  33525. *
  33526. * @type {WeakMap<Node, Object>}
  33527. */
  33528. this.updateBeforeMap = new WeakMap();
  33529. /**
  33530. * Used to control the {@link Node#updateAfter} call.
  33531. *
  33532. * @type {WeakMap<Node, Object>}
  33533. */
  33534. this.updateAfterMap = new WeakMap();
  33535. /**
  33536. * A reference to the current renderer.
  33537. *
  33538. * @type {?Renderer}
  33539. * @default null
  33540. */
  33541. this.renderer = null;
  33542. /**
  33543. * A reference to the current material.
  33544. *
  33545. * @type {?Material}
  33546. * @default null
  33547. */
  33548. this.material = null;
  33549. /**
  33550. * A reference to the current camera.
  33551. *
  33552. * @type {?Camera}
  33553. * @default null
  33554. */
  33555. this.camera = null;
  33556. /**
  33557. * A reference to the current 3D object.
  33558. *
  33559. * @type {?Object3D}
  33560. * @default null
  33561. */
  33562. this.object = null;
  33563. /**
  33564. * A reference to the current scene.
  33565. *
  33566. * @type {?Scene}
  33567. * @default null
  33568. */
  33569. this.scene = null;
  33570. }
  33571. /**
  33572. * Returns a dictionary for a given node and update map which
  33573. * is used to correctly call node update methods per frame or render.
  33574. *
  33575. * @private
  33576. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  33577. * @param {Node} nodeRef - The reference to the current node.
  33578. * @return {Object<string,WeakMap>} The dictionary.
  33579. */
  33580. _getMaps( referenceMap, nodeRef ) {
  33581. let maps = referenceMap.get( nodeRef );
  33582. if ( maps === undefined ) {
  33583. maps = {
  33584. renderMap: new WeakMap(),
  33585. frameMap: new WeakMap()
  33586. };
  33587. referenceMap.set( nodeRef, maps );
  33588. }
  33589. return maps;
  33590. }
  33591. /**
  33592. * This method executes the {@link Node#updateBefore} for the given node.
  33593. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  33594. * is only executed once per frame, render or object depending on the update
  33595. * type.
  33596. *
  33597. * @param {Node} node - The node that should be updated.
  33598. */
  33599. updateBeforeNode( node ) {
  33600. const updateType = node.getUpdateBeforeType();
  33601. const reference = node.updateReference( this );
  33602. if ( updateType === NodeUpdateType.FRAME ) {
  33603. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  33604. if ( frameMap.get( reference ) !== this.frameId ) {
  33605. if ( node.updateBefore( this ) !== false ) {
  33606. frameMap.set( reference, this.frameId );
  33607. }
  33608. }
  33609. } else if ( updateType === NodeUpdateType.RENDER ) {
  33610. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  33611. if ( renderMap.get( reference ) !== this.renderId ) {
  33612. if ( node.updateBefore( this ) !== false ) {
  33613. renderMap.set( reference, this.renderId );
  33614. }
  33615. }
  33616. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33617. node.updateBefore( this );
  33618. }
  33619. }
  33620. /**
  33621. * This method executes the {@link Node#updateAfter} for the given node.
  33622. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  33623. * is only executed once per frame, render or object depending on the update
  33624. * type.
  33625. *
  33626. * @param {Node} node - The node that should be updated.
  33627. */
  33628. updateAfterNode( node ) {
  33629. const updateType = node.getUpdateAfterType();
  33630. const reference = node.updateReference( this );
  33631. if ( updateType === NodeUpdateType.FRAME ) {
  33632. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  33633. if ( frameMap.get( reference ) !== this.frameId ) {
  33634. if ( node.updateAfter( this ) !== false ) {
  33635. frameMap.set( reference, this.frameId );
  33636. }
  33637. }
  33638. } else if ( updateType === NodeUpdateType.RENDER ) {
  33639. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  33640. if ( renderMap.get( reference ) !== this.renderId ) {
  33641. if ( node.updateAfter( this ) !== false ) {
  33642. renderMap.set( reference, this.renderId );
  33643. }
  33644. }
  33645. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33646. node.updateAfter( this );
  33647. }
  33648. }
  33649. /**
  33650. * This method executes the {@link Node#update} for the given node.
  33651. * It makes sure {@link Node#updateType} is honored meaning the update
  33652. * is only executed once per frame, render or object depending on the update
  33653. * type.
  33654. *
  33655. * @param {Node} node - The node that should be updated.
  33656. */
  33657. updateNode( node ) {
  33658. const updateType = node.getUpdateType();
  33659. const reference = node.updateReference( this );
  33660. if ( updateType === NodeUpdateType.FRAME ) {
  33661. const { frameMap } = this._getMaps( this.updateMap, reference );
  33662. if ( frameMap.get( reference ) !== this.frameId ) {
  33663. if ( node.update( this ) !== false ) {
  33664. frameMap.set( reference, this.frameId );
  33665. }
  33666. }
  33667. } else if ( updateType === NodeUpdateType.RENDER ) {
  33668. const { renderMap } = this._getMaps( this.updateMap, reference );
  33669. if ( renderMap.get( reference ) !== this.renderId ) {
  33670. if ( node.update( this ) !== false ) {
  33671. renderMap.set( reference, this.renderId );
  33672. }
  33673. }
  33674. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33675. node.update( this );
  33676. }
  33677. }
  33678. /**
  33679. * Updates the internal state of the node frame. This method is
  33680. * called by the renderer in its internal animation loop.
  33681. */
  33682. update() {
  33683. this.frameId ++;
  33684. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  33685. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  33686. this.lastTime = performance.now();
  33687. this.time += this.deltaTime;
  33688. }
  33689. }
  33690. /**
  33691. * Describes the input of a {@link NodeFunction}.
  33692. */
  33693. class NodeFunctionInput {
  33694. /**
  33695. * Constructs a new node function input.
  33696. *
  33697. * @param {string} type - The input type.
  33698. * @param {string} name - The input name.
  33699. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  33700. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  33701. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  33702. */
  33703. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  33704. /**
  33705. * The input type.
  33706. *
  33707. * @type {string}
  33708. */
  33709. this.type = type;
  33710. /**
  33711. * The input name.
  33712. *
  33713. * @type {string}
  33714. */
  33715. this.name = name;
  33716. /**
  33717. * If the input is an Array, count will be the length.
  33718. *
  33719. * @type {?number}
  33720. * @default null
  33721. */
  33722. this.count = count;
  33723. /**
  33724. *The parameter qualifier (only relevant for GLSL).
  33725. *
  33726. * @type {('in'|'out'|'inout')}
  33727. * @default ''
  33728. */
  33729. this.qualifier = qualifier;
  33730. /**
  33731. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  33732. *
  33733. * @type {boolean}
  33734. * @default false
  33735. */
  33736. this.isConst = isConst;
  33737. }
  33738. }
  33739. NodeFunctionInput.isNodeFunctionInput = true;
  33740. /**
  33741. * Module for representing directional lights as nodes.
  33742. *
  33743. * @augments AnalyticLightNode
  33744. */
  33745. class DirectionalLightNode extends AnalyticLightNode {
  33746. static get type() {
  33747. return 'DirectionalLightNode';
  33748. }
  33749. /**
  33750. * Constructs a new directional light node.
  33751. *
  33752. * @param {?DirectionalLight} [light=null] - The directional light source.
  33753. */
  33754. constructor( light = null ) {
  33755. super( light );
  33756. }
  33757. setupDirect() {
  33758. const lightColor = this.colorNode;
  33759. const lightDirection = lightTargetDirection( this.light );
  33760. return { lightDirection, lightColor };
  33761. }
  33762. }
  33763. const _matrix41 = /*@__PURE__*/ new Matrix4();
  33764. const _matrix42 = /*@__PURE__*/ new Matrix4();
  33765. let _ltcLib = null;
  33766. /**
  33767. * Module for representing rect area lights as nodes.
  33768. *
  33769. * @augments AnalyticLightNode
  33770. */
  33771. class RectAreaLightNode extends AnalyticLightNode {
  33772. static get type() {
  33773. return 'RectAreaLightNode';
  33774. }
  33775. /**
  33776. * Constructs a new rect area light node.
  33777. *
  33778. * @param {?RectAreaLight} [light=null] - The rect area light source.
  33779. */
  33780. constructor( light = null ) {
  33781. super( light );
  33782. /**
  33783. * Uniform node representing the half height of the are light.
  33784. *
  33785. * @type {UniformNode<vec3>}
  33786. */
  33787. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  33788. /**
  33789. * Uniform node representing the half width of the are light.
  33790. *
  33791. * @type {UniformNode<vec3>}
  33792. */
  33793. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  33794. /**
  33795. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  33796. * relies on `viewMatrix` which might vary per render call.
  33797. *
  33798. * @type {string}
  33799. * @default 'render'
  33800. */
  33801. this.updateType = NodeUpdateType.RENDER;
  33802. }
  33803. /**
  33804. * Overwritten to updated rect area light specific uniforms.
  33805. *
  33806. * @param {NodeFrame} frame - A reference to the current node frame.
  33807. */
  33808. update( frame ) {
  33809. super.update( frame );
  33810. const { light } = this;
  33811. const viewMatrix = frame.camera.matrixWorldInverse;
  33812. _matrix42.identity();
  33813. _matrix41.copy( light.matrixWorld );
  33814. _matrix41.premultiply( viewMatrix );
  33815. _matrix42.extractRotation( _matrix41 );
  33816. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  33817. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  33818. this.halfWidth.value.applyMatrix4( _matrix42 );
  33819. this.halfHeight.value.applyMatrix4( _matrix42 );
  33820. }
  33821. setupDirectRectArea( builder ) {
  33822. let ltc_1, ltc_2;
  33823. if ( builder.isAvailable( 'float32Filterable' ) ) {
  33824. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  33825. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  33826. } else {
  33827. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  33828. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  33829. }
  33830. const { colorNode, light } = this;
  33831. const lightPosition = lightViewPosition( light );
  33832. return {
  33833. lightColor: colorNode,
  33834. lightPosition,
  33835. halfWidth: this.halfWidth,
  33836. halfHeight: this.halfHeight,
  33837. ltc_1,
  33838. ltc_2
  33839. };
  33840. }
  33841. /**
  33842. * Used to configure the internal BRDF approximation texture data.
  33843. *
  33844. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  33845. */
  33846. static setLTC( ltc ) {
  33847. _ltcLib = ltc;
  33848. }
  33849. }
  33850. /**
  33851. * Module for representing spot lights as nodes.
  33852. *
  33853. * @augments AnalyticLightNode
  33854. */
  33855. class SpotLightNode extends AnalyticLightNode {
  33856. static get type() {
  33857. return 'SpotLightNode';
  33858. }
  33859. /**
  33860. * Constructs a new spot light node.
  33861. *
  33862. * @param {?SpotLight} [light=null] - The spot light source.
  33863. */
  33864. constructor( light = null ) {
  33865. super( light );
  33866. /**
  33867. * Uniform node representing the cone cosine.
  33868. *
  33869. * @type {UniformNode<float>}
  33870. */
  33871. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  33872. /**
  33873. * Uniform node representing the penumbra cosine.
  33874. *
  33875. * @type {UniformNode<float>}
  33876. */
  33877. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  33878. /**
  33879. * Uniform node representing the cutoff distance.
  33880. *
  33881. * @type {UniformNode<float>}
  33882. */
  33883. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  33884. /**
  33885. * Uniform node representing the decay exponent.
  33886. *
  33887. * @type {UniformNode<float>}
  33888. */
  33889. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  33890. /**
  33891. * Uniform node representing the light color.
  33892. *
  33893. * @type {UniformNode<Color>}
  33894. */
  33895. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  33896. }
  33897. /**
  33898. * Overwritten to updated spot light specific uniforms.
  33899. *
  33900. * @param {NodeFrame} frame - A reference to the current node frame.
  33901. */
  33902. update( frame ) {
  33903. super.update( frame );
  33904. const { light } = this;
  33905. this.coneCosNode.value = Math.cos( light.angle );
  33906. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  33907. this.cutoffDistanceNode.value = light.distance;
  33908. this.decayExponentNode.value = light.decay;
  33909. }
  33910. /**
  33911. * Computes the spot attenuation for the given angle.
  33912. *
  33913. * @param {NodeBuilder} builder - The node builder.
  33914. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  33915. * @return {Node<float>} The spot attenuation.
  33916. */
  33917. getSpotAttenuation( builder, angleCosine ) {
  33918. const { coneCosNode, penumbraCosNode } = this;
  33919. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  33920. }
  33921. getLightCoord( builder ) {
  33922. const properties = builder.getNodeProperties( this );
  33923. let projectionUV = properties.projectionUV;
  33924. if ( projectionUV === undefined ) {
  33925. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  33926. properties.projectionUV = projectionUV;
  33927. }
  33928. return projectionUV;
  33929. }
  33930. setupDirect( builder ) {
  33931. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  33932. const lightVector = this.getLightVector( builder );
  33933. const lightDirection = lightVector.normalize();
  33934. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  33935. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  33936. const lightDistance = lightVector.length();
  33937. const lightAttenuation = getDistanceAttenuation( {
  33938. lightDistance,
  33939. cutoffDistance: cutoffDistanceNode,
  33940. decayExponent: decayExponentNode
  33941. } );
  33942. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  33943. let projected, lightCoord;
  33944. if ( light.colorNode ) {
  33945. lightCoord = this.getLightCoord( builder );
  33946. projected = light.colorNode( lightCoord );
  33947. } else if ( light.map ) {
  33948. lightCoord = this.getLightCoord( builder );
  33949. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  33950. }
  33951. if ( projected ) {
  33952. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  33953. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  33954. }
  33955. return { lightColor, lightDirection };
  33956. }
  33957. }
  33958. /**
  33959. * An IES version of the default spot light node.
  33960. *
  33961. * @augments SpotLightNode
  33962. */
  33963. class IESSpotLightNode extends SpotLightNode {
  33964. static get type() {
  33965. return 'IESSpotLightNode';
  33966. }
  33967. /**
  33968. * Overwrites the default implementation to compute an IES conform spot attenuation.
  33969. *
  33970. * @param {NodeBuilder} builder - The node builder.
  33971. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  33972. * @return {Node<float>} The spot attenuation.
  33973. */
  33974. getSpotAttenuation( builder, angleCosine ) {
  33975. const iesMap = this.light.iesMap;
  33976. let spotAttenuation = null;
  33977. if ( iesMap && iesMap.isTexture === true ) {
  33978. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  33979. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  33980. } else {
  33981. spotAttenuation = super.getSpotAttenuation( angleCosine );
  33982. }
  33983. return spotAttenuation;
  33984. }
  33985. }
  33986. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  33987. const d = p.abs().sub( b );
  33988. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  33989. } );
  33990. /**
  33991. * An implementation of a projector light node.
  33992. *
  33993. * @augments SpotLightNode
  33994. */
  33995. class ProjectorLightNode extends SpotLightNode {
  33996. static get type() {
  33997. return 'ProjectorLightNode';
  33998. }
  33999. update( frame ) {
  34000. super.update( frame );
  34001. const light = this.light;
  34002. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  34003. if ( light.aspect === null ) {
  34004. let aspect = 1;
  34005. if ( light.map !== null ) {
  34006. aspect = light.map.width / light.map.height;
  34007. }
  34008. light.shadow.aspect = aspect;
  34009. } else {
  34010. light.shadow.aspect = light.aspect;
  34011. }
  34012. }
  34013. /**
  34014. * Overwrites the default implementation to compute projection attenuation.
  34015. *
  34016. * @param {NodeBuilder} builder - The node builder.
  34017. * @return {Node<float>} The spot attenuation.
  34018. */
  34019. getSpotAttenuation( builder ) {
  34020. const penumbraCos = this.penumbraCosNode;
  34021. const spotLightCoord = this.getLightCoord( builder );
  34022. const coord = spotLightCoord.xyz.div( spotLightCoord.w );
  34023. const boxDist = sdBox( coord.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  34024. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  34025. const attenuation = saturate( boxDist.mul( -2 ).mul( angleFactor ) );
  34026. return attenuation;
  34027. }
  34028. }
  34029. /**
  34030. * Module for representing ambient lights as nodes.
  34031. *
  34032. * @augments AnalyticLightNode
  34033. */
  34034. class AmbientLightNode extends AnalyticLightNode {
  34035. static get type() {
  34036. return 'AmbientLightNode';
  34037. }
  34038. /**
  34039. * Constructs a new ambient light node.
  34040. *
  34041. * @param {?AmbientLight} [light=null] - The ambient light source.
  34042. */
  34043. constructor( light = null ) {
  34044. super( light );
  34045. }
  34046. setup( { context } ) {
  34047. context.irradiance.addAssign( this.colorNode );
  34048. }
  34049. }
  34050. /**
  34051. * Module for representing hemisphere lights as nodes.
  34052. *
  34053. * @augments AnalyticLightNode
  34054. */
  34055. class HemisphereLightNode extends AnalyticLightNode {
  34056. static get type() {
  34057. return 'HemisphereLightNode';
  34058. }
  34059. /**
  34060. * Constructs a new hemisphere light node.
  34061. *
  34062. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  34063. */
  34064. constructor( light = null ) {
  34065. super( light );
  34066. /**
  34067. * Uniform node representing the light's position.
  34068. *
  34069. * @type {UniformNode<vec3>}
  34070. */
  34071. this.lightPositionNode = lightPosition( light );
  34072. /**
  34073. * A node representing the light's direction.
  34074. *
  34075. * @type {Node<vec3>}
  34076. */
  34077. this.lightDirectionNode = this.lightPositionNode.normalize();
  34078. /**
  34079. * Uniform node representing the light's ground color.
  34080. *
  34081. * @type {UniformNode<vec3>}
  34082. */
  34083. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  34084. }
  34085. /**
  34086. * Overwritten to updated hemisphere light specific uniforms.
  34087. *
  34088. * @param {NodeFrame} frame - A reference to the current node frame.
  34089. */
  34090. update( frame ) {
  34091. const { light } = this;
  34092. super.update( frame );
  34093. this.lightPositionNode.object3d = light;
  34094. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  34095. }
  34096. setup( builder ) {
  34097. const { colorNode, groundColorNode, lightDirectionNode } = this;
  34098. const dotNL = normalWorld.dot( lightDirectionNode );
  34099. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  34100. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  34101. builder.context.irradiance.addAssign( irradiance );
  34102. }
  34103. }
  34104. /**
  34105. * Module for representing light probes as nodes.
  34106. *
  34107. * @augments AnalyticLightNode
  34108. */
  34109. class LightProbeNode extends AnalyticLightNode {
  34110. static get type() {
  34111. return 'LightProbeNode';
  34112. }
  34113. /**
  34114. * Constructs a new light probe node.
  34115. *
  34116. * @param {?LightProbe} [light=null] - The light probe.
  34117. */
  34118. constructor( light = null ) {
  34119. super( light );
  34120. const array = [];
  34121. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  34122. /**
  34123. * Light probe represented as a uniform of spherical harmonics.
  34124. *
  34125. * @type {UniformArrayNode}
  34126. */
  34127. this.lightProbe = uniformArray( array );
  34128. }
  34129. /**
  34130. * Overwritten to updated light probe specific uniforms.
  34131. *
  34132. * @param {NodeFrame} frame - A reference to the current node frame.
  34133. */
  34134. update( frame ) {
  34135. const { light } = this;
  34136. super.update( frame );
  34137. //
  34138. for ( let i = 0; i < 9; i ++ ) {
  34139. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  34140. }
  34141. }
  34142. setup( builder ) {
  34143. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  34144. builder.context.irradiance.addAssign( irradiance );
  34145. }
  34146. }
  34147. /**
  34148. * Base class for node parsers. A derived parser must be implemented
  34149. * for each supported native shader language.
  34150. */
  34151. class NodeParser {
  34152. /**
  34153. * The method parses the given native code an returns a node function.
  34154. *
  34155. * @abstract
  34156. * @param {string} source - The native shader code.
  34157. * @return {NodeFunction} A node function.
  34158. */
  34159. parseFunction( /*source*/ ) {
  34160. console.warn( 'Abstract function.' );
  34161. }
  34162. }
  34163. /**
  34164. * Base class for node functions. A derived module must be implemented
  34165. * for each supported native shader language. Similar to other `Node*` modules,
  34166. * this class is only relevant during the building process and not used
  34167. * in user-level code.
  34168. */
  34169. class NodeFunction {
  34170. /**
  34171. * Constructs a new node function.
  34172. *
  34173. * @param {string} type - The node type. This type is the return type of the node function.
  34174. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  34175. * @param {string} [name=''] - The function's name.
  34176. * @param {string} [precision=''] - The precision qualifier.
  34177. */
  34178. constructor( type, inputs, name = '', precision = '' ) {
  34179. /**
  34180. * The node type. This type is the return type of the node function.
  34181. *
  34182. * @type {string}
  34183. */
  34184. this.type = type;
  34185. /**
  34186. * The function's inputs.
  34187. *
  34188. * @type {Array<NodeFunctionInput>}
  34189. */
  34190. this.inputs = inputs;
  34191. /**
  34192. * The name of the uniform.
  34193. *
  34194. * @type {string}
  34195. * @default ''
  34196. */
  34197. this.name = name;
  34198. /**
  34199. * The precision qualifier.
  34200. *
  34201. * @type {string}
  34202. * @default ''
  34203. */
  34204. this.precision = precision;
  34205. }
  34206. /**
  34207. * This method returns the native code of the node function.
  34208. *
  34209. * @abstract
  34210. * @param {string} name - The function's name.
  34211. * @return {string} A shader code.
  34212. */
  34213. getCode( /*name = this.name*/ ) {
  34214. console.warn( 'Abstract function.' );
  34215. }
  34216. }
  34217. NodeFunction.isNodeFunction = true;
  34218. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  34219. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  34220. const pragmaMain = '#pragma main';
  34221. const parse$1 = ( source ) => {
  34222. source = source.trim();
  34223. const pragmaMainIndex = source.indexOf( pragmaMain );
  34224. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  34225. const declaration = mainCode.match( declarationRegexp$1 );
  34226. if ( declaration !== null && declaration.length === 5 ) {
  34227. // tokenizer
  34228. const inputsCode = declaration[ 4 ];
  34229. const propsMatches = [];
  34230. let nameMatch = null;
  34231. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  34232. propsMatches.push( nameMatch );
  34233. }
  34234. // parser
  34235. const inputs = [];
  34236. let i = 0;
  34237. while ( i < propsMatches.length ) {
  34238. const isConst = propsMatches[ i ][ 0 ] === 'const';
  34239. if ( isConst === true ) {
  34240. i ++;
  34241. }
  34242. let qualifier = propsMatches[ i ][ 0 ];
  34243. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  34244. i ++;
  34245. } else {
  34246. qualifier = '';
  34247. }
  34248. const type = propsMatches[ i ++ ][ 0 ];
  34249. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  34250. if ( Number.isNaN( count ) === false ) i ++;
  34251. else count = null;
  34252. const name = propsMatches[ i ++ ][ 0 ];
  34253. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  34254. }
  34255. //
  34256. const blockCode = mainCode.substring( declaration[ 0 ].length );
  34257. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  34258. const type = declaration[ 2 ];
  34259. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  34260. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  34261. return {
  34262. type,
  34263. inputs,
  34264. name,
  34265. precision,
  34266. inputsCode,
  34267. blockCode,
  34268. headerCode
  34269. };
  34270. } else {
  34271. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  34272. }
  34273. };
  34274. /**
  34275. * This class represents a GLSL node function.
  34276. *
  34277. * @augments NodeFunction
  34278. */
  34279. class GLSLNodeFunction extends NodeFunction {
  34280. /**
  34281. * Constructs a new GLSL node function.
  34282. *
  34283. * @param {string} source - The GLSL source.
  34284. */
  34285. constructor( source ) {
  34286. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  34287. super( type, inputs, name, precision );
  34288. this.inputsCode = inputsCode;
  34289. this.blockCode = blockCode;
  34290. this.headerCode = headerCode;
  34291. }
  34292. /**
  34293. * This method returns the GLSL code of the node function.
  34294. *
  34295. * @param {string} [name=this.name] - The function's name.
  34296. * @return {string} The shader code.
  34297. */
  34298. getCode( name = this.name ) {
  34299. let code;
  34300. const blockCode = this.blockCode;
  34301. if ( blockCode !== '' ) {
  34302. const { type, inputsCode, headerCode, precision } = this;
  34303. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  34304. if ( precision !== '' ) {
  34305. declarationCode = `${ precision } ${ declarationCode }`;
  34306. }
  34307. code = headerCode + declarationCode + blockCode;
  34308. } else {
  34309. // interface function
  34310. code = '';
  34311. }
  34312. return code;
  34313. }
  34314. }
  34315. /**
  34316. * A GLSL node parser.
  34317. *
  34318. * @augments NodeParser
  34319. */
  34320. class GLSLNodeParser extends NodeParser {
  34321. /**
  34322. * The method parses the given GLSL code an returns a node function.
  34323. *
  34324. * @param {string} source - The GLSL code.
  34325. * @return {GLSLNodeFunction} A node function.
  34326. */
  34327. parseFunction( source ) {
  34328. return new GLSLNodeFunction( source );
  34329. }
  34330. }
  34331. const _outputNodeMap = new WeakMap();
  34332. const _chainKeys$2 = [];
  34333. const _cacheKeyValues = [];
  34334. /**
  34335. * This renderer module manages node-related objects and is the
  34336. * primary interface between the renderer and the node system.
  34337. *
  34338. * @private
  34339. * @augments DataMap
  34340. */
  34341. class Nodes extends DataMap {
  34342. /**
  34343. * Constructs a new nodes management component.
  34344. *
  34345. * @param {Renderer} renderer - The renderer.
  34346. * @param {Backend} backend - The renderer's backend.
  34347. */
  34348. constructor( renderer, backend ) {
  34349. super();
  34350. /**
  34351. * The renderer.
  34352. *
  34353. * @type {Renderer}
  34354. */
  34355. this.renderer = renderer;
  34356. /**
  34357. * The renderer's backend.
  34358. *
  34359. * @type {Backend}
  34360. */
  34361. this.backend = backend;
  34362. /**
  34363. * The node frame.
  34364. *
  34365. * @type {Renderer}
  34366. */
  34367. this.nodeFrame = new NodeFrame();
  34368. /**
  34369. * A cache for managing node builder states.
  34370. *
  34371. * @type {Map<number,NodeBuilderState>}
  34372. */
  34373. this.nodeBuilderCache = new Map();
  34374. /**
  34375. * A cache for managing data cache key data.
  34376. *
  34377. * @type {ChainMap}
  34378. */
  34379. this.callHashCache = new ChainMap();
  34380. /**
  34381. * A cache for managing node uniforms group data.
  34382. *
  34383. * @type {ChainMap}
  34384. */
  34385. this.groupsData = new ChainMap();
  34386. /**
  34387. * A cache for managing node objects of
  34388. * scene properties like fog or environments.
  34389. *
  34390. * @type {Object<string,WeakMap>}
  34391. */
  34392. this.cacheLib = {};
  34393. }
  34394. /**
  34395. * Returns `true` if the given node uniforms group must be updated or not.
  34396. *
  34397. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  34398. * @return {boolean} Whether the node uniforms group requires an update or not.
  34399. */
  34400. updateGroup( nodeUniformsGroup ) {
  34401. const groupNode = nodeUniformsGroup.groupNode;
  34402. const name = groupNode.name;
  34403. // objectGroup is always updated
  34404. if ( name === objectGroup.name ) return true;
  34405. // renderGroup is updated once per render/compute call
  34406. if ( name === renderGroup.name ) {
  34407. const uniformsGroupData = this.get( nodeUniformsGroup );
  34408. const renderId = this.nodeFrame.renderId;
  34409. if ( uniformsGroupData.renderId !== renderId ) {
  34410. uniformsGroupData.renderId = renderId;
  34411. return true;
  34412. }
  34413. return false;
  34414. }
  34415. // frameGroup is updated once per frame
  34416. if ( name === frameGroup.name ) {
  34417. const uniformsGroupData = this.get( nodeUniformsGroup );
  34418. const frameId = this.nodeFrame.frameId;
  34419. if ( uniformsGroupData.frameId !== frameId ) {
  34420. uniformsGroupData.frameId = frameId;
  34421. return true;
  34422. }
  34423. return false;
  34424. }
  34425. // other groups are updated just when groupNode.needsUpdate is true
  34426. _chainKeys$2[ 0 ] = groupNode;
  34427. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  34428. let groupData = this.groupsData.get( _chainKeys$2 );
  34429. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  34430. _chainKeys$2.length = 0;
  34431. if ( groupData.version !== groupNode.version ) {
  34432. groupData.version = groupNode.version;
  34433. return true;
  34434. }
  34435. return false;
  34436. }
  34437. /**
  34438. * Returns the cache key for the given render object.
  34439. *
  34440. * @param {RenderObject} renderObject - The render object.
  34441. * @return {number} The cache key.
  34442. */
  34443. getForRenderCacheKey( renderObject ) {
  34444. return renderObject.initialCacheKey;
  34445. }
  34446. /**
  34447. * Returns a node builder state for the given render object.
  34448. *
  34449. * @param {RenderObject} renderObject - The render object.
  34450. * @return {NodeBuilderState} The node builder state.
  34451. */
  34452. getForRender( renderObject ) {
  34453. const renderObjectData = this.get( renderObject );
  34454. let nodeBuilderState = renderObjectData.nodeBuilderState;
  34455. if ( nodeBuilderState === undefined ) {
  34456. const { nodeBuilderCache } = this;
  34457. const cacheKey = this.getForRenderCacheKey( renderObject );
  34458. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  34459. if ( nodeBuilderState === undefined ) {
  34460. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  34461. nodeBuilder.scene = renderObject.scene;
  34462. nodeBuilder.material = renderObject.material;
  34463. nodeBuilder.camera = renderObject.camera;
  34464. nodeBuilder.context.material = renderObject.material;
  34465. nodeBuilder.lightsNode = renderObject.lightsNode;
  34466. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  34467. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  34468. nodeBuilder.clippingContext = renderObject.clippingContext;
  34469. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  34470. nodeBuilder.enableMultiview();
  34471. }
  34472. nodeBuilder.build();
  34473. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  34474. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  34475. }
  34476. nodeBuilderState.usedTimes ++;
  34477. renderObjectData.nodeBuilderState = nodeBuilderState;
  34478. }
  34479. return nodeBuilderState;
  34480. }
  34481. /**
  34482. * Deletes the given object from the internal data map
  34483. *
  34484. * @param {any} object - The object to delete.
  34485. * @return {?Object} The deleted dictionary.
  34486. */
  34487. delete( object ) {
  34488. if ( object.isRenderObject ) {
  34489. const nodeBuilderState = this.get( object ).nodeBuilderState;
  34490. nodeBuilderState.usedTimes --;
  34491. if ( nodeBuilderState.usedTimes === 0 ) {
  34492. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  34493. }
  34494. }
  34495. return super.delete( object );
  34496. }
  34497. /**
  34498. * Returns a node builder state for the given compute node.
  34499. *
  34500. * @param {Node} computeNode - The compute node.
  34501. * @return {NodeBuilderState} The node builder state.
  34502. */
  34503. getForCompute( computeNode ) {
  34504. const computeData = this.get( computeNode );
  34505. let nodeBuilderState = computeData.nodeBuilderState;
  34506. if ( nodeBuilderState === undefined ) {
  34507. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  34508. nodeBuilder.build();
  34509. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  34510. computeData.nodeBuilderState = nodeBuilderState;
  34511. }
  34512. return nodeBuilderState;
  34513. }
  34514. /**
  34515. * Creates a node builder state for the given node builder.
  34516. *
  34517. * @private
  34518. * @param {NodeBuilder} nodeBuilder - The node builder.
  34519. * @return {NodeBuilderState} The node builder state.
  34520. */
  34521. _createNodeBuilderState( nodeBuilder ) {
  34522. return new NodeBuilderState(
  34523. nodeBuilder.vertexShader,
  34524. nodeBuilder.fragmentShader,
  34525. nodeBuilder.computeShader,
  34526. nodeBuilder.getAttributesArray(),
  34527. nodeBuilder.getBindings(),
  34528. nodeBuilder.updateNodes,
  34529. nodeBuilder.updateBeforeNodes,
  34530. nodeBuilder.updateAfterNodes,
  34531. nodeBuilder.observer,
  34532. nodeBuilder.transforms
  34533. );
  34534. }
  34535. /**
  34536. * Returns an environment node for the current configured
  34537. * scene environment.
  34538. *
  34539. * @param {Scene} scene - The scene.
  34540. * @return {Node} A node representing the current scene environment.
  34541. */
  34542. getEnvironmentNode( scene ) {
  34543. this.updateEnvironment( scene );
  34544. let environmentNode = null;
  34545. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  34546. environmentNode = scene.environmentNode;
  34547. } else {
  34548. const sceneData = this.get( scene );
  34549. if ( sceneData.environmentNode ) {
  34550. environmentNode = sceneData.environmentNode;
  34551. }
  34552. }
  34553. return environmentNode;
  34554. }
  34555. /**
  34556. * Returns a background node for the current configured
  34557. * scene background.
  34558. *
  34559. * @param {Scene} scene - The scene.
  34560. * @return {Node} A node representing the current scene background.
  34561. */
  34562. getBackgroundNode( scene ) {
  34563. this.updateBackground( scene );
  34564. let backgroundNode = null;
  34565. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  34566. backgroundNode = scene.backgroundNode;
  34567. } else {
  34568. const sceneData = this.get( scene );
  34569. if ( sceneData.backgroundNode ) {
  34570. backgroundNode = sceneData.backgroundNode;
  34571. }
  34572. }
  34573. return backgroundNode;
  34574. }
  34575. /**
  34576. * Returns a fog node for the current configured scene fog.
  34577. *
  34578. * @param {Scene} scene - The scene.
  34579. * @return {Node} A node representing the current scene fog.
  34580. */
  34581. getFogNode( scene ) {
  34582. this.updateFog( scene );
  34583. return scene.fogNode || this.get( scene ).fogNode || null;
  34584. }
  34585. /**
  34586. * Returns a cache key for the given scene and lights node.
  34587. * This key is used by `RenderObject` as a part of the dynamic
  34588. * cache key (a key that must be checked every time the render
  34589. * objects is drawn).
  34590. *
  34591. * @param {Scene} scene - The scene.
  34592. * @param {LightsNode} lightsNode - The lights node.
  34593. * @return {number} The cache key.
  34594. */
  34595. getCacheKey( scene, lightsNode ) {
  34596. _chainKeys$2[ 0 ] = scene;
  34597. _chainKeys$2[ 1 ] = lightsNode;
  34598. const callId = this.renderer.info.calls;
  34599. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  34600. if ( cacheKeyData.callId !== callId ) {
  34601. const environmentNode = this.getEnvironmentNode( scene );
  34602. const fogNode = this.getFogNode( scene );
  34603. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  34604. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  34605. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  34606. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  34607. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  34608. cacheKeyData.callId = callId;
  34609. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  34610. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  34611. _cacheKeyValues.length = 0;
  34612. }
  34613. _chainKeys$2.length = 0;
  34614. return cacheKeyData.cacheKey;
  34615. }
  34616. /**
  34617. * A boolean that indicates whether tone mapping should be enabled
  34618. * or not.
  34619. *
  34620. * @type {boolean}
  34621. */
  34622. get isToneMappingState() {
  34623. return this.renderer.getRenderTarget() ? false : true;
  34624. }
  34625. /**
  34626. * If a scene background is configured, this method makes sure to
  34627. * represent the background with a corresponding node-based implementation.
  34628. *
  34629. * @param {Scene} scene - The scene.
  34630. */
  34631. updateBackground( scene ) {
  34632. const sceneData = this.get( scene );
  34633. const background = scene.background;
  34634. if ( background ) {
  34635. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  34636. if ( sceneData.background !== background || forceUpdate ) {
  34637. const backgroundNode = this.getCacheNode( 'background', background, () => {
  34638. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  34639. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  34640. return pmremTexture( background );
  34641. } else {
  34642. let envMap;
  34643. if ( background.isCubeTexture === true ) {
  34644. envMap = cubeTexture( background );
  34645. } else {
  34646. envMap = texture( background );
  34647. }
  34648. return cubeMapNode( envMap );
  34649. }
  34650. } else if ( background.isTexture === true ) {
  34651. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  34652. } else if ( background.isColor !== true ) {
  34653. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  34654. }
  34655. }, forceUpdate );
  34656. sceneData.backgroundNode = backgroundNode;
  34657. sceneData.background = background;
  34658. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  34659. }
  34660. } else if ( sceneData.backgroundNode ) {
  34661. delete sceneData.backgroundNode;
  34662. delete sceneData.background;
  34663. }
  34664. }
  34665. /**
  34666. * This method is part of the caching of nodes which are used to represents the
  34667. * scene's background, fog or environment.
  34668. *
  34669. * @param {string} type - The type of object to cache.
  34670. * @param {Object} object - The object.
  34671. * @param {Function} callback - A callback that produces a node representation for the given object.
  34672. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  34673. * @return {Node} The node representation.
  34674. */
  34675. getCacheNode( type, object, callback, forceUpdate = false ) {
  34676. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  34677. let node = nodeCache.get( object );
  34678. if ( node === undefined || forceUpdate ) {
  34679. node = callback();
  34680. nodeCache.set( object, node );
  34681. }
  34682. return node;
  34683. }
  34684. /**
  34685. * If a scene fog is configured, this method makes sure to
  34686. * represent the fog with a corresponding node-based implementation.
  34687. *
  34688. * @param {Scene} scene - The scene.
  34689. */
  34690. updateFog( scene ) {
  34691. const sceneData = this.get( scene );
  34692. const sceneFog = scene.fog;
  34693. if ( sceneFog ) {
  34694. if ( sceneData.fog !== sceneFog ) {
  34695. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  34696. if ( sceneFog.isFogExp2 ) {
  34697. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  34698. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  34699. return fog( color, densityFogFactor( density ) );
  34700. } else if ( sceneFog.isFog ) {
  34701. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  34702. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  34703. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  34704. return fog( color, rangeFogFactor( near, far ) );
  34705. } else {
  34706. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  34707. }
  34708. } );
  34709. sceneData.fogNode = fogNode;
  34710. sceneData.fog = sceneFog;
  34711. }
  34712. } else {
  34713. delete sceneData.fogNode;
  34714. delete sceneData.fog;
  34715. }
  34716. }
  34717. /**
  34718. * If a scene environment is configured, this method makes sure to
  34719. * represent the environment with a corresponding node-based implementation.
  34720. *
  34721. * @param {Scene} scene - The scene.
  34722. */
  34723. updateEnvironment( scene ) {
  34724. const sceneData = this.get( scene );
  34725. const environment = scene.environment;
  34726. if ( environment ) {
  34727. if ( sceneData.environment !== environment ) {
  34728. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  34729. if ( environment.isCubeTexture === true ) {
  34730. return cubeTexture( environment );
  34731. } else if ( environment.isTexture === true ) {
  34732. return texture( environment );
  34733. } else {
  34734. console.error( 'Nodes: Unsupported environment configuration.', environment );
  34735. }
  34736. } );
  34737. sceneData.environmentNode = environmentNode;
  34738. sceneData.environment = environment;
  34739. }
  34740. } else if ( sceneData.environmentNode ) {
  34741. delete sceneData.environmentNode;
  34742. delete sceneData.environment;
  34743. }
  34744. }
  34745. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  34746. const nodeFrame = this.nodeFrame;
  34747. nodeFrame.renderer = renderer;
  34748. nodeFrame.scene = scene;
  34749. nodeFrame.object = object;
  34750. nodeFrame.camera = camera;
  34751. nodeFrame.material = material;
  34752. return nodeFrame;
  34753. }
  34754. getNodeFrameForRender( renderObject ) {
  34755. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  34756. }
  34757. /**
  34758. * Returns the current output cache key.
  34759. *
  34760. * @return {string} The output cache key.
  34761. */
  34762. getOutputCacheKey() {
  34763. const renderer = this.renderer;
  34764. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  34765. }
  34766. /**
  34767. * Checks if the output configuration (tone mapping and color space) for
  34768. * the given target has changed.
  34769. *
  34770. * @param {Texture} outputTarget - The output target.
  34771. * @return {boolean} Whether the output configuration has changed or not.
  34772. */
  34773. hasOutputChange( outputTarget ) {
  34774. const cacheKey = _outputNodeMap.get( outputTarget );
  34775. return cacheKey !== this.getOutputCacheKey();
  34776. }
  34777. /**
  34778. * Returns a node that represents the output configuration (tone mapping and
  34779. * color space) for the current target.
  34780. *
  34781. * @param {Texture} outputTarget - The output target.
  34782. * @return {Node} The output node.
  34783. */
  34784. getOutputNode( outputTarget ) {
  34785. const renderer = this.renderer;
  34786. const cacheKey = this.getOutputCacheKey();
  34787. const output = outputTarget.isArrayTexture ?
  34788. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  34789. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  34790. _outputNodeMap.set( outputTarget, cacheKey );
  34791. return output;
  34792. }
  34793. /**
  34794. * Triggers the call of `updateBefore()` methods
  34795. * for all nodes of the given render object.
  34796. *
  34797. * @param {RenderObject} renderObject - The render object.
  34798. */
  34799. updateBefore( renderObject ) {
  34800. const nodeBuilder = renderObject.getNodeBuilderState();
  34801. for ( const node of nodeBuilder.updateBeforeNodes ) {
  34802. // update frame state for each node
  34803. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  34804. }
  34805. }
  34806. /**
  34807. * Triggers the call of `updateAfter()` methods
  34808. * for all nodes of the given render object.
  34809. *
  34810. * @param {RenderObject} renderObject - The render object.
  34811. */
  34812. updateAfter( renderObject ) {
  34813. const nodeBuilder = renderObject.getNodeBuilderState();
  34814. for ( const node of nodeBuilder.updateAfterNodes ) {
  34815. // update frame state for each node
  34816. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  34817. }
  34818. }
  34819. /**
  34820. * Triggers the call of `update()` methods
  34821. * for all nodes of the given compute node.
  34822. *
  34823. * @param {Node} computeNode - The compute node.
  34824. */
  34825. updateForCompute( computeNode ) {
  34826. const nodeFrame = this.getNodeFrame();
  34827. const nodeBuilder = this.getForCompute( computeNode );
  34828. for ( const node of nodeBuilder.updateNodes ) {
  34829. nodeFrame.updateNode( node );
  34830. }
  34831. }
  34832. /**
  34833. * Triggers the call of `update()` methods
  34834. * for all nodes of the given compute node.
  34835. *
  34836. * @param {RenderObject} renderObject - The render object.
  34837. */
  34838. updateForRender( renderObject ) {
  34839. const nodeFrame = this.getNodeFrameForRender( renderObject );
  34840. const nodeBuilder = renderObject.getNodeBuilderState();
  34841. for ( const node of nodeBuilder.updateNodes ) {
  34842. nodeFrame.updateNode( node );
  34843. }
  34844. }
  34845. /**
  34846. * Returns `true` if the given render object requires a refresh.
  34847. *
  34848. * @param {RenderObject} renderObject - The render object.
  34849. * @return {boolean} Whether the given render object requires a refresh or not.
  34850. */
  34851. needsRefresh( renderObject ) {
  34852. const nodeFrame = this.getNodeFrameForRender( renderObject );
  34853. const monitor = renderObject.getMonitor();
  34854. return monitor.needsRefresh( renderObject, nodeFrame );
  34855. }
  34856. /**
  34857. * Frees the internal resources.
  34858. */
  34859. dispose() {
  34860. super.dispose();
  34861. this.nodeFrame = new NodeFrame();
  34862. this.nodeBuilderCache = new Map();
  34863. this.cacheLib = {};
  34864. }
  34865. }
  34866. const _plane = /*@__PURE__*/ new Plane();
  34867. /**
  34868. * Represents the state that is used to perform clipping via clipping planes.
  34869. * There is a default clipping context for each render context. When the
  34870. * scene holds instances of `ClippingGroup`, there will be a context for each
  34871. * group.
  34872. *
  34873. * @private
  34874. */
  34875. class ClippingContext {
  34876. /**
  34877. * Constructs a new clipping context.
  34878. *
  34879. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  34880. */
  34881. constructor( parentContext = null ) {
  34882. /**
  34883. * The clipping context's version.
  34884. *
  34885. * @type {number}
  34886. * @readonly
  34887. */
  34888. this.version = 0;
  34889. /**
  34890. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  34891. *
  34892. * @type {?boolean}
  34893. * @default null
  34894. */
  34895. this.clipIntersection = null;
  34896. /**
  34897. * The clipping context's cache key.
  34898. *
  34899. * @type {string}
  34900. */
  34901. this.cacheKey = '';
  34902. /**
  34903. * Whether the shadow pass is active or not.
  34904. *
  34905. * @type {boolean}
  34906. * @default false
  34907. */
  34908. this.shadowPass = false;
  34909. /**
  34910. * The view normal matrix.
  34911. *
  34912. * @type {Matrix3}
  34913. */
  34914. this.viewNormalMatrix = new Matrix3();
  34915. /**
  34916. * Internal cache for maintaining clipping contexts.
  34917. *
  34918. * @type {WeakMap<ClippingGroup,ClippingContext>}
  34919. */
  34920. this.clippingGroupContexts = new WeakMap();
  34921. /**
  34922. * The intersection planes.
  34923. *
  34924. * @type {Array<Vector4>}
  34925. */
  34926. this.intersectionPlanes = [];
  34927. /**
  34928. * The intersection planes.
  34929. *
  34930. * @type {Array<Vector4>}
  34931. */
  34932. this.unionPlanes = [];
  34933. /**
  34934. * The version of the clipping context's parent context.
  34935. *
  34936. * @type {?number}
  34937. * @readonly
  34938. */
  34939. this.parentVersion = null;
  34940. if ( parentContext !== null ) {
  34941. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  34942. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  34943. this.shadowPass = parentContext.shadowPass;
  34944. this.viewMatrix = parentContext.viewMatrix;
  34945. }
  34946. }
  34947. /**
  34948. * Projects the given source clipping planes and writes the result into the
  34949. * destination array.
  34950. *
  34951. * @param {Array<Plane>} source - The source clipping planes.
  34952. * @param {Array<Vector4>} destination - The destination.
  34953. * @param {number} offset - The offset.
  34954. */
  34955. projectPlanes( source, destination, offset ) {
  34956. const l = source.length;
  34957. for ( let i = 0; i < l; i ++ ) {
  34958. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  34959. const v = destination[ offset + i ];
  34960. const normal = _plane.normal;
  34961. v.x = - normal.x;
  34962. v.y = - normal.y;
  34963. v.z = - normal.z;
  34964. v.w = _plane.constant;
  34965. }
  34966. }
  34967. /**
  34968. * Updates the root clipping context of a scene.
  34969. *
  34970. * @param {Scene} scene - The scene.
  34971. * @param {Camera} camera - The camera that is used to render the scene.
  34972. */
  34973. updateGlobal( scene, camera ) {
  34974. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  34975. this.viewMatrix = camera.matrixWorldInverse;
  34976. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  34977. }
  34978. /**
  34979. * Updates the clipping context.
  34980. *
  34981. * @param {ClippingContext} parentContext - The parent context.
  34982. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  34983. */
  34984. update( parentContext, clippingGroup ) {
  34985. let update = false;
  34986. if ( parentContext.version !== this.parentVersion ) {
  34987. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  34988. this.unionPlanes = Array.from( parentContext.unionPlanes );
  34989. this.parentVersion = parentContext.version;
  34990. }
  34991. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  34992. this.clipIntersection = clippingGroup.clipIntersection;
  34993. if ( this.clipIntersection ) {
  34994. this.unionPlanes.length = parentContext.unionPlanes.length;
  34995. } else {
  34996. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  34997. }
  34998. }
  34999. const srcClippingPlanes = clippingGroup.clippingPlanes;
  35000. const l = srcClippingPlanes.length;
  35001. let dstClippingPlanes;
  35002. let offset;
  35003. if ( this.clipIntersection ) {
  35004. dstClippingPlanes = this.intersectionPlanes;
  35005. offset = parentContext.intersectionPlanes.length;
  35006. } else {
  35007. dstClippingPlanes = this.unionPlanes;
  35008. offset = parentContext.unionPlanes.length;
  35009. }
  35010. if ( dstClippingPlanes.length !== offset + l ) {
  35011. dstClippingPlanes.length = offset + l;
  35012. for ( let i = 0; i < l; i ++ ) {
  35013. dstClippingPlanes[ offset + i ] = new Vector4();
  35014. }
  35015. update = true;
  35016. }
  35017. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  35018. if ( update ) {
  35019. this.version ++;
  35020. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  35021. }
  35022. }
  35023. /**
  35024. * Returns a clipping context for the given clipping group.
  35025. *
  35026. * @param {ClippingGroup} clippingGroup - The clipping group.
  35027. * @return {ClippingContext} The clipping context.
  35028. */
  35029. getGroupContext( clippingGroup ) {
  35030. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  35031. let context = this.clippingGroupContexts.get( clippingGroup );
  35032. if ( context === undefined ) {
  35033. context = new ClippingContext( this );
  35034. this.clippingGroupContexts.set( clippingGroup, context );
  35035. }
  35036. context.update( this, clippingGroup );
  35037. return context;
  35038. }
  35039. /**
  35040. * The count of union clipping planes.
  35041. *
  35042. * @type {number}
  35043. * @readonly
  35044. */
  35045. get unionClippingCount() {
  35046. return this.unionPlanes.length;
  35047. }
  35048. }
  35049. /**
  35050. * This module is used to represent render bundles inside the renderer
  35051. * for further processing.
  35052. *
  35053. * @private
  35054. */
  35055. class RenderBundle {
  35056. /**
  35057. * Constructs a new bundle group.
  35058. *
  35059. * @param {BundleGroup} bundleGroup - The bundle group.
  35060. * @param {Camera} camera - The camera the bundle group is rendered with.
  35061. */
  35062. constructor( bundleGroup, camera ) {
  35063. this.bundleGroup = bundleGroup;
  35064. this.camera = camera;
  35065. }
  35066. }
  35067. const _chainKeys$1 = [];
  35068. /**
  35069. * This renderer module manages render bundles.
  35070. *
  35071. * @private
  35072. */
  35073. class RenderBundles {
  35074. /**
  35075. * Constructs a new render bundle management component.
  35076. */
  35077. constructor() {
  35078. /**
  35079. * A chain map for maintaining the render bundles.
  35080. *
  35081. * @type {ChainMap}
  35082. */
  35083. this.bundles = new ChainMap();
  35084. }
  35085. /**
  35086. * Returns a render bundle for the given bundle group and camera.
  35087. *
  35088. * @param {BundleGroup} bundleGroup - The bundle group.
  35089. * @param {Camera} camera - The camera the bundle group is rendered with.
  35090. * @return {RenderBundle} The render bundle.
  35091. */
  35092. get( bundleGroup, camera ) {
  35093. const bundles = this.bundles;
  35094. _chainKeys$1[ 0 ] = bundleGroup;
  35095. _chainKeys$1[ 1 ] = camera;
  35096. let bundle = bundles.get( _chainKeys$1 );
  35097. if ( bundle === undefined ) {
  35098. bundle = new RenderBundle( bundleGroup, camera );
  35099. bundles.set( _chainKeys$1, bundle );
  35100. }
  35101. _chainKeys$1.length = 0;
  35102. return bundle;
  35103. }
  35104. /**
  35105. * Frees all internal resources.
  35106. */
  35107. dispose() {
  35108. this.bundles = new ChainMap();
  35109. }
  35110. }
  35111. /**
  35112. * The purpose of a node library is to assign node implementations
  35113. * to existing library features. In `WebGPURenderer` lights, materials
  35114. * which are not based on `NodeMaterial` as well as tone mapping techniques
  35115. * are implemented with node-based modules.
  35116. *
  35117. * @private
  35118. */
  35119. class NodeLibrary {
  35120. /**
  35121. * Constructs a new node library.
  35122. */
  35123. constructor() {
  35124. /**
  35125. * A weak map that maps lights to light nodes.
  35126. *
  35127. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  35128. */
  35129. this.lightNodes = new WeakMap();
  35130. /**
  35131. * A map that maps materials to node materials.
  35132. *
  35133. * @type {Map<string,NodeMaterial.constructor>}
  35134. */
  35135. this.materialNodes = new Map();
  35136. /**
  35137. * A map that maps tone mapping techniques (constants)
  35138. * to tone mapping node functions.
  35139. *
  35140. * @type {Map<number,Function>}
  35141. */
  35142. this.toneMappingNodes = new Map();
  35143. }
  35144. /**
  35145. * Returns a matching node material instance for the given material object.
  35146. *
  35147. * This method also assigns/copies the properties of the given material object
  35148. * to the node material. This is done to make sure the current material
  35149. * configuration carries over to the node version.
  35150. *
  35151. * @param {Material} material - A material.
  35152. * @return {NodeMaterial} The corresponding node material.
  35153. */
  35154. fromMaterial( material ) {
  35155. if ( material.isNodeMaterial ) return material;
  35156. let nodeMaterial = null;
  35157. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  35158. if ( nodeMaterialClass !== null ) {
  35159. nodeMaterial = new nodeMaterialClass();
  35160. for ( const key in material ) {
  35161. nodeMaterial[ key ] = material[ key ];
  35162. }
  35163. }
  35164. return nodeMaterial;
  35165. }
  35166. /**
  35167. * Adds a tone mapping node function for a tone mapping technique (constant).
  35168. *
  35169. * @param {Function} toneMappingNode - The tone mapping node function.
  35170. * @param {number} toneMapping - The tone mapping.
  35171. */
  35172. addToneMapping( toneMappingNode, toneMapping ) {
  35173. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  35174. }
  35175. /**
  35176. * Returns a tone mapping node function for a tone mapping technique (constant).
  35177. *
  35178. * @param {number} toneMapping - The tone mapping.
  35179. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  35180. */
  35181. getToneMappingFunction( toneMapping ) {
  35182. return this.toneMappingNodes.get( toneMapping ) || null;
  35183. }
  35184. /**
  35185. * Returns a node material class definition for a material type.
  35186. *
  35187. * @param {string} materialType - The material type.
  35188. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  35189. */
  35190. getMaterialNodeClass( materialType ) {
  35191. return this.materialNodes.get( materialType ) || null;
  35192. }
  35193. /**
  35194. * Adds a node material class definition for a given material type.
  35195. *
  35196. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  35197. * @param {string} materialClassType - The material type.
  35198. */
  35199. addMaterial( materialNodeClass, materialClassType ) {
  35200. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  35201. }
  35202. /**
  35203. * Returns a light node class definition for a light class definition.
  35204. *
  35205. * @param {Light.constructor} light - The light class definition.
  35206. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  35207. */
  35208. getLightNodeClass( light ) {
  35209. return this.lightNodes.get( light ) || null;
  35210. }
  35211. /**
  35212. * Adds a light node class definition for a given light class definition.
  35213. *
  35214. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  35215. * @param {Light.constructor} lightClass - The light class definition.
  35216. */
  35217. addLight( lightNodeClass, lightClass ) {
  35218. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  35219. }
  35220. /**
  35221. * Adds a node class definition for the given type to the provided type library.
  35222. *
  35223. * @param {any} nodeClass - The node class definition.
  35224. * @param {number|string} type - The object type.
  35225. * @param {Map} library - The type library.
  35226. */
  35227. addType( nodeClass, type, library ) {
  35228. if ( library.has( type ) ) {
  35229. console.warn( `Redefinition of node ${ type }` );
  35230. return;
  35231. }
  35232. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  35233. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  35234. library.set( type, nodeClass );
  35235. }
  35236. /**
  35237. * Adds a node class definition for the given class definition to the provided type library.
  35238. *
  35239. * @param {any} nodeClass - The node class definition.
  35240. * @param {any} baseClass - The class definition.
  35241. * @param {WeakMap} library - The type library.
  35242. */
  35243. addClass( nodeClass, baseClass, library ) {
  35244. if ( library.has( baseClass ) ) {
  35245. console.warn( `Redefinition of node ${ baseClass.name }` );
  35246. return;
  35247. }
  35248. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  35249. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  35250. library.set( baseClass, nodeClass );
  35251. }
  35252. }
  35253. const _defaultLights = /*@__PURE__*/ new LightsNode();
  35254. const _chainKeys = [];
  35255. /**
  35256. * This renderer module manages the lights nodes which are unique
  35257. * per scene and camera combination.
  35258. *
  35259. * The lights node itself is later configured in the render list
  35260. * with the actual lights from the scene.
  35261. *
  35262. * @private
  35263. * @augments ChainMap
  35264. */
  35265. class Lighting extends ChainMap {
  35266. /**
  35267. * Constructs a lighting management component.
  35268. */
  35269. constructor() {
  35270. super();
  35271. }
  35272. /**
  35273. * Creates a new lights node for the given array of lights.
  35274. *
  35275. * @param {Array<Light>} lights - The render object.
  35276. * @return {LightsNode} The lights node.
  35277. */
  35278. createNode( lights = [] ) {
  35279. return new LightsNode().setLights( lights );
  35280. }
  35281. /**
  35282. * Returns a lights node for the given scene and camera.
  35283. *
  35284. * @param {Scene} scene - The scene.
  35285. * @param {Camera} camera - The camera.
  35286. * @return {LightsNode} The lights node.
  35287. */
  35288. getNode( scene, camera ) {
  35289. // ignore post-processing
  35290. if ( scene.isQuadMesh ) return _defaultLights;
  35291. _chainKeys[ 0 ] = scene;
  35292. _chainKeys[ 1 ] = camera;
  35293. let node = this.get( _chainKeys );
  35294. if ( node === undefined ) {
  35295. node = this.createNode();
  35296. this.set( _chainKeys, node );
  35297. }
  35298. _chainKeys.length = 0;
  35299. return node;
  35300. }
  35301. }
  35302. /**
  35303. * A special type of render target that is used when rendering
  35304. * with the WebXR Device API.
  35305. *
  35306. * @private
  35307. * @augments RenderTarget
  35308. */
  35309. class XRRenderTarget extends RenderTarget {
  35310. /**
  35311. * Constructs a new XR render target.
  35312. *
  35313. * @param {number} [width=1] - The width of the render target.
  35314. * @param {number} [height=1] - The height of the render target.
  35315. * @param {Object} [options={}] - The configuration options.
  35316. */
  35317. constructor( width = 1, height = 1, options = {} ) {
  35318. super( width, height, options );
  35319. /**
  35320. * This flag can be used for type testing.
  35321. *
  35322. * @type {boolean}
  35323. * @readonly
  35324. * @default true
  35325. */
  35326. this.isXRRenderTarget = true;
  35327. /**
  35328. * Whether the attachments of the render target
  35329. * are defined by external textures. This flag is
  35330. * set to `true` when using the WebXR Layers API.
  35331. *
  35332. * @type {boolean}
  35333. * @default false
  35334. */
  35335. this.hasExternalTextures = false;
  35336. /**
  35337. * Whether a depth buffer should automatically be allocated
  35338. * for this XR render target or not.
  35339. *
  35340. * Allocating a depth buffer is the default behavior of XR render
  35341. * targets. However, when using the WebXR Layers API, this flag
  35342. * must be set to `false` when the `ignoreDepthValues` property of
  35343. * the projection layers evaluates to `false`.
  35344. *
  35345. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  35346. *
  35347. * @type {boolean}
  35348. * @default true
  35349. */
  35350. this.autoAllocateDepthBuffer = true;
  35351. }
  35352. copy( source ) {
  35353. super.copy( source );
  35354. this.hasExternalTextures = source.hasExternalTextures;
  35355. this.autoAllocateDepthBuffer = source.autoAllocateDepthBuffer;
  35356. return this;
  35357. }
  35358. }
  35359. const _cameraLPos = /*@__PURE__*/ new Vector3();
  35360. const _cameraRPos = /*@__PURE__*/ new Vector3();
  35361. /**
  35362. * The XR manager is built on top of the WebXR Device API to
  35363. * manage XR sessions with `WebGPURenderer`.
  35364. *
  35365. * XR is currently only supported with a WebGL 2 backend.
  35366. *
  35367. * @augments EventDispatcher
  35368. */
  35369. class XRManager extends EventDispatcher {
  35370. /**
  35371. * Constructs a new XR manager.
  35372. *
  35373. * @param {Renderer} renderer - The renderer.
  35374. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  35375. */
  35376. constructor( renderer, multiview = false ) {
  35377. super();
  35378. /**
  35379. * This flag globally enables XR rendering.
  35380. *
  35381. * @type {boolean}
  35382. * @default false
  35383. */
  35384. this.enabled = false;
  35385. /**
  35386. * Whether the XR device is currently presenting or not.
  35387. *
  35388. * @type {boolean}
  35389. * @default false
  35390. * @readonly
  35391. */
  35392. this.isPresenting = false;
  35393. /**
  35394. * Whether the XR camera should automatically be updated or not.
  35395. *
  35396. * @type {boolean}
  35397. * @default true
  35398. */
  35399. this.cameraAutoUpdate = true;
  35400. /**
  35401. * The renderer.
  35402. *
  35403. * @private
  35404. * @type {Renderer}
  35405. */
  35406. this._renderer = renderer;
  35407. // camera
  35408. /**
  35409. * Represents the camera for the left eye.
  35410. *
  35411. * @private
  35412. * @type {PerspectiveCamera}
  35413. */
  35414. this._cameraL = new PerspectiveCamera();
  35415. this._cameraL.viewport = new Vector4();
  35416. /**
  35417. * Represents the camera for the right eye.
  35418. *
  35419. * @private
  35420. * @type {PerspectiveCamera}
  35421. */
  35422. this._cameraR = new PerspectiveCamera();
  35423. this._cameraR.viewport = new Vector4();
  35424. /**
  35425. * A list of cameras used for rendering the XR views.
  35426. *
  35427. * @private
  35428. * @type {Array<Camera>}
  35429. */
  35430. this._cameras = [ this._cameraL, this._cameraR ];
  35431. /**
  35432. * The main XR camera.
  35433. *
  35434. * @private
  35435. * @type {ArrayCamera}
  35436. */
  35437. this._cameraXR = new ArrayCamera();
  35438. /**
  35439. * The current near value of the XR camera.
  35440. *
  35441. * @private
  35442. * @type {?number}
  35443. * @default null
  35444. */
  35445. this._currentDepthNear = null;
  35446. /**
  35447. * The current far value of the XR camera.
  35448. *
  35449. * @private
  35450. * @type {?number}
  35451. * @default null
  35452. */
  35453. this._currentDepthFar = null;
  35454. /**
  35455. * A list of WebXR controllers requested by the application.
  35456. *
  35457. * @private
  35458. * @type {Array<WebXRController>}
  35459. */
  35460. this._controllers = [];
  35461. /**
  35462. * A list of XR input source. Each input source belongs to
  35463. * an instance of WebXRController.
  35464. *
  35465. * @private
  35466. * @type {Array<XRInputSource?>}
  35467. */
  35468. this._controllerInputSources = [];
  35469. /**
  35470. * The XR render target that represents the rendering destination
  35471. * during an active XR session.
  35472. *
  35473. * @private
  35474. * @type {?RenderTarget}
  35475. * @default null
  35476. */
  35477. this._xrRenderTarget = null;
  35478. /**
  35479. * An array holding all the non-projection layers
  35480. *
  35481. * @private
  35482. * @type {Array<Object>}
  35483. * @default []
  35484. */
  35485. this._layers = [];
  35486. /**
  35487. * Whether the device has support for all layer types.
  35488. *
  35489. * @type {boolean}
  35490. * @default false
  35491. */
  35492. this._supportsLayers = false;
  35493. this._frameBufferTargets = null;
  35494. /**
  35495. * Helper function to create native WebXR Layer.
  35496. *
  35497. * @private
  35498. * @type {Function}
  35499. */
  35500. this._createXRLayer = createXRLayer.bind( this );
  35501. /**
  35502. * The current WebGL context.
  35503. *
  35504. * @private
  35505. * @type {?WebGL2RenderingContext}
  35506. * @default null
  35507. */
  35508. this._gl = null;
  35509. /**
  35510. * The current animation context.
  35511. *
  35512. * @private
  35513. * @type {?Window}
  35514. * @default null
  35515. */
  35516. this._currentAnimationContext = null;
  35517. /**
  35518. * The current animation loop.
  35519. *
  35520. * @private
  35521. * @type {?Function}
  35522. * @default null
  35523. */
  35524. this._currentAnimationLoop = null;
  35525. /**
  35526. * The current pixel ratio.
  35527. *
  35528. * @private
  35529. * @type {?number}
  35530. * @default null
  35531. */
  35532. this._currentPixelRatio = null;
  35533. /**
  35534. * The current size of the renderer's canvas
  35535. * in logical pixel unit.
  35536. *
  35537. * @private
  35538. * @type {Vector2}
  35539. */
  35540. this._currentSize = new Vector2();
  35541. /**
  35542. * The default event listener for handling events inside a XR session.
  35543. *
  35544. * @private
  35545. * @type {Function}
  35546. */
  35547. this._onSessionEvent = onSessionEvent.bind( this );
  35548. /**
  35549. * The event listener for handling the end of a XR session.
  35550. *
  35551. * @private
  35552. * @type {Function}
  35553. */
  35554. this._onSessionEnd = onSessionEnd.bind( this );
  35555. /**
  35556. * The event listener for handling the `inputsourceschange` event.
  35557. *
  35558. * @private
  35559. * @type {Function}
  35560. */
  35561. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  35562. /**
  35563. * The animation loop which is used as a replacement for the default
  35564. * animation loop of the application. It is only used when a XR session
  35565. * is active.
  35566. *
  35567. * @private
  35568. * @type {Function}
  35569. */
  35570. this._onAnimationFrame = onAnimationFrame.bind( this );
  35571. /**
  35572. * The current XR reference space.
  35573. *
  35574. * @private
  35575. * @type {?XRReferenceSpace}
  35576. * @default null
  35577. */
  35578. this._referenceSpace = null;
  35579. /**
  35580. * The current XR reference space type.
  35581. *
  35582. * @private
  35583. * @type {XRReferenceSpaceType}
  35584. * @default 'local-floor'
  35585. */
  35586. this._referenceSpaceType = 'local-floor';
  35587. /**
  35588. * A custom reference space defined by the application.
  35589. *
  35590. * @private
  35591. * @type {?XRReferenceSpace}
  35592. * @default null
  35593. */
  35594. this._customReferenceSpace = null;
  35595. /**
  35596. * The framebuffer scale factor.
  35597. *
  35598. * @private
  35599. * @type {number}
  35600. * @default 1
  35601. */
  35602. this._framebufferScaleFactor = 1;
  35603. /**
  35604. * The foveation factor.
  35605. *
  35606. * @private
  35607. * @type {number}
  35608. * @default 1
  35609. */
  35610. this._foveation = 1.0;
  35611. /**
  35612. * A reference to the current XR session.
  35613. *
  35614. * @private
  35615. * @type {?XRSession}
  35616. * @default null
  35617. */
  35618. this._session = null;
  35619. /**
  35620. * A reference to the current XR base layer.
  35621. *
  35622. * @private
  35623. * @type {?XRWebGLLayer}
  35624. * @default null
  35625. */
  35626. this._glBaseLayer = null;
  35627. /**
  35628. * A reference to the current XR binding.
  35629. *
  35630. * @private
  35631. * @type {?XRWebGLBinding}
  35632. * @default null
  35633. */
  35634. this._glBinding = null;
  35635. /**
  35636. * A reference to the current XR projection layer.
  35637. *
  35638. * @private
  35639. * @type {?XRProjectionLayer}
  35640. * @default null
  35641. */
  35642. this._glProjLayer = null;
  35643. /**
  35644. * A reference to the current XR frame.
  35645. *
  35646. * @private
  35647. * @type {?XRFrame}
  35648. * @default null
  35649. */
  35650. this._xrFrame = null;
  35651. /**
  35652. * Whether to use the WebXR Layers API or not.
  35653. *
  35654. * @private
  35655. * @type {boolean}
  35656. * @readonly
  35657. */
  35658. this._useLayers = ( typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  35659. /**
  35660. * Whether the usage of multiview has been requested by the application or not.
  35661. *
  35662. * @private
  35663. * @type {boolean}
  35664. * @default false
  35665. * @readonly
  35666. */
  35667. this._useMultiviewIfPossible = multiview;
  35668. /**
  35669. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  35670. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  35671. *
  35672. * @private
  35673. * @type {boolean}
  35674. * @readonly
  35675. */
  35676. this._useMultiview = false;
  35677. }
  35678. /**
  35679. * Returns an instance of `THREE.Group` that represents the transformation
  35680. * of a XR controller in target ray space. The requested controller is defined
  35681. * by the given index.
  35682. *
  35683. * @param {number} index - The index of the XR controller.
  35684. * @return {Group} A group that represents the controller's transformation.
  35685. */
  35686. getController( index ) {
  35687. const controller = this._getController( index );
  35688. return controller.getTargetRaySpace();
  35689. }
  35690. /**
  35691. * Returns an instance of `THREE.Group` that represents the transformation
  35692. * of a XR controller in grip space. The requested controller is defined
  35693. * by the given index.
  35694. *
  35695. * @param {number} index - The index of the XR controller.
  35696. * @return {Group} A group that represents the controller's transformation.
  35697. */
  35698. getControllerGrip( index ) {
  35699. const controller = this._getController( index );
  35700. return controller.getGripSpace();
  35701. }
  35702. /**
  35703. * Returns an instance of `THREE.Group` that represents the transformation
  35704. * of a XR controller in hand space. The requested controller is defined
  35705. * by the given index.
  35706. *
  35707. * @param {number} index - The index of the XR controller.
  35708. * @return {Group} A group that represents the controller's transformation.
  35709. */
  35710. getHand( index ) {
  35711. const controller = this._getController( index );
  35712. return controller.getHandSpace();
  35713. }
  35714. /**
  35715. * Returns the foveation value.
  35716. *
  35717. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  35718. */
  35719. getFoveation() {
  35720. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  35721. return undefined;
  35722. }
  35723. return this._foveation;
  35724. }
  35725. /**
  35726. * Sets the foveation value.
  35727. *
  35728. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  35729. * and `1` means maximum foveation (the edges render at lower resolution).
  35730. */
  35731. setFoveation( foveation ) {
  35732. this._foveation = foveation;
  35733. if ( this._glProjLayer !== null ) {
  35734. this._glProjLayer.fixedFoveation = foveation;
  35735. }
  35736. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  35737. this._glBaseLayer.fixedFoveation = foveation;
  35738. }
  35739. }
  35740. /**
  35741. * Returns the framebuffer scale factor.
  35742. *
  35743. * @return {number} The framebuffer scale factor.
  35744. */
  35745. getFramebufferScaleFactor() {
  35746. return this._framebufferScaleFactor;
  35747. }
  35748. /**
  35749. * Sets the framebuffer scale factor.
  35750. *
  35751. * This method can not be used during a XR session.
  35752. *
  35753. * @param {number} factor - The framebuffer scale factor.
  35754. */
  35755. setFramebufferScaleFactor( factor ) {
  35756. this._framebufferScaleFactor = factor;
  35757. if ( this.isPresenting === true ) {
  35758. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  35759. }
  35760. }
  35761. /**
  35762. * Returns the reference space type.
  35763. *
  35764. * @return {XRReferenceSpaceType} The reference space type.
  35765. */
  35766. getReferenceSpaceType() {
  35767. return this._referenceSpaceType;
  35768. }
  35769. /**
  35770. * Sets the reference space type.
  35771. *
  35772. * This method can not be used during a XR session.
  35773. *
  35774. * @param {XRReferenceSpaceType} type - The reference space type.
  35775. */
  35776. setReferenceSpaceType( type ) {
  35777. this._referenceSpaceType = type;
  35778. if ( this.isPresenting === true ) {
  35779. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  35780. }
  35781. }
  35782. /**
  35783. * Returns the XR reference space.
  35784. *
  35785. * @return {XRReferenceSpace} The XR reference space.
  35786. */
  35787. getReferenceSpace() {
  35788. return this._customReferenceSpace || this._referenceSpace;
  35789. }
  35790. /**
  35791. * Sets a custom XR reference space.
  35792. *
  35793. * @param {XRReferenceSpace} space - The XR reference space.
  35794. */
  35795. setReferenceSpace( space ) {
  35796. this._customReferenceSpace = space;
  35797. }
  35798. /**
  35799. * Returns the XR camera.
  35800. *
  35801. * @return {ArrayCamera} The XR camera.
  35802. */
  35803. getCamera() {
  35804. return this._cameraXR;
  35805. }
  35806. /**
  35807. * Returns the environment blend mode from the current XR session.
  35808. *
  35809. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  35810. */
  35811. getEnvironmentBlendMode() {
  35812. if ( this._session !== null ) {
  35813. return this._session.environmentBlendMode;
  35814. }
  35815. }
  35816. /**
  35817. * Returns the current XR frame.
  35818. *
  35819. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  35820. */
  35821. getFrame() {
  35822. return this._xrFrame;
  35823. }
  35824. /**
  35825. * Returns `true` if the engine renders to a multiview target.
  35826. *
  35827. * @return {boolean} Whether the engine renders to a multiview render target or not.
  35828. */
  35829. useMultiview() {
  35830. return this._useMultiview;
  35831. }
  35832. /**
  35833. * This method can be used in XR applications to create a quadratic layer that presents a separate
  35834. * rendered scene.
  35835. *
  35836. * @param {number} width - The width of the layer plane in world units.
  35837. * @param {number} height - The height of the layer plane in world units.
  35838. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  35839. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  35840. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  35841. * @param {number} pixelheight - The height of the layer's render target in pixels.
  35842. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  35843. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  35844. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  35845. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  35846. */
  35847. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  35848. const geometry = new PlaneGeometry( width, height );
  35849. const renderTarget = new XRRenderTarget(
  35850. pixelwidth,
  35851. pixelheight,
  35852. {
  35853. format: RGBAFormat,
  35854. type: UnsignedByteType,
  35855. depthTexture: new DepthTexture(
  35856. pixelwidth,
  35857. pixelheight,
  35858. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  35859. undefined,
  35860. undefined,
  35861. undefined,
  35862. undefined,
  35863. undefined,
  35864. undefined,
  35865. attributes.stencil ? DepthStencilFormat : DepthFormat
  35866. ),
  35867. stencilBuffer: attributes.stencil,
  35868. resolveDepthBuffer: false,
  35869. resolveStencilBuffer: false
  35870. } );
  35871. renderTarget.autoAllocateDepthBuffer = true;
  35872. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  35873. material.map = renderTarget.texture;
  35874. material.map.offset.y = 1;
  35875. material.map.repeat.y = -1;
  35876. const plane = new Mesh( geometry, material );
  35877. plane.position.copy( translation );
  35878. plane.quaternion.copy( quaternion );
  35879. const layer = {
  35880. type: 'quad',
  35881. width: width,
  35882. height: height,
  35883. translation: translation,
  35884. quaternion: quaternion,
  35885. pixelwidth: pixelwidth,
  35886. pixelheight: pixelheight,
  35887. plane: plane,
  35888. material: material,
  35889. rendercall: rendercall,
  35890. renderTarget: renderTarget };
  35891. this._layers.push( layer );
  35892. if ( this._session !== null ) {
  35893. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  35894. layer.plane.material.blending = CustomBlending;
  35895. layer.plane.material.blendEquation = AddEquation;
  35896. layer.plane.material.blendSrc = ZeroFactor;
  35897. layer.plane.material.blendDst = ZeroFactor;
  35898. layer.xrlayer = this._createXRLayer( layer );
  35899. const xrlayers = this._session.renderState.layers;
  35900. xrlayers.unshift( layer.xrlayer );
  35901. this._session.updateRenderState( { layers: xrlayers } );
  35902. } else {
  35903. renderTarget.isXRRenderTarget = false;
  35904. }
  35905. return plane;
  35906. }
  35907. /**
  35908. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  35909. * rendered scene.
  35910. *
  35911. * @param {number} radius - The radius of the cylinder in world units.
  35912. * @param {number} centralAngle - The central angle of the cylinder in radians.
  35913. * @param {number} aspectratio - The aspect ratio.
  35914. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  35915. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  35916. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  35917. * @param {number} pixelheight - The height of the layer's render target in pixels.
  35918. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  35919. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  35920. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  35921. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  35922. */
  35923. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  35924. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  35925. const renderTarget = new XRRenderTarget(
  35926. pixelwidth,
  35927. pixelheight,
  35928. {
  35929. format: RGBAFormat,
  35930. type: UnsignedByteType,
  35931. depthTexture: new DepthTexture(
  35932. pixelwidth,
  35933. pixelheight,
  35934. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  35935. undefined,
  35936. undefined,
  35937. undefined,
  35938. undefined,
  35939. undefined,
  35940. undefined,
  35941. attributes.stencil ? DepthStencilFormat : DepthFormat
  35942. ),
  35943. stencilBuffer: attributes.stencil,
  35944. resolveDepthBuffer: false,
  35945. resolveStencilBuffer: false
  35946. } );
  35947. renderTarget.autoAllocateDepthBuffer = true;
  35948. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  35949. material.map = renderTarget.texture;
  35950. material.map.offset.y = 1;
  35951. material.map.repeat.y = -1;
  35952. const plane = new Mesh( geometry, material );
  35953. plane.position.copy( translation );
  35954. plane.quaternion.copy( quaternion );
  35955. const layer = {
  35956. type: 'cylinder',
  35957. radius: radius,
  35958. centralAngle: centralAngle,
  35959. aspectratio: aspectratio,
  35960. translation: translation,
  35961. quaternion: quaternion,
  35962. pixelwidth: pixelwidth,
  35963. pixelheight: pixelheight,
  35964. plane: plane,
  35965. material: material,
  35966. rendercall: rendercall,
  35967. renderTarget: renderTarget };
  35968. this._layers.push( layer );
  35969. if ( this._session !== null ) {
  35970. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  35971. layer.plane.material.blending = CustomBlending;
  35972. layer.plane.material.blendEquation = AddEquation;
  35973. layer.plane.material.blendSrc = ZeroFactor;
  35974. layer.plane.material.blendDst = ZeroFactor;
  35975. layer.xrlayer = this._createXRLayer( layer );
  35976. const xrlayers = this._session.renderState.layers;
  35977. xrlayers.unshift( layer.xrlayer );
  35978. this._session.updateRenderState( { layers: xrlayers } );
  35979. } else {
  35980. renderTarget.isXRRenderTarget = false;
  35981. }
  35982. return plane;
  35983. }
  35984. /**
  35985. * Renders the XR layers that have been previously added to the scene.
  35986. *
  35987. * This method is usually called in your animation loop before rendering
  35988. * the actual scene via `renderer.render( scene, camera );`.
  35989. */
  35990. renderLayers( ) {
  35991. const translationObject = new Vector3();
  35992. const quaternionObject = new Quaternion();
  35993. const renderer = this._renderer;
  35994. const wasPresenting = this.isPresenting;
  35995. const rendererOutputTarget = renderer.getOutputRenderTarget();
  35996. const rendererFramebufferTarget = renderer._frameBufferTarget;
  35997. this.isPresenting = false;
  35998. const rendererSize = new Vector2();
  35999. renderer.getSize( rendererSize );
  36000. const rendererQuad = renderer._quad;
  36001. for ( const layer of this._layers ) {
  36002. layer.renderTarget.isXRRenderTarget = this._session !== null;
  36003. layer.renderTarget.hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  36004. if ( layer.renderTarget.isXRRenderTarget && this._supportsLayers ) {
  36005. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  36006. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  36007. renderer.backend.setXRRenderTargetTextures(
  36008. layer.renderTarget,
  36009. glSubImage.colorTexture,
  36010. undefined );
  36011. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  36012. renderer.setOutputRenderTarget( layer.renderTarget );
  36013. renderer.setRenderTarget( null );
  36014. renderer._frameBufferTarget = null;
  36015. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  36016. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  36017. if ( ! frameBufferTarget ) {
  36018. renderer._quad = new QuadMesh( new NodeMaterial() );
  36019. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  36020. } else {
  36021. renderer._frameBufferTarget = frameBufferTarget;
  36022. renderer._quad = quad;
  36023. }
  36024. layer.rendercall();
  36025. renderer._frameBufferTarget = null;
  36026. } else {
  36027. renderer.setRenderTarget( layer.renderTarget );
  36028. layer.rendercall();
  36029. }
  36030. }
  36031. renderer.setRenderTarget( null );
  36032. renderer.setOutputRenderTarget( rendererOutputTarget );
  36033. renderer._frameBufferTarget = rendererFramebufferTarget;
  36034. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  36035. renderer._quad = rendererQuad;
  36036. this.isPresenting = wasPresenting;
  36037. }
  36038. /**
  36039. * Returns the current XR session.
  36040. *
  36041. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  36042. */
  36043. getSession() {
  36044. return this._session;
  36045. }
  36046. /**
  36047. * After a XR session has been requested usually with one of the `*Button` modules, it
  36048. * is injected into the renderer with this method. This method triggers the start of
  36049. * the actual XR rendering.
  36050. *
  36051. * @async
  36052. * @param {XRSession} session - The XR session to set.
  36053. * @return {Promise} A Promise that resolves when the session has been set.
  36054. */
  36055. async setSession( session ) {
  36056. const renderer = this._renderer;
  36057. const backend = renderer.backend;
  36058. this._gl = renderer.getContext();
  36059. const gl = this._gl;
  36060. const attributes = gl.getContextAttributes();
  36061. this._session = session;
  36062. if ( session !== null ) {
  36063. if ( backend.isWebGPUBackend === true ) throw new Error( 'THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.' );
  36064. session.addEventListener( 'select', this._onSessionEvent );
  36065. session.addEventListener( 'selectstart', this._onSessionEvent );
  36066. session.addEventListener( 'selectend', this._onSessionEvent );
  36067. session.addEventListener( 'squeeze', this._onSessionEvent );
  36068. session.addEventListener( 'squeezestart', this._onSessionEvent );
  36069. session.addEventListener( 'squeezeend', this._onSessionEvent );
  36070. session.addEventListener( 'end', this._onSessionEnd );
  36071. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  36072. await backend.makeXRCompatible();
  36073. this._currentPixelRatio = renderer.getPixelRatio();
  36074. renderer.getSize( this._currentSize );
  36075. this._currentAnimationContext = renderer._animation.getContext();
  36076. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  36077. renderer._animation.stop();
  36078. //
  36079. if ( this._useLayers === true ) {
  36080. // default path using XRWebGLBinding/XRProjectionLayer
  36081. let depthFormat = null;
  36082. let depthType = null;
  36083. let glDepthFormat = null;
  36084. if ( renderer.depth ) {
  36085. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  36086. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  36087. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  36088. }
  36089. const projectionlayerInit = {
  36090. colorFormat: gl.RGBA8,
  36091. depthFormat: glDepthFormat,
  36092. scaleFactor: this._framebufferScaleFactor,
  36093. clearOnAccess: false
  36094. };
  36095. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  36096. projectionlayerInit.textureType = 'texture-array';
  36097. this._useMultiview = true;
  36098. }
  36099. const glBinding = new XRWebGLBinding( session, gl );
  36100. const glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  36101. const layersArray = [ glProjLayer ];
  36102. this._glBinding = glBinding;
  36103. this._glProjLayer = glProjLayer;
  36104. renderer.setPixelRatio( 1 );
  36105. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  36106. const depth = this._useMultiview ? 2 : 1;
  36107. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  36108. this._xrRenderTarget = new XRRenderTarget(
  36109. glProjLayer.textureWidth,
  36110. glProjLayer.textureHeight,
  36111. {
  36112. format: RGBAFormat,
  36113. type: UnsignedByteType,
  36114. colorSpace: renderer.outputColorSpace,
  36115. depthTexture: depthTexture,
  36116. stencilBuffer: renderer.stencil,
  36117. samples: attributes.antialias ? 4 : 0,
  36118. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  36119. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  36120. depth: this._useMultiview ? 2 : 1,
  36121. multiview: this._useMultiview
  36122. } );
  36123. this._xrRenderTarget.hasExternalTextures = true;
  36124. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  36125. this._supportsLayers = session.enabledFeatures.includes( 'layers' );
  36126. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  36127. if ( this._supportsLayers ) {
  36128. // switch layers to native
  36129. for ( const layer of this._layers ) {
  36130. // change material so it "punches" out a hole to show the XR Layer.
  36131. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  36132. layer.plane.material.blending = CustomBlending;
  36133. layer.plane.material.blendEquation = AddEquation;
  36134. layer.plane.material.blendSrc = ZeroFactor;
  36135. layer.plane.material.blendDst = ZeroFactor;
  36136. layer.xrlayer = this._createXRLayer( layer );
  36137. layersArray.unshift( layer.xrlayer );
  36138. }
  36139. }
  36140. session.updateRenderState( { layers: layersArray } );
  36141. } else {
  36142. // fallback to XRWebGLLayer
  36143. const layerInit = {
  36144. antialias: renderer.samples > 0,
  36145. alpha: true,
  36146. depth: renderer.depth,
  36147. stencil: renderer.stencil,
  36148. framebufferScaleFactor: this.getFramebufferScaleFactor()
  36149. };
  36150. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  36151. this._glBaseLayer = glBaseLayer;
  36152. session.updateRenderState( { baseLayer: glBaseLayer } );
  36153. renderer.setPixelRatio( 1 );
  36154. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  36155. this._xrRenderTarget = new XRRenderTarget(
  36156. glBaseLayer.framebufferWidth,
  36157. glBaseLayer.framebufferHeight,
  36158. {
  36159. format: RGBAFormat,
  36160. type: UnsignedByteType,
  36161. colorSpace: renderer.outputColorSpace,
  36162. stencilBuffer: renderer.stencil,
  36163. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  36164. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  36165. }
  36166. );
  36167. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  36168. }
  36169. //
  36170. this.setFoveation( this.getFoveation() );
  36171. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  36172. renderer._animation.setContext( session );
  36173. renderer._animation.start();
  36174. this.isPresenting = true;
  36175. this.dispatchEvent( { type: 'sessionstart' } );
  36176. }
  36177. }
  36178. /**
  36179. * This method is called by the renderer per frame and updates the XR camera
  36180. * and it sub cameras based on the given camera. The given camera is the "user"
  36181. * camera created on application level and used for non-XR rendering.
  36182. *
  36183. * @param {PerspectiveCamera} camera - The camera.
  36184. */
  36185. updateCamera( camera ) {
  36186. const session = this._session;
  36187. if ( session === null ) return;
  36188. const depthNear = camera.near;
  36189. const depthFar = camera.far;
  36190. const cameraXR = this._cameraXR;
  36191. const cameraL = this._cameraL;
  36192. const cameraR = this._cameraR;
  36193. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  36194. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  36195. cameraXR.isMultiViewCamera = this._useMultiview;
  36196. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  36197. // Note that the new renderState won't apply until the next frame. See #18320
  36198. session.updateRenderState( {
  36199. depthNear: cameraXR.near,
  36200. depthFar: cameraXR.far
  36201. } );
  36202. this._currentDepthNear = cameraXR.near;
  36203. this._currentDepthFar = cameraXR.far;
  36204. }
  36205. cameraL.layers.mask = camera.layers.mask | 0b010;
  36206. cameraR.layers.mask = camera.layers.mask | 0b100;
  36207. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  36208. const parent = camera.parent;
  36209. const cameras = cameraXR.cameras;
  36210. updateCamera( cameraXR, parent );
  36211. for ( let i = 0; i < cameras.length; i ++ ) {
  36212. updateCamera( cameras[ i ], parent );
  36213. }
  36214. // update projection matrix for proper view frustum culling
  36215. if ( cameras.length === 2 ) {
  36216. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  36217. } else {
  36218. // assume single camera setup (AR)
  36219. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  36220. }
  36221. // update user camera and its children
  36222. updateUserCamera( camera, cameraXR, parent );
  36223. }
  36224. /**
  36225. * Returns a WebXR controller for the given controller index.
  36226. *
  36227. * @private
  36228. * @param {number} index - The controller index.
  36229. * @return {WebXRController} The XR controller.
  36230. */
  36231. _getController( index ) {
  36232. let controller = this._controllers[ index ];
  36233. if ( controller === undefined ) {
  36234. controller = new WebXRController();
  36235. this._controllers[ index ] = controller;
  36236. }
  36237. return controller;
  36238. }
  36239. }
  36240. /**
  36241. * Assumes 2 cameras that are parallel and share an X-axis, and that
  36242. * the cameras' projection and world matrices have already been set.
  36243. * And that near and far planes are identical for both cameras.
  36244. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  36245. *
  36246. * @param {ArrayCamera} camera - The camera to update.
  36247. * @param {PerspectiveCamera} cameraL - The left camera.
  36248. * @param {PerspectiveCamera} cameraR - The right camera.
  36249. */
  36250. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  36251. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  36252. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  36253. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  36254. const projL = cameraL.projectionMatrix.elements;
  36255. const projR = cameraR.projectionMatrix.elements;
  36256. // VR systems will have identical far and near planes, and
  36257. // most likely identical top and bottom frustum extents.
  36258. // Use the left camera for these values.
  36259. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  36260. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  36261. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  36262. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  36263. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  36264. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  36265. const left = near * leftFov;
  36266. const right = near * rightFov;
  36267. // Calculate the new camera's position offset from the
  36268. // left camera. xOffset should be roughly half `ipd`.
  36269. const zOffset = ipd / ( - leftFov + rightFov );
  36270. const xOffset = zOffset * - leftFov;
  36271. // TODO: Better way to apply this offset?
  36272. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  36273. camera.translateX( xOffset );
  36274. camera.translateZ( zOffset );
  36275. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  36276. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  36277. // Check if the projection uses an infinite far plane.
  36278. if ( projL[ 10 ] === -1 ) {
  36279. // Use the projection matrix from the left eye.
  36280. // The camera offset is sufficient to include the view volumes
  36281. // of both eyes (assuming symmetric projections).
  36282. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  36283. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  36284. } else {
  36285. // Find the union of the frustum values of the cameras and scale
  36286. // the values so that the near plane's position does not change in world space,
  36287. // although must now be relative to the new union camera.
  36288. const near2 = near + zOffset;
  36289. const far2 = far + zOffset;
  36290. const left2 = left - xOffset;
  36291. const right2 = right + ( ipd - xOffset );
  36292. const top2 = topFov * far / far2 * near2;
  36293. const bottom2 = bottomFov * far / far2 * near2;
  36294. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  36295. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  36296. }
  36297. }
  36298. /**
  36299. * Updates the world matrices for the given camera based on the parent 3D object.
  36300. *
  36301. * @inner
  36302. * @param {Camera} camera - The camera to update.
  36303. * @param {Object3D} parent - The parent 3D object.
  36304. */
  36305. function updateCamera( camera, parent ) {
  36306. if ( parent === null ) {
  36307. camera.matrixWorld.copy( camera.matrix );
  36308. } else {
  36309. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  36310. }
  36311. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  36312. }
  36313. /**
  36314. * Updates the given camera with the transformation of the XR camera and parent object.
  36315. *
  36316. * @inner
  36317. * @param {Camera} camera - The camera to update.
  36318. * @param {ArrayCamera} cameraXR - The XR camera.
  36319. * @param {Object3D} parent - The parent 3D object.
  36320. */
  36321. function updateUserCamera( camera, cameraXR, parent ) {
  36322. if ( parent === null ) {
  36323. camera.matrix.copy( cameraXR.matrixWorld );
  36324. } else {
  36325. camera.matrix.copy( parent.matrixWorld );
  36326. camera.matrix.invert();
  36327. camera.matrix.multiply( cameraXR.matrixWorld );
  36328. }
  36329. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  36330. camera.updateMatrixWorld( true );
  36331. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  36332. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  36333. if ( camera.isPerspectiveCamera ) {
  36334. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  36335. camera.zoom = 1;
  36336. }
  36337. }
  36338. function onSessionEvent( event ) {
  36339. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  36340. if ( controllerIndex === -1 ) {
  36341. return;
  36342. }
  36343. const controller = this._controllers[ controllerIndex ];
  36344. if ( controller !== undefined ) {
  36345. const referenceSpace = this.getReferenceSpace();
  36346. controller.update( event.inputSource, event.frame, referenceSpace );
  36347. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  36348. }
  36349. }
  36350. function onSessionEnd() {
  36351. const session = this._session;
  36352. const renderer = this._renderer;
  36353. session.removeEventListener( 'select', this._onSessionEvent );
  36354. session.removeEventListener( 'selectstart', this._onSessionEvent );
  36355. session.removeEventListener( 'selectend', this._onSessionEvent );
  36356. session.removeEventListener( 'squeeze', this._onSessionEvent );
  36357. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  36358. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  36359. session.removeEventListener( 'end', this._onSessionEnd );
  36360. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  36361. for ( let i = 0; i < this._controllers.length; i ++ ) {
  36362. const inputSource = this._controllerInputSources[ i ];
  36363. if ( inputSource === null ) continue;
  36364. this._controllerInputSources[ i ] = null;
  36365. this._controllers[ i ].disconnect( inputSource );
  36366. }
  36367. this._currentDepthNear = null;
  36368. this._currentDepthFar = null;
  36369. // restore framebuffer/rendering state
  36370. renderer._resetXRState();
  36371. this._session = null;
  36372. this._xrRenderTarget = null;
  36373. // switch layers back to emulated
  36374. if ( this._supportsLayers === true ) {
  36375. for ( const layer of this._layers ) {
  36376. // Recreate layer render target to reset state
  36377. layer.renderTarget = new XRRenderTarget(
  36378. layer.pixelwidth,
  36379. layer.pixelheight,
  36380. {
  36381. format: RGBAFormat,
  36382. type: UnsignedByteType,
  36383. depthTexture: new DepthTexture(
  36384. layer.pixelwidth,
  36385. layer.pixelheight,
  36386. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  36387. undefined,
  36388. undefined,
  36389. undefined,
  36390. undefined,
  36391. undefined,
  36392. undefined,
  36393. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  36394. ),
  36395. stencilBuffer: layer.stencilBuffer,
  36396. resolveDepthBuffer: false,
  36397. resolveStencilBuffer: false
  36398. } );
  36399. layer.renderTarget.isXRRenderTarget = false;
  36400. layer.plane.material = layer.material;
  36401. layer.material.map = layer.renderTarget.texture;
  36402. layer.material.map.offset.y = 1;
  36403. layer.material.map.repeat.y = -1;
  36404. delete layer.xrlayer;
  36405. }
  36406. }
  36407. //
  36408. this.isPresenting = false;
  36409. this._useMultiview = false;
  36410. renderer._animation.stop();
  36411. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  36412. renderer._animation.setContext( this._currentAnimationContext );
  36413. renderer._animation.start();
  36414. renderer.setPixelRatio( this._currentPixelRatio );
  36415. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  36416. this.dispatchEvent( { type: 'sessionend' } );
  36417. }
  36418. function onInputSourcesChange( event ) {
  36419. const controllers = this._controllers;
  36420. const controllerInputSources = this._controllerInputSources;
  36421. // Notify disconnected
  36422. for ( let i = 0; i < event.removed.length; i ++ ) {
  36423. const inputSource = event.removed[ i ];
  36424. const index = controllerInputSources.indexOf( inputSource );
  36425. if ( index >= 0 ) {
  36426. controllerInputSources[ index ] = null;
  36427. controllers[ index ].disconnect( inputSource );
  36428. }
  36429. }
  36430. // Notify connected
  36431. for ( let i = 0; i < event.added.length; i ++ ) {
  36432. const inputSource = event.added[ i ];
  36433. let controllerIndex = controllerInputSources.indexOf( inputSource );
  36434. if ( controllerIndex === -1 ) {
  36435. // Assign input source a controller that currently has no input source
  36436. for ( let i = 0; i < controllers.length; i ++ ) {
  36437. if ( i >= controllerInputSources.length ) {
  36438. controllerInputSources.push( inputSource );
  36439. controllerIndex = i;
  36440. break;
  36441. } else if ( controllerInputSources[ i ] === null ) {
  36442. controllerInputSources[ i ] = inputSource;
  36443. controllerIndex = i;
  36444. break;
  36445. }
  36446. }
  36447. // If all controllers do currently receive input we ignore new ones
  36448. if ( controllerIndex === -1 ) break;
  36449. }
  36450. const controller = controllers[ controllerIndex ];
  36451. if ( controller ) {
  36452. controller.connect( inputSource );
  36453. }
  36454. }
  36455. }
  36456. // Creation method for native WebXR layers
  36457. function createXRLayer( layer ) {
  36458. if ( layer.type === 'quad' ) {
  36459. return this._glBinding.createQuadLayer( {
  36460. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  36461. width: layer.width / 2,
  36462. height: layer.height / 2,
  36463. space: this._referenceSpace,
  36464. viewPixelWidth: layer.pixelwidth,
  36465. viewPixelHeight: layer.pixelheight,
  36466. clearOnAccess: false
  36467. } );
  36468. } else {
  36469. return this._glBinding.createCylinderLayer( {
  36470. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  36471. radius: layer.radius,
  36472. centralAngle: layer.centralAngle,
  36473. aspectRatio: layer.aspectRatio,
  36474. space: this._referenceSpace,
  36475. viewPixelWidth: layer.pixelwidth,
  36476. viewPixelHeight: layer.pixelheight,
  36477. clearOnAccess: false
  36478. } );
  36479. }
  36480. }
  36481. // Animation Loop
  36482. function onAnimationFrame( time, frame ) {
  36483. if ( frame === undefined ) return;
  36484. const cameraXR = this._cameraXR;
  36485. const renderer = this._renderer;
  36486. const backend = renderer.backend;
  36487. const glBaseLayer = this._glBaseLayer;
  36488. const referenceSpace = this.getReferenceSpace();
  36489. const pose = frame.getViewerPose( referenceSpace );
  36490. this._xrFrame = frame;
  36491. if ( pose !== null ) {
  36492. const views = pose.views;
  36493. if ( this._glBaseLayer !== null ) {
  36494. backend.setXRTarget( glBaseLayer.framebuffer );
  36495. }
  36496. let cameraXRNeedsUpdate = false;
  36497. // check if it's necessary to rebuild cameraXR's camera list
  36498. if ( views.length !== cameraXR.cameras.length ) {
  36499. cameraXR.cameras.length = 0;
  36500. cameraXRNeedsUpdate = true;
  36501. }
  36502. for ( let i = 0; i < views.length; i ++ ) {
  36503. const view = views[ i ];
  36504. let viewport;
  36505. if ( this._useLayers === true ) {
  36506. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  36507. viewport = glSubImage.viewport;
  36508. // For side-by-side projection, we only produce a single texture for both eyes.
  36509. if ( i === 0 ) {
  36510. backend.setXRRenderTargetTextures(
  36511. this._xrRenderTarget,
  36512. glSubImage.colorTexture,
  36513. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  36514. );
  36515. }
  36516. } else {
  36517. viewport = glBaseLayer.getViewport( view );
  36518. }
  36519. let camera = this._cameras[ i ];
  36520. if ( camera === undefined ) {
  36521. camera = new PerspectiveCamera();
  36522. camera.layers.enable( i );
  36523. camera.viewport = new Vector4();
  36524. this._cameras[ i ] = camera;
  36525. }
  36526. camera.matrix.fromArray( view.transform.matrix );
  36527. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  36528. camera.projectionMatrix.fromArray( view.projectionMatrix );
  36529. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  36530. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  36531. if ( i === 0 ) {
  36532. cameraXR.matrix.copy( camera.matrix );
  36533. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  36534. }
  36535. if ( cameraXRNeedsUpdate === true ) {
  36536. cameraXR.cameras.push( camera );
  36537. }
  36538. }
  36539. renderer.setOutputRenderTarget( this._xrRenderTarget );
  36540. }
  36541. //
  36542. for ( let i = 0; i < this._controllers.length; i ++ ) {
  36543. const inputSource = this._controllerInputSources[ i ];
  36544. const controller = this._controllers[ i ];
  36545. if ( inputSource !== null && controller !== undefined ) {
  36546. controller.update( inputSource, frame, referenceSpace );
  36547. }
  36548. }
  36549. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  36550. if ( frame.detectedPlanes ) {
  36551. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  36552. }
  36553. this._xrFrame = null;
  36554. }
  36555. const _scene = /*@__PURE__*/ new Scene();
  36556. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  36557. const _screen = /*@__PURE__*/ new Vector4();
  36558. const _frustum = /*@__PURE__*/ new Frustum();
  36559. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  36560. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  36561. const _vector4 = /*@__PURE__*/ new Vector4();
  36562. /**
  36563. * Base class for renderers.
  36564. */
  36565. class Renderer {
  36566. /**
  36567. * Renderer options.
  36568. *
  36569. * @typedef {Object} Renderer~Options
  36570. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  36571. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  36572. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  36573. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  36574. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  36575. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  36576. * to overwrite the default.
  36577. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  36578. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  36579. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  36580. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  36581. */
  36582. /**
  36583. * Constructs a new renderer.
  36584. *
  36585. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  36586. * @param {Renderer~Options} [parameters] - The configuration parameter.
  36587. */
  36588. constructor( backend, parameters = {} ) {
  36589. /**
  36590. * This flag can be used for type testing.
  36591. *
  36592. * @type {boolean}
  36593. * @readonly
  36594. * @default true
  36595. */
  36596. this.isRenderer = true;
  36597. //
  36598. const {
  36599. logarithmicDepthBuffer = false,
  36600. alpha = true,
  36601. depth = true,
  36602. stencil = false,
  36603. antialias = false,
  36604. samples = 0,
  36605. getFallback = null,
  36606. colorBufferType = HalfFloatType,
  36607. multiview = false
  36608. } = parameters;
  36609. /**
  36610. * A reference to the canvas element the renderer is drawing to.
  36611. * This value of this property will automatically be created by
  36612. * the renderer.
  36613. *
  36614. * @type {HTMLCanvasElement|OffscreenCanvas}
  36615. */
  36616. this.domElement = backend.getDomElement();
  36617. /**
  36618. * A reference to the current backend.
  36619. *
  36620. * @type {Backend}
  36621. */
  36622. this.backend = backend;
  36623. /**
  36624. * The number of MSAA samples.
  36625. *
  36626. * @type {number}
  36627. * @default 0
  36628. */
  36629. this.samples = samples || ( antialias === true ) ? 4 : 0;
  36630. /**
  36631. * Whether the renderer should automatically clear the current rendering target
  36632. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  36633. * or the current bound render target (custom framebuffer).
  36634. *
  36635. * @type {boolean}
  36636. * @default true
  36637. */
  36638. this.autoClear = true;
  36639. /**
  36640. * When `autoClear` is set to `true`, this property defines whether the renderer
  36641. * should clear the color buffer.
  36642. *
  36643. * @type {boolean}
  36644. * @default true
  36645. */
  36646. this.autoClearColor = true;
  36647. /**
  36648. * When `autoClear` is set to `true`, this property defines whether the renderer
  36649. * should clear the depth buffer.
  36650. *
  36651. * @type {boolean}
  36652. * @default true
  36653. */
  36654. this.autoClearDepth = true;
  36655. /**
  36656. * When `autoClear` is set to `true`, this property defines whether the renderer
  36657. * should clear the stencil buffer.
  36658. *
  36659. * @type {boolean}
  36660. * @default true
  36661. */
  36662. this.autoClearStencil = true;
  36663. /**
  36664. * Whether the default framebuffer should be transparent or opaque.
  36665. *
  36666. * @type {boolean}
  36667. * @default true
  36668. */
  36669. this.alpha = alpha;
  36670. /**
  36671. * Whether logarithmic depth buffer is enabled or not.
  36672. *
  36673. * @type {boolean}
  36674. * @default false
  36675. */
  36676. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  36677. /**
  36678. * Defines the output color space of the renderer.
  36679. *
  36680. * @type {string}
  36681. * @default SRGBColorSpace
  36682. */
  36683. this.outputColorSpace = SRGBColorSpace;
  36684. /**
  36685. * Defines the tone mapping of the renderer.
  36686. *
  36687. * @type {number}
  36688. * @default NoToneMapping
  36689. */
  36690. this.toneMapping = NoToneMapping;
  36691. /**
  36692. * Defines the tone mapping exposure.
  36693. *
  36694. * @type {number}
  36695. * @default 1
  36696. */
  36697. this.toneMappingExposure = 1.0;
  36698. /**
  36699. * Whether the renderer should sort its render lists or not.
  36700. *
  36701. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  36702. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  36703. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  36704. * e.g. manually determining each object's rendering order.
  36705. *
  36706. * @type {boolean}
  36707. * @default true
  36708. */
  36709. this.sortObjects = true;
  36710. /**
  36711. * Whether the default framebuffer should have a depth buffer or not.
  36712. *
  36713. * @type {boolean}
  36714. * @default true
  36715. */
  36716. this.depth = depth;
  36717. /**
  36718. * Whether the default framebuffer should have a stencil buffer or not.
  36719. *
  36720. * @type {boolean}
  36721. * @default false
  36722. */
  36723. this.stencil = stencil;
  36724. /**
  36725. * Holds a series of statistical information about the GPU memory
  36726. * and the rendering process. Useful for debugging and monitoring.
  36727. *
  36728. * @type {Info}
  36729. */
  36730. this.info = new Info();
  36731. /**
  36732. * Stores override nodes for specific transformations or calculations.
  36733. * These nodes can be used to replace default behavior in the rendering pipeline.
  36734. *
  36735. * @type {Object}
  36736. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  36737. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  36738. */
  36739. this.overrideNodes = {
  36740. modelViewMatrix: null,
  36741. modelNormalViewMatrix: null
  36742. };
  36743. /**
  36744. * The node library defines how certain library objects like materials, lights
  36745. * or tone mapping functions are mapped to node types. This is required since
  36746. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  36747. * be part of the scene graph, they are internally represented as nodes for
  36748. * further processing.
  36749. *
  36750. * @type {NodeLibrary}
  36751. */
  36752. this.library = new NodeLibrary();
  36753. /**
  36754. * A map-like data structure for managing lights.
  36755. *
  36756. * @type {Lighting}
  36757. */
  36758. this.lighting = new Lighting();
  36759. // internals
  36760. /**
  36761. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  36762. *
  36763. * @private
  36764. * @type {?Function}
  36765. */
  36766. this._getFallback = getFallback;
  36767. /**
  36768. * The renderer's pixel ratio.
  36769. *
  36770. * @private
  36771. * @type {number}
  36772. * @default 1
  36773. */
  36774. this._pixelRatio = 1;
  36775. /**
  36776. * The width of the renderer's default framebuffer in logical pixel unit.
  36777. *
  36778. * @private
  36779. * @type {number}
  36780. */
  36781. this._width = this.domElement.width;
  36782. /**
  36783. * The height of the renderer's default framebuffer in logical pixel unit.
  36784. *
  36785. * @private
  36786. * @type {number}
  36787. */
  36788. this._height = this.domElement.height;
  36789. /**
  36790. * The viewport of the renderer in logical pixel unit.
  36791. *
  36792. * @private
  36793. * @type {Vector4}
  36794. */
  36795. this._viewport = new Vector4( 0, 0, this._width, this._height );
  36796. /**
  36797. * The scissor rectangle of the renderer in logical pixel unit.
  36798. *
  36799. * @private
  36800. * @type {Vector4}
  36801. */
  36802. this._scissor = new Vector4( 0, 0, this._width, this._height );
  36803. this._forceViewport = false;
  36804. /**
  36805. * Whether the scissor test should be enabled or not.
  36806. *
  36807. * @private
  36808. * @type {boolean}
  36809. */
  36810. this._scissorTest = false;
  36811. /**
  36812. * A reference to a renderer module for managing shader attributes.
  36813. *
  36814. * @private
  36815. * @type {?Attributes}
  36816. * @default null
  36817. */
  36818. this._attributes = null;
  36819. /**
  36820. * A reference to a renderer module for managing geometries.
  36821. *
  36822. * @private
  36823. * @type {?Geometries}
  36824. * @default null
  36825. */
  36826. this._geometries = null;
  36827. /**
  36828. * A reference to a renderer module for managing node related logic.
  36829. *
  36830. * @private
  36831. * @type {?Nodes}
  36832. * @default null
  36833. */
  36834. this._nodes = null;
  36835. /**
  36836. * A reference to a renderer module for managing the internal animation loop.
  36837. *
  36838. * @private
  36839. * @type {?Animation}
  36840. * @default null
  36841. */
  36842. this._animation = null;
  36843. /**
  36844. * A reference to a renderer module for managing shader program bindings.
  36845. *
  36846. * @private
  36847. * @type {?Bindings}
  36848. * @default null
  36849. */
  36850. this._bindings = null;
  36851. /**
  36852. * A reference to a renderer module for managing render objects.
  36853. *
  36854. * @private
  36855. * @type {?RenderObjects}
  36856. * @default null
  36857. */
  36858. this._objects = null;
  36859. /**
  36860. * A reference to a renderer module for managing render and compute pipelines.
  36861. *
  36862. * @private
  36863. * @type {?Pipelines}
  36864. * @default null
  36865. */
  36866. this._pipelines = null;
  36867. /**
  36868. * A reference to a renderer module for managing render bundles.
  36869. *
  36870. * @private
  36871. * @type {?RenderBundles}
  36872. * @default null
  36873. */
  36874. this._bundles = null;
  36875. /**
  36876. * A reference to a renderer module for managing render lists.
  36877. *
  36878. * @private
  36879. * @type {?RenderLists}
  36880. * @default null
  36881. */
  36882. this._renderLists = null;
  36883. /**
  36884. * A reference to a renderer module for managing render contexts.
  36885. *
  36886. * @private
  36887. * @type {?RenderContexts}
  36888. * @default null
  36889. */
  36890. this._renderContexts = null;
  36891. /**
  36892. * A reference to a renderer module for managing textures.
  36893. *
  36894. * @private
  36895. * @type {?Textures}
  36896. * @default null
  36897. */
  36898. this._textures = null;
  36899. /**
  36900. * A reference to a renderer module for backgrounds.
  36901. *
  36902. * @private
  36903. * @type {?Background}
  36904. * @default null
  36905. */
  36906. this._background = null;
  36907. /**
  36908. * This fullscreen quad is used for internal render passes
  36909. * like the tone mapping and color space output pass.
  36910. *
  36911. * @private
  36912. * @type {QuadMesh}
  36913. */
  36914. this._quad = new QuadMesh( new NodeMaterial() );
  36915. this._quad.material.name = 'Renderer_output';
  36916. /**
  36917. * A reference to the current render context.
  36918. *
  36919. * @private
  36920. * @type {?RenderContext}
  36921. * @default null
  36922. */
  36923. this._currentRenderContext = null;
  36924. /**
  36925. * A custom sort function for the opaque render list.
  36926. *
  36927. * @private
  36928. * @type {?Function}
  36929. * @default null
  36930. */
  36931. this._opaqueSort = null;
  36932. /**
  36933. * A custom sort function for the transparent render list.
  36934. *
  36935. * @private
  36936. * @type {?Function}
  36937. * @default null
  36938. */
  36939. this._transparentSort = null;
  36940. /**
  36941. * The framebuffer target.
  36942. *
  36943. * @private
  36944. * @type {?RenderTarget}
  36945. * @default null
  36946. */
  36947. this._frameBufferTarget = null;
  36948. const alphaClear = this.alpha === true ? 0 : 1;
  36949. /**
  36950. * The clear color value.
  36951. *
  36952. * @private
  36953. * @type {Color4}
  36954. */
  36955. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  36956. /**
  36957. * The clear depth value.
  36958. *
  36959. * @private
  36960. * @type {number}
  36961. * @default 1
  36962. */
  36963. this._clearDepth = 1;
  36964. /**
  36965. * The clear stencil value.
  36966. *
  36967. * @private
  36968. * @type {number}
  36969. * @default 0
  36970. */
  36971. this._clearStencil = 0;
  36972. /**
  36973. * The current render target.
  36974. *
  36975. * @private
  36976. * @type {?RenderTarget}
  36977. * @default null
  36978. */
  36979. this._renderTarget = null;
  36980. /**
  36981. * The active cube face.
  36982. *
  36983. * @private
  36984. * @type {number}
  36985. * @default 0
  36986. */
  36987. this._activeCubeFace = 0;
  36988. /**
  36989. * The active mipmap level.
  36990. *
  36991. * @private
  36992. * @type {number}
  36993. * @default 0
  36994. */
  36995. this._activeMipmapLevel = 0;
  36996. /**
  36997. * The current output render target.
  36998. *
  36999. * @private
  37000. * @type {?RenderTarget}
  37001. * @default null
  37002. */
  37003. this._outputRenderTarget = null;
  37004. /**
  37005. * The MRT setting.
  37006. *
  37007. * @private
  37008. * @type {?MRTNode}
  37009. * @default null
  37010. */
  37011. this._mrt = null;
  37012. /**
  37013. * This function defines how a render object is going
  37014. * to be rendered.
  37015. *
  37016. * @private
  37017. * @type {?Function}
  37018. * @default null
  37019. */
  37020. this._renderObjectFunction = null;
  37021. /**
  37022. * Used to keep track of the current render object function.
  37023. *
  37024. * @private
  37025. * @type {?Function}
  37026. * @default null
  37027. */
  37028. this._currentRenderObjectFunction = null;
  37029. /**
  37030. * Used to keep track of the current render bundle.
  37031. *
  37032. * @private
  37033. * @type {?RenderBundle}
  37034. * @default null
  37035. */
  37036. this._currentRenderBundle = null;
  37037. /**
  37038. * Next to `_renderObjectFunction()`, this function provides another hook
  37039. * for influencing the render process of a render object. It is meant for internal
  37040. * use and only relevant for `compileAsync()` right now. Instead of using
  37041. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  37042. * a different function might be used which performs no draw but just the node
  37043. * and pipeline updates.
  37044. *
  37045. * @private
  37046. * @type {?Function}
  37047. * @default null
  37048. */
  37049. this._handleObjectFunction = this._renderObjectDirect;
  37050. /**
  37051. * Indicates whether the device has been lost or not. In WebGL terms, the device
  37052. * lost is considered as a context lost. When this is set to `true`, rendering
  37053. * isn't possible anymore.
  37054. *
  37055. * @private
  37056. * @type {boolean}
  37057. * @default false
  37058. */
  37059. this._isDeviceLost = false;
  37060. /**
  37061. * A callback function that defines what should happen when a device/context lost occurs.
  37062. *
  37063. * @type {Function}
  37064. */
  37065. this.onDeviceLost = this._onDeviceLost;
  37066. /**
  37067. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  37068. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  37069. * This will reduce rendering quality though.
  37070. *
  37071. * @private
  37072. * @type {number}
  37073. * @default HalfFloatType
  37074. */
  37075. this._colorBufferType = colorBufferType;
  37076. /**
  37077. * Whether the renderer has been initialized or not.
  37078. *
  37079. * @private
  37080. * @type {boolean}
  37081. * @default false
  37082. */
  37083. this._initialized = false;
  37084. /**
  37085. * A reference to the promise which initializes the renderer.
  37086. *
  37087. * @private
  37088. * @type {?Promise<this>}
  37089. * @default null
  37090. */
  37091. this._initPromise = null;
  37092. /**
  37093. * An array of compilation promises which are used in `compileAsync()`.
  37094. *
  37095. * @private
  37096. * @type {?Array<Promise>}
  37097. * @default null
  37098. */
  37099. this._compilationPromises = null;
  37100. /**
  37101. * Whether the renderer should render transparent render objects or not.
  37102. *
  37103. * @type {boolean}
  37104. * @default true
  37105. */
  37106. this.transparent = true;
  37107. /**
  37108. * Whether the renderer should render opaque render objects or not.
  37109. *
  37110. * @type {boolean}
  37111. * @default true
  37112. */
  37113. this.opaque = true;
  37114. /**
  37115. * Shadow map configuration
  37116. * @typedef {Object} ShadowMapConfig
  37117. * @property {boolean} enabled - Whether to globally enable shadows or not.
  37118. * @property {number} type - The shadow map type.
  37119. */
  37120. /**
  37121. * The renderer's shadow configuration.
  37122. *
  37123. * @type {ShadowMapConfig}
  37124. */
  37125. this.shadowMap = {
  37126. enabled: false,
  37127. type: PCFShadowMap
  37128. };
  37129. /**
  37130. * XR configuration.
  37131. * @typedef {Object} XRConfig
  37132. * @property {boolean} enabled - Whether to globally enable XR or not.
  37133. */
  37134. /**
  37135. * The renderer's XR manager.
  37136. *
  37137. * @type {XRManager}
  37138. */
  37139. this.xr = new XRManager( this, multiview );
  37140. /**
  37141. * Debug configuration.
  37142. * @typedef {Object} DebugConfig
  37143. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  37144. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  37145. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  37146. */
  37147. /**
  37148. * The renderer's debug configuration.
  37149. *
  37150. * @type {DebugConfig}
  37151. */
  37152. this.debug = {
  37153. checkShaderErrors: true,
  37154. onShaderError: null,
  37155. getShaderAsync: async ( scene, camera, object ) => {
  37156. await this.compileAsync( scene, camera );
  37157. const renderList = this._renderLists.get( scene, camera );
  37158. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  37159. const material = scene.overrideMaterial || object.material;
  37160. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  37161. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  37162. return { fragmentShader, vertexShader };
  37163. }
  37164. };
  37165. }
  37166. /**
  37167. * Initializes the renderer so it is ready for usage.
  37168. *
  37169. * @async
  37170. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  37171. */
  37172. async init() {
  37173. if ( this._initialized ) {
  37174. throw new Error( 'Renderer: Backend has already been initialized.' );
  37175. }
  37176. if ( this._initPromise !== null ) {
  37177. return this._initPromise;
  37178. }
  37179. this._initPromise = new Promise( async ( resolve, reject ) => {
  37180. let backend = this.backend;
  37181. try {
  37182. await backend.init( this );
  37183. } catch ( error ) {
  37184. if ( this._getFallback !== null ) {
  37185. // try the fallback
  37186. try {
  37187. this.backend = backend = this._getFallback( error );
  37188. await backend.init( this );
  37189. } catch ( error ) {
  37190. reject( error );
  37191. return;
  37192. }
  37193. } else {
  37194. reject( error );
  37195. return;
  37196. }
  37197. }
  37198. this._nodes = new Nodes( this, backend );
  37199. this._animation = new Animation( this._nodes, this.info );
  37200. this._attributes = new Attributes( backend );
  37201. this._background = new Background( this, this._nodes );
  37202. this._geometries = new Geometries( this._attributes, this.info );
  37203. this._textures = new Textures( this, backend, this.info );
  37204. this._pipelines = new Pipelines( backend, this._nodes );
  37205. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  37206. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  37207. this._renderLists = new RenderLists( this.lighting );
  37208. this._bundles = new RenderBundles();
  37209. this._renderContexts = new RenderContexts();
  37210. //
  37211. this._animation.start();
  37212. this._initialized = true;
  37213. resolve( this );
  37214. } );
  37215. return this._initPromise;
  37216. }
  37217. /**
  37218. * The coordinate system of the renderer. The value of this property
  37219. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  37220. * `THREE.WebGPUCoordinateSystem`.
  37221. *
  37222. * @readonly
  37223. * @type {number}
  37224. */
  37225. get coordinateSystem() {
  37226. return this.backend.coordinateSystem;
  37227. }
  37228. /**
  37229. * Compiles all materials in the given scene. This can be useful to avoid a
  37230. * phenomenon which is called "shader compilation stutter", which occurs when
  37231. * rendering an object with a new shader for the first time.
  37232. *
  37233. * If you want to add a 3D object to an existing scene, use the third optional
  37234. * parameter for applying the target scene. Note that the (target) scene's lighting
  37235. * and environment must be configured before calling this method.
  37236. *
  37237. * @async
  37238. * @param {Object3D} scene - The scene or 3D object to precompile.
  37239. * @param {Camera} camera - The camera that is used to render the scene.
  37240. * @param {?Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  37241. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  37242. */
  37243. async compileAsync( scene, camera, targetScene = null ) {
  37244. if ( this._isDeviceLost === true ) return;
  37245. if ( this._initialized === false ) await this.init();
  37246. // preserve render tree
  37247. const nodeFrame = this._nodes.nodeFrame;
  37248. const previousRenderId = nodeFrame.renderId;
  37249. const previousRenderContext = this._currentRenderContext;
  37250. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37251. const previousCompilationPromises = this._compilationPromises;
  37252. //
  37253. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37254. if ( targetScene === null ) targetScene = scene;
  37255. const renderTarget = this._renderTarget;
  37256. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  37257. const activeMipmapLevel = this._activeMipmapLevel;
  37258. const compilationPromises = [];
  37259. this._currentRenderContext = renderContext;
  37260. this._currentRenderObjectFunction = this.renderObject;
  37261. this._handleObjectFunction = this._createObjectPipeline;
  37262. this._compilationPromises = compilationPromises;
  37263. nodeFrame.renderId ++;
  37264. //
  37265. nodeFrame.update();
  37266. //
  37267. renderContext.depth = this.depth;
  37268. renderContext.stencil = this.stencil;
  37269. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37270. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  37271. //
  37272. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37273. //
  37274. const renderList = this._renderLists.get( scene, camera );
  37275. renderList.begin();
  37276. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  37277. // include lights from target scene
  37278. if ( targetScene !== scene ) {
  37279. targetScene.traverseVisible( function ( object ) {
  37280. if ( object.isLight && object.layers.test( camera.layers ) ) {
  37281. renderList.pushLight( object );
  37282. }
  37283. } );
  37284. }
  37285. renderList.finish();
  37286. //
  37287. if ( renderTarget !== null ) {
  37288. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37289. const renderTargetData = this._textures.get( renderTarget );
  37290. renderContext.textures = renderTargetData.textures;
  37291. renderContext.depthTexture = renderTargetData.depthTexture;
  37292. } else {
  37293. renderContext.textures = null;
  37294. renderContext.depthTexture = null;
  37295. }
  37296. //
  37297. this._background.update( sceneRef, renderList, renderContext );
  37298. // process render lists
  37299. const opaqueObjects = renderList.opaque;
  37300. const transparentObjects = renderList.transparent;
  37301. const transparentDoublePassObjects = renderList.transparentDoublePass;
  37302. const lightsNode = renderList.lightsNode;
  37303. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37304. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37305. // restore render tree
  37306. nodeFrame.renderId = previousRenderId;
  37307. this._currentRenderContext = previousRenderContext;
  37308. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37309. this._compilationPromises = previousCompilationPromises;
  37310. this._handleObjectFunction = this._renderObjectDirect;
  37311. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  37312. await Promise.all( compilationPromises );
  37313. }
  37314. /**
  37315. * Renders the scene in an async fashion.
  37316. *
  37317. * @async
  37318. * @param {Object3D} scene - The scene or 3D object to render.
  37319. * @param {Camera} camera - The camera.
  37320. * @return {Promise} A Promise that resolves when the render has been finished.
  37321. */
  37322. async renderAsync( scene, camera ) {
  37323. if ( this._initialized === false ) await this.init();
  37324. this._renderScene( scene, camera );
  37325. }
  37326. /**
  37327. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  37328. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  37329. *
  37330. * @async
  37331. * @return {Promise} A Promise that resolves when synchronization has been finished.
  37332. */
  37333. async waitForGPU() {
  37334. await this.backend.waitForGPU();
  37335. }
  37336. /**
  37337. * Enables or disables high precision for model-view and normal-view matrices.
  37338. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  37339. *
  37340. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  37341. *
  37342. * @param {boolean} value - Whether to enable or disable high precision.
  37343. * @type {boolean}
  37344. */
  37345. set highPrecision( value ) {
  37346. if ( value === true ) {
  37347. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  37348. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  37349. } else if ( this.highPrecision ) {
  37350. this.overrideNodes.modelViewMatrix = null;
  37351. this.overrideNodes.modelNormalViewMatrix = null;
  37352. }
  37353. }
  37354. /**
  37355. * Returns whether high precision is enabled or not.
  37356. *
  37357. * @return {boolean} Whether high precision is enabled or not.
  37358. * @type {boolean}
  37359. */
  37360. get highPrecision() {
  37361. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  37362. }
  37363. /**
  37364. * Sets the given MRT configuration.
  37365. *
  37366. * @param {MRTNode} mrt - The MRT node to set.
  37367. * @return {Renderer} A reference to this renderer.
  37368. */
  37369. setMRT( mrt ) {
  37370. this._mrt = mrt;
  37371. return this;
  37372. }
  37373. /**
  37374. * Returns the MRT configuration.
  37375. *
  37376. * @return {MRTNode} The MRT configuration.
  37377. */
  37378. getMRT() {
  37379. return this._mrt;
  37380. }
  37381. /**
  37382. * Returns the color buffer type.
  37383. *
  37384. * @return {number} The color buffer type.
  37385. */
  37386. getColorBufferType() {
  37387. return this._colorBufferType;
  37388. }
  37389. /**
  37390. * Default implementation of the device lost callback.
  37391. *
  37392. * @private
  37393. * @param {Object} info - Information about the context lost.
  37394. */
  37395. _onDeviceLost( info ) {
  37396. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  37397. if ( info.reason ) {
  37398. errorMessage += `\nReason: ${info.reason}`;
  37399. }
  37400. console.error( errorMessage );
  37401. this._isDeviceLost = true;
  37402. }
  37403. /**
  37404. * Renders the given render bundle.
  37405. *
  37406. * @private
  37407. * @param {Object} bundle - Render bundle data.
  37408. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  37409. * @param {LightsNode} lightsNode - The lights node.
  37410. */
  37411. _renderBundle( bundle, sceneRef, lightsNode ) {
  37412. const { bundleGroup, camera, renderList } = bundle;
  37413. const renderContext = this._currentRenderContext;
  37414. //
  37415. const renderBundle = this._bundles.get( bundleGroup, camera );
  37416. const renderBundleData = this.backend.get( renderBundle );
  37417. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37418. //
  37419. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  37420. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  37421. renderBundleData.renderContexts.add( renderContext );
  37422. if ( renderBundleNeedsUpdate ) {
  37423. this.backend.beginBundle( renderContext );
  37424. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  37425. renderBundleData.renderObjects = [];
  37426. }
  37427. this._currentRenderBundle = renderBundle;
  37428. const {
  37429. transparentDoublePass: transparentDoublePassObjects,
  37430. transparent: transparentObjects,
  37431. opaque: opaqueObjects
  37432. } = renderList;
  37433. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37434. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37435. this._currentRenderBundle = null;
  37436. //
  37437. this.backend.finishBundle( renderContext, renderBundle );
  37438. renderBundleData.version = bundleGroup.version;
  37439. } else {
  37440. const { renderObjects } = renderBundleData;
  37441. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  37442. const renderObject = renderObjects[ i ];
  37443. if ( this._nodes.needsRefresh( renderObject ) ) {
  37444. this._nodes.updateBefore( renderObject );
  37445. this._nodes.updateForRender( renderObject );
  37446. this._bindings.updateForRender( renderObject );
  37447. this._nodes.updateAfter( renderObject );
  37448. }
  37449. }
  37450. }
  37451. this.backend.addBundle( renderContext, renderBundle );
  37452. }
  37453. /**
  37454. * Renders the scene or 3D object with the given camera. This method can only be called
  37455. * if the renderer has been initialized.
  37456. *
  37457. * The target of the method is the default framebuffer (meaning the canvas)
  37458. * or alternatively a render target when specified via `setRenderTarget()`.
  37459. *
  37460. * @param {Object3D} scene - The scene or 3D object to render.
  37461. * @param {Camera} camera - The camera to render the scene with.
  37462. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  37463. * Only returned when the renderer has not been initialized.
  37464. */
  37465. render( scene, camera ) {
  37466. if ( this._initialized === false ) {
  37467. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37468. return this.renderAsync( scene, camera );
  37469. }
  37470. this._renderScene( scene, camera );
  37471. }
  37472. /**
  37473. * Returns an internal render target which is used when computing the output tone mapping
  37474. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  37475. * pass and not inline to achieve more correct results.
  37476. *
  37477. * @private
  37478. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  37479. */
  37480. _getFrameBufferTarget() {
  37481. const { currentToneMapping, currentColorSpace } = this;
  37482. const useToneMapping = currentToneMapping !== NoToneMapping;
  37483. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  37484. if ( useToneMapping === false && useColorSpace === false ) return null;
  37485. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  37486. const { depth, stencil } = this;
  37487. let frameBufferTarget = this._frameBufferTarget;
  37488. if ( frameBufferTarget === null ) {
  37489. frameBufferTarget = new RenderTarget( width, height, {
  37490. depthBuffer: depth,
  37491. stencilBuffer: stencil,
  37492. type: this._colorBufferType,
  37493. format: RGBAFormat,
  37494. colorSpace: LinearSRGBColorSpace,
  37495. generateMipmaps: false,
  37496. minFilter: LinearFilter,
  37497. magFilter: LinearFilter,
  37498. samples: this.samples
  37499. } );
  37500. frameBufferTarget.isPostProcessingRenderTarget = true;
  37501. this._frameBufferTarget = frameBufferTarget;
  37502. }
  37503. const outputRenderTarget = this.getOutputRenderTarget();
  37504. frameBufferTarget.depthBuffer = depth;
  37505. frameBufferTarget.stencilBuffer = stencil;
  37506. frameBufferTarget.setSize( width, height, outputRenderTarget !== null ? outputRenderTarget.depth : 1 );
  37507. frameBufferTarget.viewport.copy( this._viewport );
  37508. frameBufferTarget.scissor.copy( this._scissor );
  37509. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37510. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37511. frameBufferTarget.scissorTest = this._scissorTest;
  37512. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  37513. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  37514. return frameBufferTarget;
  37515. }
  37516. /**
  37517. * Renders the scene or 3D object with the given camera.
  37518. *
  37519. * @private
  37520. * @param {Object3D} scene - The scene or 3D object to render.
  37521. * @param {Camera} camera - The camera to render the scene with.
  37522. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  37523. * @return {RenderContext} The current render context.
  37524. */
  37525. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37526. if ( this._isDeviceLost === true ) return;
  37527. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37528. // preserve render tree
  37529. const nodeFrame = this._nodes.nodeFrame;
  37530. const previousRenderId = nodeFrame.renderId;
  37531. const previousRenderContext = this._currentRenderContext;
  37532. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37533. //
  37534. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37535. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  37536. const activeCubeFace = this._activeCubeFace;
  37537. const activeMipmapLevel = this._activeMipmapLevel;
  37538. //
  37539. let renderTarget;
  37540. if ( frameBufferTarget !== null ) {
  37541. renderTarget = frameBufferTarget;
  37542. this.setRenderTarget( renderTarget );
  37543. } else {
  37544. renderTarget = outputRenderTarget;
  37545. }
  37546. //
  37547. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37548. this._currentRenderContext = renderContext;
  37549. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37550. //
  37551. this.info.calls ++;
  37552. this.info.render.calls ++;
  37553. this.info.render.frameCalls ++;
  37554. nodeFrame.renderId = this.info.calls;
  37555. //
  37556. const coordinateSystem = this.coordinateSystem;
  37557. const xr = this.xr;
  37558. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  37559. camera.coordinateSystem = coordinateSystem;
  37560. camera.updateProjectionMatrix();
  37561. if ( camera.isArrayCamera ) {
  37562. for ( const subCamera of camera.cameras ) {
  37563. subCamera.coordinateSystem = coordinateSystem;
  37564. subCamera.updateProjectionMatrix();
  37565. }
  37566. }
  37567. }
  37568. //
  37569. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37570. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37571. if ( xr.enabled === true && xr.isPresenting === true ) {
  37572. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  37573. camera = xr.getCamera(); // use XR camera for rendering
  37574. }
  37575. //
  37576. let viewport = this._viewport;
  37577. let scissor = this._scissor;
  37578. let pixelRatio = this._pixelRatio;
  37579. if ( renderTarget !== null ) {
  37580. viewport = renderTarget.viewport;
  37581. scissor = renderTarget.scissor;
  37582. pixelRatio = 1;
  37583. }
  37584. this.getDrawingBufferSize( _drawingBufferSize );
  37585. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  37586. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37587. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37588. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37589. renderContext.viewportValue.width >>= activeMipmapLevel;
  37590. renderContext.viewportValue.height >>= activeMipmapLevel;
  37591. renderContext.viewportValue.minDepth = minDepth;
  37592. renderContext.viewportValue.maxDepth = maxDepth;
  37593. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false || this._forceViewport;
  37594. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37595. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37596. renderContext.scissorValue.width >>= activeMipmapLevel;
  37597. renderContext.scissorValue.height >>= activeMipmapLevel;
  37598. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37599. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  37600. //
  37601. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37602. //
  37603. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  37604. if ( ! camera.isArrayCamera ) {
  37605. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37606. frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37607. }
  37608. const renderList = this._renderLists.get( scene, camera );
  37609. renderList.begin();
  37610. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  37611. renderList.finish();
  37612. if ( this.sortObjects === true ) {
  37613. renderList.sort( this._opaqueSort, this._transparentSort );
  37614. }
  37615. //
  37616. if ( renderTarget !== null ) {
  37617. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37618. const renderTargetData = this._textures.get( renderTarget );
  37619. renderContext.textures = renderTargetData.textures;
  37620. renderContext.depthTexture = renderTargetData.depthTexture;
  37621. renderContext.width = renderTargetData.width;
  37622. renderContext.height = renderTargetData.height;
  37623. renderContext.renderTarget = renderTarget;
  37624. renderContext.depth = renderTarget.depthBuffer;
  37625. renderContext.stencil = renderTarget.stencilBuffer;
  37626. } else {
  37627. renderContext.textures = null;
  37628. renderContext.depthTexture = null;
  37629. renderContext.width = this.domElement.width;
  37630. renderContext.height = this.domElement.height;
  37631. renderContext.depth = this.depth;
  37632. renderContext.stencil = this.stencil;
  37633. }
  37634. renderContext.width >>= activeMipmapLevel;
  37635. renderContext.height >>= activeMipmapLevel;
  37636. renderContext.activeCubeFace = activeCubeFace;
  37637. renderContext.activeMipmapLevel = activeMipmapLevel;
  37638. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37639. //
  37640. this._background.update( sceneRef, renderList, renderContext );
  37641. //
  37642. renderContext.camera = camera;
  37643. this.backend.beginRender( renderContext );
  37644. // process render lists
  37645. const {
  37646. bundles,
  37647. lightsNode,
  37648. transparentDoublePass: transparentDoublePassObjects,
  37649. transparent: transparentObjects,
  37650. opaque: opaqueObjects
  37651. } = renderList;
  37652. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37653. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37654. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37655. // finish render pass
  37656. this.backend.finishRender( renderContext );
  37657. // restore render tree
  37658. nodeFrame.renderId = previousRenderId;
  37659. this._currentRenderContext = previousRenderContext;
  37660. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37661. //
  37662. if ( frameBufferTarget !== null ) {
  37663. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37664. this._renderOutput( renderTarget );
  37665. }
  37666. //
  37667. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37668. //
  37669. return renderContext;
  37670. }
  37671. _setXRLayerSize( width, height ) {
  37672. this._width = width;
  37673. this._height = height;
  37674. this._forceViewport = true;
  37675. this.setViewport( 0, 0, width, height );
  37676. }
  37677. /**
  37678. * The output pass performs tone mapping and color space conversion.
  37679. *
  37680. * @private
  37681. * @param {RenderTarget} renderTarget - The current render target.
  37682. */
  37683. _renderOutput( renderTarget ) {
  37684. const quad = this._quad;
  37685. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37686. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37687. quad.material.needsUpdate = true;
  37688. }
  37689. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  37690. const currentAutoClear = this.autoClear;
  37691. const currentXR = this.xr.enabled;
  37692. this.autoClear = false;
  37693. this.xr.enabled = false;
  37694. this._renderScene( quad, quad.camera, false );
  37695. this.autoClear = currentAutoClear;
  37696. this.xr.enabled = currentXR;
  37697. }
  37698. /**
  37699. * Returns the maximum available anisotropy for texture filtering.
  37700. *
  37701. * @return {number} The maximum available anisotropy.
  37702. */
  37703. getMaxAnisotropy() {
  37704. return this.backend.getMaxAnisotropy();
  37705. }
  37706. /**
  37707. * Returns the active cube face.
  37708. *
  37709. * @return {number} The active cube face.
  37710. */
  37711. getActiveCubeFace() {
  37712. return this._activeCubeFace;
  37713. }
  37714. /**
  37715. * Returns the active mipmap level.
  37716. *
  37717. * @return {number} The active mipmap level.
  37718. */
  37719. getActiveMipmapLevel() {
  37720. return this._activeMipmapLevel;
  37721. }
  37722. /**
  37723. * Applications are advised to always define the animation loop
  37724. * with this method and not manually with `requestAnimationFrame()`
  37725. * for best compatibility.
  37726. *
  37727. * @async
  37728. * @param {?Function} callback - The application's animation loop.
  37729. * @return {Promise} A Promise that resolves when the set has been executed.
  37730. */
  37731. async setAnimationLoop( callback ) {
  37732. if ( this._initialized === false ) await this.init();
  37733. this._animation.setAnimationLoop( callback );
  37734. }
  37735. /**
  37736. * Can be used to transfer buffer data from a storage buffer attribute
  37737. * from the GPU to the CPU in context of compute shaders.
  37738. *
  37739. * @async
  37740. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  37741. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  37742. */
  37743. async getArrayBufferAsync( attribute ) {
  37744. return await this.backend.getArrayBufferAsync( attribute );
  37745. }
  37746. /**
  37747. * Returns the rendering context.
  37748. *
  37749. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  37750. */
  37751. getContext() {
  37752. return this.backend.getContext();
  37753. }
  37754. /**
  37755. * Returns the pixel ratio.
  37756. *
  37757. * @return {number} The pixel ratio.
  37758. */
  37759. getPixelRatio() {
  37760. return this._pixelRatio;
  37761. }
  37762. /**
  37763. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  37764. *
  37765. * @param {Vector2} target - The method writes the result in this target object.
  37766. * @return {Vector2} The drawing buffer size.
  37767. */
  37768. getDrawingBufferSize( target ) {
  37769. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37770. }
  37771. /**
  37772. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  37773. *
  37774. * @param {Vector2} target - The method writes the result in this target object.
  37775. * @return {Vector2} The renderer's size in logical pixels.
  37776. */
  37777. getSize( target ) {
  37778. return target.set( this._width, this._height );
  37779. }
  37780. /**
  37781. * Sets the given pixel ratio and resizes the canvas if necessary.
  37782. *
  37783. * @param {number} [value=1] - The pixel ratio.
  37784. */
  37785. setPixelRatio( value = 1 ) {
  37786. if ( this._pixelRatio === value ) return;
  37787. this._pixelRatio = value;
  37788. this.setSize( this._width, this._height, false );
  37789. }
  37790. /**
  37791. * This method allows to define the drawing buffer size by specifying
  37792. * width, height and pixel ratio all at once. The size of the drawing
  37793. * buffer is computed with this formula:
  37794. * ```js
  37795. * size.x = width * pixelRatio;
  37796. * size.y = height * pixelRatio;
  37797. * ```
  37798. *
  37799. * @param {number} width - The width in logical pixels.
  37800. * @param {number} height - The height in logical pixels.
  37801. * @param {number} pixelRatio - The pixel ratio.
  37802. */
  37803. setDrawingBufferSize( width, height, pixelRatio ) {
  37804. // Renderer can't be resized while presenting in XR.
  37805. if ( this.xr && this.xr.isPresenting ) return;
  37806. this._width = width;
  37807. this._height = height;
  37808. this._pixelRatio = pixelRatio;
  37809. this.domElement.width = Math.floor( width * pixelRatio );
  37810. this.domElement.height = Math.floor( height * pixelRatio );
  37811. this._forceViewport = false;
  37812. this.setViewport( 0, 0, width, height );
  37813. if ( this._initialized ) this.backend.updateSize();
  37814. }
  37815. /**
  37816. * Sets the size of the renderer.
  37817. *
  37818. * @param {number} width - The width in logical pixels.
  37819. * @param {number} height - The height in logical pixels.
  37820. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  37821. */
  37822. setSize( width, height, updateStyle = true ) {
  37823. // Renderer can't be resized while presenting in XR.
  37824. if ( this.xr && this.xr.isPresenting ) return;
  37825. this._width = width;
  37826. this._height = height;
  37827. this.domElement.width = Math.floor( width * this._pixelRatio );
  37828. this.domElement.height = Math.floor( height * this._pixelRatio );
  37829. this._forceViewport = false;
  37830. if ( updateStyle === true ) {
  37831. this.domElement.style.width = width + 'px';
  37832. this.domElement.style.height = height + 'px';
  37833. }
  37834. this.setViewport( 0, 0, width, height );
  37835. if ( this._initialized ) this.backend.updateSize();
  37836. }
  37837. /**
  37838. * Defines a manual sort function for the opaque render list.
  37839. * Pass `null` to use the default sort.
  37840. *
  37841. * @param {Function} method - The sort function.
  37842. */
  37843. setOpaqueSort( method ) {
  37844. this._opaqueSort = method;
  37845. }
  37846. /**
  37847. * Defines a manual sort function for the transparent render list.
  37848. * Pass `null` to use the default sort.
  37849. *
  37850. * @param {Function} method - The sort function.
  37851. */
  37852. setTransparentSort( method ) {
  37853. this._transparentSort = method;
  37854. }
  37855. /**
  37856. * Returns the scissor rectangle.
  37857. *
  37858. * @param {Vector4} target - The method writes the result in this target object.
  37859. * @return {Vector4} The scissor rectangle.
  37860. */
  37861. getScissor( target ) {
  37862. const scissor = this._scissor;
  37863. target.x = scissor.x;
  37864. target.y = scissor.y;
  37865. target.width = scissor.width;
  37866. target.height = scissor.height;
  37867. return target;
  37868. }
  37869. /**
  37870. * Defines the scissor rectangle.
  37871. *
  37872. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  37873. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  37874. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  37875. * @param {number} width - The width of the scissor box in logical pixel unit.
  37876. * @param {number} height - The height of the scissor box in logical pixel unit.
  37877. */
  37878. setScissor( x, y, width, height ) {
  37879. const scissor = this._scissor;
  37880. if ( x.isVector4 ) {
  37881. scissor.copy( x );
  37882. } else {
  37883. scissor.set( x, y, width, height );
  37884. }
  37885. }
  37886. /**
  37887. * Returns the scissor test value.
  37888. *
  37889. * @return {boolean} Whether the scissor test should be enabled or not.
  37890. */
  37891. getScissorTest() {
  37892. return this._scissorTest;
  37893. }
  37894. /**
  37895. * Defines the scissor test.
  37896. *
  37897. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  37898. */
  37899. setScissorTest( boolean ) {
  37900. this._scissorTest = boolean;
  37901. this.backend.setScissorTest( boolean );
  37902. }
  37903. /**
  37904. * Returns the viewport definition.
  37905. *
  37906. * @param {Vector4} target - The method writes the result in this target object.
  37907. * @return {Vector4} The viewport definition.
  37908. */
  37909. getViewport( target ) {
  37910. return target.copy( this._viewport );
  37911. }
  37912. /**
  37913. * Defines the viewport.
  37914. *
  37915. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  37916. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  37917. * @param {number} width - The width of the viewport in logical pixel unit.
  37918. * @param {number} height - The height of the viewport in logical pixel unit.
  37919. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  37920. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  37921. */
  37922. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  37923. const viewport = this._viewport;
  37924. if ( x.isVector4 ) {
  37925. viewport.copy( x );
  37926. } else {
  37927. viewport.set( x, y, width, height );
  37928. }
  37929. viewport.minDepth = minDepth;
  37930. viewport.maxDepth = maxDepth;
  37931. }
  37932. /**
  37933. * Returns the clear color.
  37934. *
  37935. * @param {Color} target - The method writes the result in this target object.
  37936. * @return {Color} The clear color.
  37937. */
  37938. getClearColor( target ) {
  37939. return target.copy( this._clearColor );
  37940. }
  37941. /**
  37942. * Defines the clear color and optionally the clear alpha.
  37943. *
  37944. * @param {Color} color - The clear color.
  37945. * @param {number} [alpha=1] - The clear alpha.
  37946. */
  37947. setClearColor( color, alpha = 1 ) {
  37948. this._clearColor.set( color );
  37949. this._clearColor.a = alpha;
  37950. }
  37951. /**
  37952. * Returns the clear alpha.
  37953. *
  37954. * @return {number} The clear alpha.
  37955. */
  37956. getClearAlpha() {
  37957. return this._clearColor.a;
  37958. }
  37959. /**
  37960. * Defines the clear alpha.
  37961. *
  37962. * @param {number} alpha - The clear alpha.
  37963. */
  37964. setClearAlpha( alpha ) {
  37965. this._clearColor.a = alpha;
  37966. }
  37967. /**
  37968. * Returns the clear depth.
  37969. *
  37970. * @return {number} The clear depth.
  37971. */
  37972. getClearDepth() {
  37973. return this._clearDepth;
  37974. }
  37975. /**
  37976. * Defines the clear depth.
  37977. *
  37978. * @param {number} depth - The clear depth.
  37979. */
  37980. setClearDepth( depth ) {
  37981. this._clearDepth = depth;
  37982. }
  37983. /**
  37984. * Returns the clear stencil.
  37985. *
  37986. * @return {number} The clear stencil.
  37987. */
  37988. getClearStencil() {
  37989. return this._clearStencil;
  37990. }
  37991. /**
  37992. * Defines the clear stencil.
  37993. *
  37994. * @param {number} stencil - The clear stencil.
  37995. */
  37996. setClearStencil( stencil ) {
  37997. this._clearStencil = stencil;
  37998. }
  37999. /**
  38000. * This method performs an occlusion query for the given 3D object.
  38001. * It returns `true` if the given 3D object is fully occluded by other
  38002. * 3D objects in the scene.
  38003. *
  38004. * @param {Object3D} object - The 3D object to test.
  38005. * @return {boolean} Whether the 3D object is fully occluded or not.
  38006. */
  38007. isOccluded( object ) {
  38008. const renderContext = this._currentRenderContext;
  38009. return renderContext && this.backend.isOccluded( renderContext, object );
  38010. }
  38011. /**
  38012. * Performs a manual clear operation. This method ignores `autoClear` properties.
  38013. *
  38014. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  38015. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  38016. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  38017. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38018. * Only returned when the renderer has not been initialized.
  38019. */
  38020. clear( color = true, depth = true, stencil = true ) {
  38021. if ( this._initialized === false ) {
  38022. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  38023. return this.clearAsync( color, depth, stencil );
  38024. }
  38025. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38026. let renderContext = null;
  38027. if ( renderTarget !== null ) {
  38028. this._textures.updateRenderTarget( renderTarget );
  38029. const renderTargetData = this._textures.get( renderTarget );
  38030. renderContext = this._renderContexts.getForClear( renderTarget );
  38031. renderContext.textures = renderTargetData.textures;
  38032. renderContext.depthTexture = renderTargetData.depthTexture;
  38033. renderContext.width = renderTargetData.width;
  38034. renderContext.height = renderTargetData.height;
  38035. renderContext.renderTarget = renderTarget;
  38036. renderContext.depth = renderTarget.depthBuffer;
  38037. renderContext.stencil = renderTarget.stencilBuffer;
  38038. // #30329
  38039. renderContext.clearColorValue = this.backend.getClearColor();
  38040. renderContext.activeCubeFace = this.getActiveCubeFace();
  38041. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  38042. }
  38043. this.backend.clear( color, depth, stencil, renderContext );
  38044. if ( renderTarget !== null && this._renderTarget === null ) {
  38045. this._renderOutput( renderTarget );
  38046. }
  38047. }
  38048. /**
  38049. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  38050. *
  38051. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38052. * Only returned when the renderer has not been initialized.
  38053. */
  38054. clearColor() {
  38055. return this.clear( true, false, false );
  38056. }
  38057. /**
  38058. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  38059. *
  38060. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38061. * Only returned when the renderer has not been initialized.
  38062. */
  38063. clearDepth() {
  38064. return this.clear( false, true, false );
  38065. }
  38066. /**
  38067. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  38068. *
  38069. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38070. * Only returned when the renderer has not been initialized.
  38071. */
  38072. clearStencil() {
  38073. return this.clear( false, false, true );
  38074. }
  38075. /**
  38076. * Async version of {@link Renderer#clear}.
  38077. *
  38078. * @async
  38079. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  38080. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  38081. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  38082. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38083. */
  38084. async clearAsync( color = true, depth = true, stencil = true ) {
  38085. if ( this._initialized === false ) await this.init();
  38086. this.clear( color, depth, stencil );
  38087. }
  38088. /**
  38089. * Async version of {@link Renderer#clearColor}.
  38090. *
  38091. * @async
  38092. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38093. */
  38094. async clearColorAsync() {
  38095. this.clearAsync( true, false, false );
  38096. }
  38097. /**
  38098. * Async version of {@link Renderer#clearDepth}.
  38099. *
  38100. * @async
  38101. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38102. */
  38103. async clearDepthAsync() {
  38104. this.clearAsync( false, true, false );
  38105. }
  38106. /**
  38107. * Async version of {@link Renderer#clearStencil}.
  38108. *
  38109. * @async
  38110. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38111. */
  38112. async clearStencilAsync() {
  38113. this.clearAsync( false, false, true );
  38114. }
  38115. /**
  38116. * The current output tone mapping of the renderer. When a render target is set,
  38117. * the output tone mapping is always `NoToneMapping`.
  38118. *
  38119. * @type {number}
  38120. */
  38121. get currentToneMapping() {
  38122. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  38123. }
  38124. /**
  38125. * The current output color space of the renderer. When a render target is set,
  38126. * the output color space is always `LinearSRGBColorSpace`.
  38127. *
  38128. * @type {string}
  38129. */
  38130. get currentColorSpace() {
  38131. return this.isOutputTarget ? this.outputColorSpace : LinearSRGBColorSpace;
  38132. }
  38133. /**
  38134. * Returns `true` if the rendering settings are set to screen output.
  38135. *
  38136. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  38137. */
  38138. get isOutputTarget() {
  38139. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  38140. }
  38141. /**
  38142. * Frees all internal resources of the renderer. Call this method if the renderer
  38143. * is no longer in use by your app.
  38144. */
  38145. dispose() {
  38146. this.info.dispose();
  38147. this.backend.dispose();
  38148. this._animation.dispose();
  38149. this._objects.dispose();
  38150. this._pipelines.dispose();
  38151. this._nodes.dispose();
  38152. this._bindings.dispose();
  38153. this._renderLists.dispose();
  38154. this._renderContexts.dispose();
  38155. this._textures.dispose();
  38156. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  38157. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  38158. if ( queryPool !== null ) queryPool.dispose();
  38159. } );
  38160. this.setRenderTarget( null );
  38161. this.setAnimationLoop( null );
  38162. }
  38163. /**
  38164. * Sets the given render target. Calling this method means the renderer does not
  38165. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  38166. * Use `null` as the first argument to reset the state.
  38167. *
  38168. * @param {?RenderTarget} renderTarget - The render target to set.
  38169. * @param {number} [activeCubeFace=0] - The active cube face.
  38170. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  38171. */
  38172. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  38173. this._renderTarget = renderTarget;
  38174. this._activeCubeFace = activeCubeFace;
  38175. this._activeMipmapLevel = activeMipmapLevel;
  38176. }
  38177. /**
  38178. * Returns the current render target.
  38179. *
  38180. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  38181. */
  38182. getRenderTarget() {
  38183. return this._renderTarget;
  38184. }
  38185. /**
  38186. * Sets the output render target for the renderer.
  38187. *
  38188. * @param {Object} renderTarget - The render target to set as the output target.
  38189. */
  38190. setOutputRenderTarget( renderTarget ) {
  38191. this._outputRenderTarget = renderTarget;
  38192. }
  38193. /**
  38194. * Returns the current output target.
  38195. *
  38196. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  38197. */
  38198. getOutputRenderTarget() {
  38199. return this._outputRenderTarget;
  38200. }
  38201. /**
  38202. * Resets the renderer to the initial state before WebXR started.
  38203. *
  38204. */
  38205. _resetXRState() {
  38206. this.backend.setXRTarget( null );
  38207. this.setOutputRenderTarget( null );
  38208. this.setRenderTarget( null );
  38209. this._frameBufferTarget.dispose();
  38210. this._frameBufferTarget = null;
  38211. }
  38212. /**
  38213. * Callback for {@link Renderer#setRenderObjectFunction}.
  38214. *
  38215. * @callback renderObjectFunction
  38216. * @param {Object3D} object - The 3D object.
  38217. * @param {Scene} scene - The scene the 3D object belongs to.
  38218. * @param {Camera} camera - The camera the object should be rendered with.
  38219. * @param {BufferGeometry} geometry - The object's geometry.
  38220. * @param {Material} material - The object's material.
  38221. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38222. * @param {LightsNode} lightsNode - The current lights node.
  38223. * @param {ClippingContext} clippingContext - The clipping context.
  38224. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38225. */
  38226. /**
  38227. * Sets the given render object function. Calling this method overwrites the default implementation
  38228. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  38229. * if you want to modify the way objects are rendered. For example you can define things like "every
  38230. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  38231. * The custom function must always call `renderObject()` in its implementation.
  38232. *
  38233. * Use `null` as the first argument to reset the state.
  38234. *
  38235. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  38236. */
  38237. setRenderObjectFunction( renderObjectFunction ) {
  38238. this._renderObjectFunction = renderObjectFunction;
  38239. }
  38240. /**
  38241. * Returns the current render object function.
  38242. *
  38243. * @return {?Function} The current render object function. Returns `null` if no function is set.
  38244. */
  38245. getRenderObjectFunction() {
  38246. return this._renderObjectFunction;
  38247. }
  38248. /**
  38249. * Execute a single or an array of compute nodes. This method can only be called
  38250. * if the renderer has been initialized.
  38251. *
  38252. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  38253. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  38254. */
  38255. compute( computeNodes ) {
  38256. if ( this._isDeviceLost === true ) return;
  38257. if ( this._initialized === false ) {
  38258. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  38259. return this.computeAsync( computeNodes );
  38260. }
  38261. //
  38262. const nodeFrame = this._nodes.nodeFrame;
  38263. const previousRenderId = nodeFrame.renderId;
  38264. //
  38265. this.info.calls ++;
  38266. this.info.compute.calls ++;
  38267. this.info.compute.frameCalls ++;
  38268. nodeFrame.renderId = this.info.calls;
  38269. //
  38270. const backend = this.backend;
  38271. const pipelines = this._pipelines;
  38272. const bindings = this._bindings;
  38273. const nodes = this._nodes;
  38274. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  38275. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  38276. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  38277. }
  38278. backend.beginCompute( computeNodes );
  38279. for ( const computeNode of computeList ) {
  38280. // onInit
  38281. if ( pipelines.has( computeNode ) === false ) {
  38282. const dispose = () => {
  38283. computeNode.removeEventListener( 'dispose', dispose );
  38284. pipelines.delete( computeNode );
  38285. bindings.delete( computeNode );
  38286. nodes.delete( computeNode );
  38287. };
  38288. computeNode.addEventListener( 'dispose', dispose );
  38289. //
  38290. const onInitFn = computeNode.onInitFunction;
  38291. if ( onInitFn !== null ) {
  38292. onInitFn.call( computeNode, { renderer: this } );
  38293. }
  38294. }
  38295. nodes.updateForCompute( computeNode );
  38296. bindings.updateForCompute( computeNode );
  38297. const computeBindings = bindings.getForCompute( computeNode );
  38298. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  38299. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  38300. }
  38301. backend.finishCompute( computeNodes );
  38302. //
  38303. nodeFrame.renderId = previousRenderId;
  38304. }
  38305. /**
  38306. * Execute a single or an array of compute nodes.
  38307. *
  38308. * @async
  38309. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  38310. * @return {Promise} A Promise that resolve when the compute has finished.
  38311. */
  38312. async computeAsync( computeNodes ) {
  38313. if ( this._initialized === false ) await this.init();
  38314. this.compute( computeNodes );
  38315. }
  38316. /**
  38317. * Checks if the given feature is supported by the selected backend.
  38318. *
  38319. * @async
  38320. * @param {string} name - The feature's name.
  38321. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  38322. */
  38323. async hasFeatureAsync( name ) {
  38324. if ( this._initialized === false ) await this.init();
  38325. return this.backend.hasFeature( name );
  38326. }
  38327. async resolveTimestampsAsync( type = 'render' ) {
  38328. if ( this._initialized === false ) await this.init();
  38329. return this.backend.resolveTimestampsAsync( type );
  38330. }
  38331. /**
  38332. * Checks if the given feature is supported by the selected backend. If the
  38333. * renderer has not been initialized, this method always returns `false`.
  38334. *
  38335. * @param {string} name - The feature's name.
  38336. * @return {boolean} Whether the feature is supported or not.
  38337. */
  38338. hasFeature( name ) {
  38339. if ( this._initialized === false ) {
  38340. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  38341. return false;
  38342. }
  38343. return this.backend.hasFeature( name );
  38344. }
  38345. /**
  38346. * Returns `true` when the renderer has been initialized.
  38347. *
  38348. * @return {boolean} Whether the renderer has been initialized or not.
  38349. */
  38350. hasInitialized() {
  38351. return this._initialized;
  38352. }
  38353. /**
  38354. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  38355. * (which can cause noticeable lags due to decode and GPU upload overhead).
  38356. *
  38357. * @async
  38358. * @param {Texture} texture - The texture.
  38359. * @return {Promise} A Promise that resolves when the texture has been initialized.
  38360. */
  38361. async initTextureAsync( texture ) {
  38362. if ( this._initialized === false ) await this.init();
  38363. this._textures.updateTexture( texture );
  38364. }
  38365. /**
  38366. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  38367. * (which can cause noticeable lags due to decode and GPU upload overhead).
  38368. *
  38369. * This method can only be used if the renderer has been initialized.
  38370. *
  38371. * @param {Texture} texture - The texture.
  38372. */
  38373. initTexture( texture ) {
  38374. if ( this._initialized === false ) {
  38375. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  38376. }
  38377. this._textures.updateTexture( texture );
  38378. }
  38379. /**
  38380. * Copies the current bound framebuffer into the given texture.
  38381. *
  38382. * @param {FramebufferTexture} framebufferTexture - The texture.
  38383. * @param {?Vector2|Vector4} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  38384. */
  38385. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  38386. if ( rectangle !== null ) {
  38387. if ( rectangle.isVector2 ) {
  38388. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  38389. } else if ( rectangle.isVector4 ) {
  38390. rectangle = _vector4.copy( rectangle ).floor();
  38391. } else {
  38392. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  38393. return;
  38394. }
  38395. } else {
  38396. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  38397. }
  38398. //
  38399. let renderContext = this._currentRenderContext;
  38400. let renderTarget;
  38401. if ( renderContext !== null ) {
  38402. renderTarget = renderContext.renderTarget;
  38403. } else {
  38404. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38405. if ( renderTarget !== null ) {
  38406. this._textures.updateRenderTarget( renderTarget );
  38407. renderContext = this._textures.get( renderTarget );
  38408. }
  38409. }
  38410. //
  38411. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  38412. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  38413. }
  38414. /**
  38415. * Copies data of the given source texture into a destination texture.
  38416. *
  38417. * @param {Texture} srcTexture - The source texture.
  38418. * @param {Texture} dstTexture - The destination texture.
  38419. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  38420. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  38421. * @param {number} [srcLevel=0] - The source mip level to copy from.
  38422. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  38423. */
  38424. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  38425. this._textures.updateTexture( srcTexture );
  38426. this._textures.updateTexture( dstTexture );
  38427. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  38428. }
  38429. /**
  38430. * Reads pixel data from the given render target.
  38431. *
  38432. * @async
  38433. * @param {RenderTarget} renderTarget - The render target to read from.
  38434. * @param {number} x - The `x` coordinate of the copy region's origin.
  38435. * @param {number} y - The `y` coordinate of the copy region's origin.
  38436. * @param {number} width - The width of the copy region.
  38437. * @param {number} height - The height of the copy region.
  38438. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  38439. * @param {number} [faceIndex=0] - The active cube face index.
  38440. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  38441. */
  38442. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  38443. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  38444. }
  38445. /**
  38446. * Analyzes the given 3D object's hierarchy and builds render lists from the
  38447. * processed hierarchy.
  38448. *
  38449. * @param {Object3D} object - The 3D object to process (usually a scene).
  38450. * @param {Camera} camera - The camera the object is rendered with.
  38451. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  38452. * @param {RenderList} renderList - The current render list.
  38453. * @param {ClippingContext} clippingContext - The current clipping context.
  38454. */
  38455. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  38456. if ( object.visible === false ) return;
  38457. const visible = object.layers.test( camera.layers );
  38458. if ( visible ) {
  38459. if ( object.isGroup ) {
  38460. groupOrder = object.renderOrder;
  38461. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  38462. } else if ( object.isLOD ) {
  38463. if ( object.autoUpdate === true ) object.update( camera );
  38464. } else if ( object.isLight ) {
  38465. renderList.pushLight( object );
  38466. } else if ( object.isSprite ) {
  38467. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38468. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  38469. if ( this.sortObjects === true ) {
  38470. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  38471. }
  38472. const { geometry, material } = object;
  38473. if ( material.visible ) {
  38474. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38475. }
  38476. }
  38477. } else if ( object.isLineLoop ) {
  38478. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  38479. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  38480. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38481. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  38482. const { geometry, material } = object;
  38483. if ( this.sortObjects === true ) {
  38484. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  38485. _vector4
  38486. .copy( geometry.boundingSphere.center )
  38487. .applyMatrix4( object.matrixWorld )
  38488. .applyMatrix4( _projScreenMatrix );
  38489. }
  38490. if ( Array.isArray( material ) ) {
  38491. const groups = geometry.groups;
  38492. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  38493. const group = groups[ i ];
  38494. const groupMaterial = material[ group.materialIndex ];
  38495. if ( groupMaterial && groupMaterial.visible ) {
  38496. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  38497. }
  38498. }
  38499. } else if ( material.visible ) {
  38500. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38501. }
  38502. }
  38503. }
  38504. }
  38505. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  38506. const baseRenderList = renderList;
  38507. // replace render list
  38508. renderList = this._renderLists.get( object, camera );
  38509. renderList.begin();
  38510. baseRenderList.pushBundle( {
  38511. bundleGroup: object,
  38512. camera,
  38513. renderList,
  38514. } );
  38515. renderList.finish();
  38516. }
  38517. const children = object.children;
  38518. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38519. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  38520. }
  38521. }
  38522. /**
  38523. * Renders the given render bundles.
  38524. *
  38525. * @private
  38526. * @param {Array<Object>} bundles - Array with render bundle data.
  38527. * @param {Scene} sceneRef - The scene the render bundles belong to.
  38528. * @param {LightsNode} lightsNode - The current lights node.
  38529. */
  38530. _renderBundles( bundles, sceneRef, lightsNode ) {
  38531. for ( const bundle of bundles ) {
  38532. this._renderBundle( bundle, sceneRef, lightsNode );
  38533. }
  38534. }
  38535. /**
  38536. * Renders the transparent objects from the given render lists.
  38537. *
  38538. * @private
  38539. * @param {Array<Object>} renderList - The transparent render list.
  38540. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  38541. * @param {Camera} camera - The camera the render list should be rendered with.
  38542. * @param {Scene} scene - The scene the render list belongs to.
  38543. * @param {LightsNode} lightsNode - The current lights node.
  38544. */
  38545. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  38546. if ( doublePassList.length > 0 ) {
  38547. // render back side
  38548. for ( const { material } of doublePassList ) {
  38549. material.side = BackSide;
  38550. }
  38551. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  38552. // render front side
  38553. for ( const { material } of doublePassList ) {
  38554. material.side = FrontSide;
  38555. }
  38556. this._renderObjects( renderList, camera, scene, lightsNode );
  38557. // restore
  38558. for ( const { material } of doublePassList ) {
  38559. material.side = DoubleSide;
  38560. }
  38561. } else {
  38562. this._renderObjects( renderList, camera, scene, lightsNode );
  38563. }
  38564. }
  38565. /**
  38566. * Renders the objects from the given render list.
  38567. *
  38568. * @private
  38569. * @param {Array<Object>} renderList - The render list.
  38570. * @param {Camera} camera - The camera the render list should be rendered with.
  38571. * @param {Scene} scene - The scene the render list belongs to.
  38572. * @param {LightsNode} lightsNode - The current lights node.
  38573. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38574. */
  38575. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  38576. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  38577. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  38578. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  38579. }
  38580. }
  38581. /**
  38582. * This method represents the default render object function that manages the render lifecycle
  38583. * of the object.
  38584. *
  38585. * @param {Object3D} object - The 3D object.
  38586. * @param {Scene} scene - The scene the 3D object belongs to.
  38587. * @param {Camera} camera - The camera the object should be rendered with.
  38588. * @param {BufferGeometry} geometry - The object's geometry.
  38589. * @param {Material} material - The object's material.
  38590. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38591. * @param {LightsNode} lightsNode - The current lights node.
  38592. * @param {?ClippingContext} clippingContext - The clipping context.
  38593. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38594. */
  38595. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  38596. let overridePositionNode;
  38597. let overrideColorNode;
  38598. let overrideDepthNode;
  38599. //
  38600. object.onBeforeRender( this, scene, camera, geometry, material, group );
  38601. //
  38602. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  38603. const overrideMaterial = scene.overrideMaterial;
  38604. if ( material.positionNode && material.positionNode.isNode ) {
  38605. overridePositionNode = overrideMaterial.positionNode;
  38606. overrideMaterial.positionNode = material.positionNode;
  38607. }
  38608. overrideMaterial.alphaTest = material.alphaTest;
  38609. overrideMaterial.alphaMap = material.alphaMap;
  38610. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  38611. if ( overrideMaterial.isShadowPassMaterial ) {
  38612. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  38613. if ( material.depthNode && material.depthNode.isNode ) {
  38614. overrideDepthNode = overrideMaterial.depthNode;
  38615. overrideMaterial.depthNode = material.depthNode;
  38616. }
  38617. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  38618. overrideColorNode = overrideMaterial.colorNode;
  38619. overrideMaterial.colorNode = material.castShadowNode;
  38620. }
  38621. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  38622. overridePositionNode = overrideMaterial.positionNode;
  38623. overrideMaterial.positionNode = material.castShadowPositionNode;
  38624. }
  38625. }
  38626. material = overrideMaterial;
  38627. }
  38628. //
  38629. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  38630. material.side = BackSide;
  38631. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  38632. material.side = FrontSide;
  38633. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  38634. material.side = DoubleSide;
  38635. } else {
  38636. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  38637. }
  38638. //
  38639. if ( overridePositionNode !== undefined ) {
  38640. scene.overrideMaterial.positionNode = overridePositionNode;
  38641. }
  38642. if ( overrideDepthNode !== undefined ) {
  38643. scene.overrideMaterial.depthNode = overrideDepthNode;
  38644. }
  38645. if ( overrideColorNode !== undefined ) {
  38646. scene.overrideMaterial.colorNode = overrideColorNode;
  38647. }
  38648. //
  38649. object.onAfterRender( this, scene, camera, geometry, material, group );
  38650. }
  38651. /**
  38652. * This method represents the default `_handleObjectFunction` implementation which creates
  38653. * a render object from the given data and performs the draw command with the selected backend.
  38654. *
  38655. * @private
  38656. * @param {Object3D} object - The 3D object.
  38657. * @param {Material} material - The object's material.
  38658. * @param {Scene} scene - The scene the 3D object belongs to.
  38659. * @param {Camera} camera - The camera the object should be rendered with.
  38660. * @param {LightsNode} lightsNode - The current lights node.
  38661. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38662. * @param {ClippingContext} clippingContext - The clipping context.
  38663. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38664. */
  38665. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  38666. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  38667. renderObject.drawRange = object.geometry.drawRange;
  38668. renderObject.group = group;
  38669. //
  38670. const needsRefresh = this._nodes.needsRefresh( renderObject );
  38671. if ( needsRefresh ) {
  38672. this._nodes.updateBefore( renderObject );
  38673. this._geometries.updateForRender( renderObject );
  38674. this._nodes.updateForRender( renderObject );
  38675. this._bindings.updateForRender( renderObject );
  38676. }
  38677. this._pipelines.updateForRender( renderObject );
  38678. //
  38679. if ( this._currentRenderBundle !== null ) {
  38680. const renderBundleData = this.backend.get( this._currentRenderBundle );
  38681. renderBundleData.renderObjects.push( renderObject );
  38682. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  38683. }
  38684. this.backend.draw( renderObject, this.info );
  38685. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  38686. }
  38687. /**
  38688. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  38689. * Used in `compileAsync()`.
  38690. *
  38691. * @private
  38692. * @param {Object3D} object - The 3D object.
  38693. * @param {Material} material - The object's material.
  38694. * @param {Scene} scene - The scene the 3D object belongs to.
  38695. * @param {Camera} camera - The camera the object should be rendered with.
  38696. * @param {LightsNode} lightsNode - The current lights node.
  38697. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38698. * @param {ClippingContext} clippingContext - The clipping context.
  38699. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38700. */
  38701. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  38702. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  38703. renderObject.drawRange = object.geometry.drawRange;
  38704. renderObject.group = group;
  38705. //
  38706. this._nodes.updateBefore( renderObject );
  38707. this._geometries.updateForRender( renderObject );
  38708. this._nodes.updateForRender( renderObject );
  38709. this._bindings.updateForRender( renderObject );
  38710. this._pipelines.getForRender( renderObject, this._compilationPromises );
  38711. this._nodes.updateAfter( renderObject );
  38712. }
  38713. /**
  38714. * Alias for `compileAsync()`.
  38715. *
  38716. * @method
  38717. * @param {Object3D} scene - The scene or 3D object to precompile.
  38718. * @param {Camera} camera - The camera that is used to render the scene.
  38719. * @param {Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  38720. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  38721. */
  38722. get compile() {
  38723. return this.compileAsync;
  38724. }
  38725. }
  38726. /**
  38727. * A binding represents the connection between a resource (like a texture, sampler
  38728. * or uniform buffer) and the resource definition in a shader stage.
  38729. *
  38730. * This module is an abstract base class for all concrete bindings types.
  38731. *
  38732. * @abstract
  38733. * @private
  38734. */
  38735. class Binding {
  38736. /**
  38737. * Constructs a new binding.
  38738. *
  38739. * @param {string} [name=''] - The binding's name.
  38740. */
  38741. constructor( name = '' ) {
  38742. /**
  38743. * The binding's name.
  38744. *
  38745. * @type {string}
  38746. */
  38747. this.name = name;
  38748. /**
  38749. * A bitmask that defines in what shader stages the
  38750. * binding's resource is accessible.
  38751. *
  38752. * @type {number}
  38753. */
  38754. this.visibility = 0;
  38755. }
  38756. /**
  38757. * Makes sure binding's resource is visible for the given shader stage.
  38758. *
  38759. * @param {number} visibility - The shader stage.
  38760. */
  38761. setVisibility( visibility ) {
  38762. this.visibility |= visibility;
  38763. }
  38764. /**
  38765. * Clones the binding.
  38766. *
  38767. * @return {Binding} The cloned binding.
  38768. */
  38769. clone() {
  38770. return Object.assign( new this.constructor(), this );
  38771. }
  38772. }
  38773. /**
  38774. * This function is usually called with the length in bytes of an array buffer.
  38775. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  38776. *
  38777. * @function
  38778. * @param {number} floatLength - The buffer length.
  38779. * @return {number} The padded length.
  38780. */
  38781. function getFloatLength( floatLength ) {
  38782. // ensure chunk size alignment (STD140 layout)
  38783. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  38784. }
  38785. /**
  38786. * Represents a buffer binding type.
  38787. *
  38788. * @private
  38789. * @abstract
  38790. * @augments Binding
  38791. */
  38792. class Buffer extends Binding {
  38793. /**
  38794. * Constructs a new buffer.
  38795. *
  38796. * @param {string} name - The buffer's name.
  38797. * @param {TypedArray} [buffer=null] - The buffer.
  38798. */
  38799. constructor( name, buffer = null ) {
  38800. super( name );
  38801. /**
  38802. * This flag can be used for type testing.
  38803. *
  38804. * @type {boolean}
  38805. * @readonly
  38806. * @default true
  38807. */
  38808. this.isBuffer = true;
  38809. /**
  38810. * The bytes per element.
  38811. *
  38812. * @type {number}
  38813. */
  38814. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  38815. /**
  38816. * A reference to the internal buffer.
  38817. *
  38818. * @private
  38819. * @type {TypedArray}
  38820. */
  38821. this._buffer = buffer;
  38822. }
  38823. /**
  38824. * The buffer's byte length.
  38825. *
  38826. * @type {number}
  38827. * @readonly
  38828. */
  38829. get byteLength() {
  38830. return getFloatLength( this._buffer.byteLength );
  38831. }
  38832. /**
  38833. * A reference to the internal buffer.
  38834. *
  38835. * @type {Float32Array}
  38836. * @readonly
  38837. */
  38838. get buffer() {
  38839. return this._buffer;
  38840. }
  38841. /**
  38842. * Updates the binding.
  38843. *
  38844. * @return {boolean} Whether the buffer has been updated and must be
  38845. * uploaded to the GPU.
  38846. */
  38847. update() {
  38848. return true;
  38849. }
  38850. }
  38851. /**
  38852. * Represents a uniform buffer binding type.
  38853. *
  38854. * @private
  38855. * @augments Buffer
  38856. */
  38857. class UniformBuffer extends Buffer {
  38858. /**
  38859. * Constructs a new uniform buffer.
  38860. *
  38861. * @param {string} name - The buffer's name.
  38862. * @param {TypedArray} [buffer=null] - The buffer.
  38863. */
  38864. constructor( name, buffer = null ) {
  38865. super( name, buffer );
  38866. /**
  38867. * This flag can be used for type testing.
  38868. *
  38869. * @type {boolean}
  38870. * @readonly
  38871. * @default true
  38872. */
  38873. this.isUniformBuffer = true;
  38874. }
  38875. }
  38876. let _id$4 = 0;
  38877. /**
  38878. * A special form of uniform buffer binding type.
  38879. * It's buffer value is managed by a node object.
  38880. *
  38881. * @private
  38882. * @augments UniformBuffer
  38883. */
  38884. class NodeUniformBuffer extends UniformBuffer {
  38885. /**
  38886. * Constructs a new node-based uniform buffer.
  38887. *
  38888. * @param {BufferNode} nodeUniform - The uniform buffer node.
  38889. * @param {UniformGroupNode} groupNode - The uniform group node.
  38890. */
  38891. constructor( nodeUniform, groupNode ) {
  38892. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  38893. /**
  38894. * The uniform buffer node.
  38895. *
  38896. * @type {BufferNode}
  38897. */
  38898. this.nodeUniform = nodeUniform;
  38899. /**
  38900. * The uniform group node.
  38901. *
  38902. * @type {UniformGroupNode}
  38903. */
  38904. this.groupNode = groupNode;
  38905. }
  38906. /**
  38907. * The uniform buffer.
  38908. *
  38909. * @type {Float32Array}
  38910. */
  38911. get buffer() {
  38912. return this.nodeUniform.value;
  38913. }
  38914. }
  38915. /**
  38916. * This class represents a uniform buffer binding but with
  38917. * an API that allows to maintain individual uniform objects.
  38918. *
  38919. * @private
  38920. * @augments UniformBuffer
  38921. */
  38922. class UniformsGroup extends UniformBuffer {
  38923. /**
  38924. * Constructs a new uniforms group.
  38925. *
  38926. * @param {string} name - The group's name.
  38927. */
  38928. constructor( name ) {
  38929. super( name );
  38930. /**
  38931. * This flag can be used for type testing.
  38932. *
  38933. * @type {boolean}
  38934. * @readonly
  38935. * @default true
  38936. */
  38937. this.isUniformsGroup = true;
  38938. /**
  38939. * An array with the raw uniform values.
  38940. *
  38941. * @private
  38942. * @type {?Array<number>}
  38943. * @default null
  38944. */
  38945. this._values = null;
  38946. /**
  38947. * An array of uniform objects.
  38948. *
  38949. * The order of uniforms in this array must match the order of uniforms in the shader.
  38950. *
  38951. * @type {Array<Uniform>}
  38952. */
  38953. this.uniforms = [];
  38954. }
  38955. /**
  38956. * Adds a uniform to this group.
  38957. *
  38958. * @param {Uniform} uniform - The uniform to add.
  38959. * @return {UniformsGroup} A reference to this group.
  38960. */
  38961. addUniform( uniform ) {
  38962. this.uniforms.push( uniform );
  38963. return this;
  38964. }
  38965. /**
  38966. * Removes a uniform from this group.
  38967. *
  38968. * @param {Uniform} uniform - The uniform to remove.
  38969. * @return {UniformsGroup} A reference to this group.
  38970. */
  38971. removeUniform( uniform ) {
  38972. const index = this.uniforms.indexOf( uniform );
  38973. if ( index !== -1 ) {
  38974. this.uniforms.splice( index, 1 );
  38975. }
  38976. return this;
  38977. }
  38978. /**
  38979. * An array with the raw uniform values.
  38980. *
  38981. * @type {Array<number>}
  38982. */
  38983. get values() {
  38984. if ( this._values === null ) {
  38985. this._values = Array.from( this.buffer );
  38986. }
  38987. return this._values;
  38988. }
  38989. /**
  38990. * A Float32 array buffer with the uniform values.
  38991. *
  38992. * @type {Float32Array}
  38993. */
  38994. get buffer() {
  38995. let buffer = this._buffer;
  38996. if ( buffer === null ) {
  38997. const byteLength = this.byteLength;
  38998. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  38999. this._buffer = buffer;
  39000. }
  39001. return buffer;
  39002. }
  39003. /**
  39004. * The byte length of the buffer with correct buffer alignment.
  39005. *
  39006. * @type {number}
  39007. */
  39008. get byteLength() {
  39009. const bytesPerElement = this.bytesPerElement;
  39010. let offset = 0; // global buffer offset in bytes
  39011. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  39012. const uniform = this.uniforms[ i ];
  39013. const boundary = uniform.boundary;
  39014. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  39015. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  39016. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  39017. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  39018. offset += chunkPadding;
  39019. // Check for chunk overflow
  39020. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  39021. // Add padding to the end of the chunk
  39022. offset += ( GPU_CHUNK_BYTES - chunkStart );
  39023. }
  39024. uniform.offset = offset / bytesPerElement;
  39025. offset += itemSize;
  39026. }
  39027. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  39028. }
  39029. /**
  39030. * Updates this group by updating each uniform object of
  39031. * the internal uniform list. The uniform objects check if their
  39032. * values has actually changed so this method only returns
  39033. * `true` if there is a real value change.
  39034. *
  39035. * @return {boolean} Whether the uniforms have been updated and
  39036. * must be uploaded to the GPU.
  39037. */
  39038. update() {
  39039. let updated = false;
  39040. for ( const uniform of this.uniforms ) {
  39041. if ( this.updateByType( uniform ) === true ) {
  39042. updated = true;
  39043. }
  39044. }
  39045. return updated;
  39046. }
  39047. /**
  39048. * Updates a given uniform by calling an update method matching
  39049. * the uniforms type.
  39050. *
  39051. * @param {Uniform} uniform - The uniform to update.
  39052. * @return {boolean} Whether the uniform has been updated or not.
  39053. */
  39054. updateByType( uniform ) {
  39055. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  39056. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  39057. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  39058. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  39059. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  39060. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  39061. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  39062. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  39063. }
  39064. /**
  39065. * Updates a given Number uniform.
  39066. *
  39067. * @param {NumberUniform} uniform - The Number uniform.
  39068. * @return {boolean} Whether the uniform has been updated or not.
  39069. */
  39070. updateNumber( uniform ) {
  39071. let updated = false;
  39072. const a = this.values;
  39073. const v = uniform.getValue();
  39074. const offset = uniform.offset;
  39075. const type = uniform.getType();
  39076. if ( a[ offset ] !== v ) {
  39077. const b = this._getBufferForType( type );
  39078. b[ offset ] = a[ offset ] = v;
  39079. updated = true;
  39080. }
  39081. return updated;
  39082. }
  39083. /**
  39084. * Updates a given Vector2 uniform.
  39085. *
  39086. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  39087. * @return {boolean} Whether the uniform has been updated or not.
  39088. */
  39089. updateVector2( uniform ) {
  39090. let updated = false;
  39091. const a = this.values;
  39092. const v = uniform.getValue();
  39093. const offset = uniform.offset;
  39094. const type = uniform.getType();
  39095. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  39096. const b = this._getBufferForType( type );
  39097. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39098. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39099. updated = true;
  39100. }
  39101. return updated;
  39102. }
  39103. /**
  39104. * Updates a given Vector3 uniform.
  39105. *
  39106. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  39107. * @return {boolean} Whether the uniform has been updated or not.
  39108. */
  39109. updateVector3( uniform ) {
  39110. let updated = false;
  39111. const a = this.values;
  39112. const v = uniform.getValue();
  39113. const offset = uniform.offset;
  39114. const type = uniform.getType();
  39115. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  39116. const b = this._getBufferForType( type );
  39117. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39118. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39119. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  39120. updated = true;
  39121. }
  39122. return updated;
  39123. }
  39124. /**
  39125. * Updates a given Vector4 uniform.
  39126. *
  39127. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  39128. * @return {boolean} Whether the uniform has been updated or not.
  39129. */
  39130. updateVector4( uniform ) {
  39131. let updated = false;
  39132. const a = this.values;
  39133. const v = uniform.getValue();
  39134. const offset = uniform.offset;
  39135. const type = uniform.getType();
  39136. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  39137. const b = this._getBufferForType( type );
  39138. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39139. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39140. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  39141. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  39142. updated = true;
  39143. }
  39144. return updated;
  39145. }
  39146. /**
  39147. * Updates a given Color uniform.
  39148. *
  39149. * @param {ColorUniform} uniform - The Color uniform.
  39150. * @return {boolean} Whether the uniform has been updated or not.
  39151. */
  39152. updateColor( uniform ) {
  39153. let updated = false;
  39154. const a = this.values;
  39155. const c = uniform.getValue();
  39156. const offset = uniform.offset;
  39157. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  39158. const b = this.buffer;
  39159. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  39160. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  39161. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  39162. updated = true;
  39163. }
  39164. return updated;
  39165. }
  39166. /**
  39167. * Updates a given Matrix3 uniform.
  39168. *
  39169. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  39170. * @return {boolean} Whether the uniform has been updated or not.
  39171. */
  39172. updateMatrix3( uniform ) {
  39173. let updated = false;
  39174. const a = this.values;
  39175. const e = uniform.getValue().elements;
  39176. const offset = uniform.offset;
  39177. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  39178. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  39179. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  39180. const b = this.buffer;
  39181. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  39182. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  39183. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  39184. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  39185. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  39186. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  39187. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  39188. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  39189. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  39190. updated = true;
  39191. }
  39192. return updated;
  39193. }
  39194. /**
  39195. * Updates a given Matrix4 uniform.
  39196. *
  39197. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  39198. * @return {boolean} Whether the uniform has been updated or not.
  39199. */
  39200. updateMatrix4( uniform ) {
  39201. let updated = false;
  39202. const a = this.values;
  39203. const e = uniform.getValue().elements;
  39204. const offset = uniform.offset;
  39205. if ( arraysEqual( a, e, offset ) === false ) {
  39206. const b = this.buffer;
  39207. b.set( e, offset );
  39208. setArray( a, e, offset );
  39209. updated = true;
  39210. }
  39211. return updated;
  39212. }
  39213. /**
  39214. * Returns a typed array that matches the given data type.
  39215. *
  39216. * @param {string} type - The data type.
  39217. * @return {TypedArray} The typed array.
  39218. */
  39219. _getBufferForType( type ) {
  39220. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  39221. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  39222. return this.buffer;
  39223. }
  39224. }
  39225. /**
  39226. * Sets the values of the second array to the first array.
  39227. *
  39228. * @private
  39229. * @param {TypedArray} a - The first array.
  39230. * @param {TypedArray} b - The second array.
  39231. * @param {number} offset - An index offset for the first array.
  39232. */
  39233. function setArray( a, b, offset ) {
  39234. for ( let i = 0, l = b.length; i < l; i ++ ) {
  39235. a[ offset + i ] = b[ i ];
  39236. }
  39237. }
  39238. /**
  39239. * Returns `true` if the given arrays are equal.
  39240. *
  39241. * @private
  39242. * @param {TypedArray} a - The first array.
  39243. * @param {TypedArray} b - The second array.
  39244. * @param {number} offset - An index offset for the first array.
  39245. * @return {boolean} Whether the given arrays are equal or not.
  39246. */
  39247. function arraysEqual( a, b, offset ) {
  39248. for ( let i = 0, l = b.length; i < l; i ++ ) {
  39249. if ( a[ offset + i ] !== b[ i ] ) return false;
  39250. }
  39251. return true;
  39252. }
  39253. let _id$3 = 0;
  39254. /**
  39255. * A special form of uniforms group that represents
  39256. * the individual uniforms as node-based uniforms.
  39257. *
  39258. * @private
  39259. * @augments UniformsGroup
  39260. */
  39261. class NodeUniformsGroup extends UniformsGroup {
  39262. /**
  39263. * Constructs a new node-based uniforms group.
  39264. *
  39265. * @param {string} name - The group's name.
  39266. * @param {UniformGroupNode} groupNode - The uniform group node.
  39267. */
  39268. constructor( name, groupNode ) {
  39269. super( name );
  39270. /**
  39271. * The group's ID.
  39272. *
  39273. * @type {number}
  39274. */
  39275. this.id = _id$3 ++;
  39276. /**
  39277. * The uniform group node.
  39278. *
  39279. * @type {UniformGroupNode}
  39280. */
  39281. this.groupNode = groupNode;
  39282. /**
  39283. * This flag can be used for type testing.
  39284. *
  39285. * @type {boolean}
  39286. * @readonly
  39287. * @default true
  39288. */
  39289. this.isNodeUniformsGroup = true;
  39290. }
  39291. }
  39292. let _id$2 = 0;
  39293. /**
  39294. * Represents a sampled texture binding type.
  39295. *
  39296. * @private
  39297. * @augments Binding
  39298. */
  39299. class SampledTexture extends Binding {
  39300. /**
  39301. * Constructs a new sampled texture.
  39302. *
  39303. * @param {string} name - The sampled texture's name.
  39304. * @param {?Texture} texture - The texture this binding is referring to.
  39305. */
  39306. constructor( name, texture ) {
  39307. super( name );
  39308. /**
  39309. * This identifier.
  39310. *
  39311. * @type {number}
  39312. */
  39313. this.id = _id$2 ++;
  39314. /**
  39315. * The texture this binding is referring to.
  39316. *
  39317. * @type {?Texture}
  39318. */
  39319. this.texture = texture;
  39320. /**
  39321. * The binding's version.
  39322. *
  39323. * @type {number}
  39324. */
  39325. this.version = texture ? texture.version : 0;
  39326. /**
  39327. * Whether the texture is a storage texture or not.
  39328. *
  39329. * @type {boolean}
  39330. * @default false
  39331. */
  39332. this.store = false;
  39333. /**
  39334. * The binding's generation which is an additional version
  39335. * qualifier.
  39336. *
  39337. * @type {?number}
  39338. * @default null
  39339. */
  39340. this.generation = null;
  39341. /**
  39342. * This flag can be used for type testing.
  39343. *
  39344. * @type {boolean}
  39345. * @readonly
  39346. * @default true
  39347. */
  39348. this.isSampledTexture = true;
  39349. }
  39350. /**
  39351. * Returns `true` whether this binding requires an update for the
  39352. * given generation.
  39353. *
  39354. * @param {number} generation - The generation.
  39355. * @return {boolean} Whether an update is required or not.
  39356. */
  39357. needsBindingsUpdate( generation ) {
  39358. const { texture } = this;
  39359. if ( generation !== this.generation ) {
  39360. this.generation = generation;
  39361. return true;
  39362. }
  39363. return texture.isVideoTexture;
  39364. }
  39365. /**
  39366. * Updates the binding.
  39367. *
  39368. * @return {boolean} Whether the texture has been updated and must be
  39369. * uploaded to the GPU.
  39370. */
  39371. update() {
  39372. const { texture, version } = this;
  39373. if ( version !== texture.version ) {
  39374. this.version = texture.version;
  39375. return true;
  39376. }
  39377. return false;
  39378. }
  39379. }
  39380. /**
  39381. * A special form of sampled texture binding type.
  39382. * It's texture value is managed by a node object.
  39383. *
  39384. * @private
  39385. * @augments SampledTexture
  39386. */
  39387. class NodeSampledTexture extends SampledTexture {
  39388. /**
  39389. * Constructs a new node-based sampled texture.
  39390. *
  39391. * @param {string} name - The textures's name.
  39392. * @param {TextureNode} textureNode - The texture node.
  39393. * @param {UniformGroupNode} groupNode - The uniform group node.
  39394. * @param {?string} [access=null] - The access type.
  39395. */
  39396. constructor( name, textureNode, groupNode, access = null ) {
  39397. super( name, textureNode ? textureNode.value : null );
  39398. /**
  39399. * The texture node.
  39400. *
  39401. * @type {TextureNode}
  39402. */
  39403. this.textureNode = textureNode;
  39404. /**
  39405. * The uniform group node.
  39406. *
  39407. * @type {UniformGroupNode}
  39408. */
  39409. this.groupNode = groupNode;
  39410. /**
  39411. * The access type.
  39412. *
  39413. * @type {?string}
  39414. * @default null
  39415. */
  39416. this.access = access;
  39417. }
  39418. /**
  39419. * Overwrites the default to additionally check if the node value has changed.
  39420. *
  39421. * @param {number} generation - The generation.
  39422. * @return {boolean} Whether an update is required or not.
  39423. */
  39424. needsBindingsUpdate( generation ) {
  39425. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  39426. }
  39427. /**
  39428. * Updates the binding.
  39429. *
  39430. * @return {boolean} Whether the texture has been updated and must be
  39431. * uploaded to the GPU.
  39432. */
  39433. update() {
  39434. const { textureNode } = this;
  39435. if ( this.texture !== textureNode.value ) {
  39436. this.texture = textureNode.value;
  39437. return true;
  39438. }
  39439. return super.update();
  39440. }
  39441. }
  39442. /**
  39443. * A special form of sampled cube texture binding type.
  39444. * It's texture value is managed by a node object.
  39445. *
  39446. * @private
  39447. * @augments NodeSampledTexture
  39448. */
  39449. class NodeSampledCubeTexture extends NodeSampledTexture {
  39450. /**
  39451. * Constructs a new node-based sampled cube texture.
  39452. *
  39453. * @param {string} name - The textures's name.
  39454. * @param {TextureNode} textureNode - The texture node.
  39455. * @param {UniformGroupNode} groupNode - The uniform group node.
  39456. * @param {?string} [access=null] - The access type.
  39457. */
  39458. constructor( name, textureNode, groupNode, access = null ) {
  39459. super( name, textureNode, groupNode, access );
  39460. /**
  39461. * This flag can be used for type testing.
  39462. *
  39463. * @type {boolean}
  39464. * @readonly
  39465. * @default true
  39466. */
  39467. this.isSampledCubeTexture = true;
  39468. }
  39469. }
  39470. /**
  39471. * A special form of sampled 3D texture binding type.
  39472. * It's texture value is managed by a node object.
  39473. *
  39474. * @private
  39475. * @augments NodeSampledTexture
  39476. */
  39477. class NodeSampledTexture3D extends NodeSampledTexture {
  39478. /**
  39479. * Constructs a new node-based sampled 3D texture.
  39480. *
  39481. * @param {string} name - The textures's name.
  39482. * @param {TextureNode} textureNode - The texture node.
  39483. * @param {UniformGroupNode} groupNode - The uniform group node.
  39484. * @param {?string} [access=null] - The access type.
  39485. */
  39486. constructor( name, textureNode, groupNode, access = null ) {
  39487. super( name, textureNode, groupNode, access );
  39488. /**
  39489. * This flag can be used for type testing.
  39490. *
  39491. * @type {boolean}
  39492. * @readonly
  39493. * @default true
  39494. */
  39495. this.isSampledTexture3D = true;
  39496. }
  39497. }
  39498. const glslMethods = {
  39499. textureDimensions: 'textureSize',
  39500. equals: 'equal'
  39501. };
  39502. const precisionLib = {
  39503. low: 'lowp',
  39504. medium: 'mediump',
  39505. high: 'highp'
  39506. };
  39507. const supports$1 = {
  39508. swizzleAssign: true,
  39509. storageBuffer: false
  39510. };
  39511. const interpolationTypeMap = {
  39512. perspective: 'smooth',
  39513. linear: 'noperspective'
  39514. };
  39515. const interpolationModeMap = {
  39516. 'centroid': 'centroid',
  39517. 'flat first': 'flat',
  39518. 'flat either': 'flat'
  39519. };
  39520. const defaultPrecisions = `
  39521. precision highp float;
  39522. precision highp int;
  39523. precision highp sampler2D;
  39524. precision highp sampler3D;
  39525. precision highp samplerCube;
  39526. precision highp sampler2DArray;
  39527. precision highp usampler2D;
  39528. precision highp usampler3D;
  39529. precision highp usamplerCube;
  39530. precision highp usampler2DArray;
  39531. precision highp isampler2D;
  39532. precision highp isampler3D;
  39533. precision highp isamplerCube;
  39534. precision highp isampler2DArray;
  39535. precision lowp sampler2DShadow;
  39536. precision lowp sampler2DArrayShadow;
  39537. precision lowp samplerCubeShadow;
  39538. `;
  39539. /**
  39540. * A node builder targeting GLSL.
  39541. *
  39542. * This module generates GLSL shader code from node materials and also
  39543. * generates the respective bindings and vertex buffer definitions. These
  39544. * data are later used by the renderer to create render and compute pipelines
  39545. * for render objects.
  39546. *
  39547. * @augments NodeBuilder
  39548. */
  39549. class GLSLNodeBuilder extends NodeBuilder {
  39550. /**
  39551. * Constructs a new GLSL node builder renderer.
  39552. *
  39553. * @param {Object3D} object - The 3D object.
  39554. * @param {Renderer} renderer - The renderer.
  39555. */
  39556. constructor( object, renderer ) {
  39557. super( object, renderer, new GLSLNodeParser() );
  39558. /**
  39559. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  39560. * another dictionary which manages UBOs per group ('render','frame','object').
  39561. *
  39562. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  39563. */
  39564. this.uniformGroups = {};
  39565. /**
  39566. * An array that holds objects defining the varying and attribute data in
  39567. * context of Transform Feedback.
  39568. *
  39569. * @type {Array<Object<string,AttributeNode|string>>}
  39570. */
  39571. this.transforms = [];
  39572. /**
  39573. * A dictionary that holds for each shader stage a Map of used extensions.
  39574. *
  39575. * @type {Object<string,Map<string,Object>>}
  39576. */
  39577. this.extensions = {};
  39578. /**
  39579. * A dictionary that holds for each shader stage an Array of used builtins.
  39580. *
  39581. * @type {Object<string,Array<string>>}
  39582. */
  39583. this.builtins = { vertex: [], fragment: [], compute: [] };
  39584. }
  39585. /**
  39586. * Checks if the given texture requires a manual conversion to the working color space.
  39587. *
  39588. * @param {Texture} texture - The texture to check.
  39589. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  39590. */
  39591. needsToWorkingColorSpace( texture ) {
  39592. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  39593. }
  39594. /**
  39595. * Returns the native shader method name for a given generic name.
  39596. *
  39597. * @param {string} method - The method name to resolve.
  39598. * @return {string} The resolved GLSL method name.
  39599. */
  39600. getMethod( method ) {
  39601. return glslMethods[ method ] || method;
  39602. }
  39603. /**
  39604. * Returns the output struct name. Not relevant for GLSL.
  39605. *
  39606. * @return {string}
  39607. */
  39608. getOutputStructName() {
  39609. return '';
  39610. }
  39611. /**
  39612. * Builds the given shader node.
  39613. *
  39614. * @param {ShaderNodeInternal} shaderNode - The shader node.
  39615. * @return {string} The GLSL function code.
  39616. */
  39617. buildFunctionCode( shaderNode ) {
  39618. const layout = shaderNode.layout;
  39619. const flowData = this.flowShaderNode( shaderNode );
  39620. const parameters = [];
  39621. for ( const input of layout.inputs ) {
  39622. parameters.push( this.getType( input.type ) + ' ' + input.name );
  39623. }
  39624. //
  39625. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  39626. ${ flowData.vars }
  39627. ${ flowData.code }
  39628. return ${ flowData.result };
  39629. }`;
  39630. //
  39631. return code;
  39632. }
  39633. /**
  39634. * Setups the Pixel Buffer Object (PBO) for the given storage
  39635. * buffer node.
  39636. *
  39637. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  39638. */
  39639. setupPBO( storageBufferNode ) {
  39640. const attribute = storageBufferNode.value;
  39641. if ( attribute.pbo === undefined ) {
  39642. const originalArray = attribute.array;
  39643. const numElements = attribute.count * attribute.itemSize;
  39644. const { itemSize } = attribute;
  39645. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  39646. let format = isInteger ? RedIntegerFormat : RedFormat;
  39647. if ( itemSize === 2 ) {
  39648. format = isInteger ? RGIntegerFormat : RGFormat;
  39649. } else if ( itemSize === 3 ) {
  39650. format = isInteger ? RGBIntegerFormat : RGBFormat;
  39651. } else if ( itemSize === 4 ) {
  39652. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  39653. }
  39654. const typeMap = {
  39655. Float32Array: FloatType,
  39656. Uint8Array: UnsignedByteType,
  39657. Uint16Array: UnsignedShortType,
  39658. Uint32Array: UnsignedIntType,
  39659. Int8Array: ByteType,
  39660. Int16Array: ShortType,
  39661. Int32Array: IntType,
  39662. Uint8ClampedArray: UnsignedByteType,
  39663. };
  39664. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  39665. let height = Math.ceil( ( numElements / itemSize ) / width );
  39666. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  39667. const newSize = width * height * itemSize;
  39668. const newArray = new originalArray.constructor( newSize );
  39669. newArray.set( originalArray, 0 );
  39670. attribute.array = newArray;
  39671. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  39672. pboTexture.needsUpdate = true;
  39673. pboTexture.isPBOTexture = true;
  39674. const pbo = new TextureNode( pboTexture, null, null );
  39675. pbo.setPrecision( 'high' );
  39676. attribute.pboNode = pbo;
  39677. attribute.pbo = pbo.value;
  39678. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39679. }
  39680. }
  39681. /**
  39682. * Returns a GLSL snippet that represents the property name of the given node.
  39683. *
  39684. * @param {Node} node - The node.
  39685. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  39686. * @return {string} The property name.
  39687. */
  39688. getPropertyName( node, shaderStage = this.shaderStage ) {
  39689. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  39690. return shaderStage.charAt( 0 ) + '_' + node.name;
  39691. }
  39692. return super.getPropertyName( node, shaderStage );
  39693. }
  39694. /**
  39695. * Setups the Pixel Buffer Object (PBO) for the given storage
  39696. * buffer node.
  39697. *
  39698. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  39699. * @return {string} The property name.
  39700. */
  39701. generatePBO( storageArrayElementNode ) {
  39702. const { node, indexNode } = storageArrayElementNode;
  39703. const attribute = node.value;
  39704. if ( this.renderer.backend.has( attribute ) ) {
  39705. const attributeData = this.renderer.backend.get( attribute );
  39706. attributeData.pbo = attribute.pbo;
  39707. }
  39708. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39709. const textureName = this.getPropertyName( nodeUniform );
  39710. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  39711. const indexSnippet = indexNode.build( this, 'uint' );
  39712. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  39713. let propertyName = elementNodeData.propertyName;
  39714. if ( propertyName === undefined ) {
  39715. // property element
  39716. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  39717. propertyName = this.getPropertyName( nodeVar );
  39718. // property size
  39719. const bufferNodeData = this.getDataFromNode( node );
  39720. let propertySizeName = bufferNodeData.propertySizeName;
  39721. if ( propertySizeName === undefined ) {
  39722. propertySizeName = propertyName + 'Size';
  39723. this.getVarFromNode( node, propertySizeName, 'uint' );
  39724. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  39725. bufferNodeData.propertySizeName = propertySizeName;
  39726. }
  39727. //
  39728. const { itemSize } = attribute;
  39729. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  39730. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  39731. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  39732. //
  39733. let prefix = 'vec4';
  39734. if ( attribute.pbo.type === UnsignedIntType ) {
  39735. prefix = 'uvec4';
  39736. } else if ( attribute.pbo.type === IntType ) {
  39737. prefix = 'ivec4';
  39738. }
  39739. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  39740. elementNodeData.propertyName = propertyName;
  39741. }
  39742. return propertyName;
  39743. }
  39744. /**
  39745. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  39746. *
  39747. * @param {Texture} texture - The texture.
  39748. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39749. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39750. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  39751. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  39752. * @return {string} The GLSL snippet.
  39753. */
  39754. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  39755. if ( depthSnippet ) {
  39756. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  39757. } else {
  39758. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  39759. }
  39760. }
  39761. /**
  39762. * Generates the GLSL snippet for sampling/loading the given texture.
  39763. *
  39764. * @param {Texture} texture - The texture.
  39765. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39766. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39767. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  39768. * @return {string} The GLSL snippet.
  39769. */
  39770. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  39771. if ( texture.isDepthTexture ) {
  39772. if ( depthSnippet ) uvSnippet = `vec4( ${ uvSnippet }, ${ depthSnippet } )`;
  39773. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  39774. } else {
  39775. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  39776. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  39777. }
  39778. }
  39779. /**
  39780. * Generates the GLSL snippet when sampling textures with explicit mip level.
  39781. *
  39782. * @param {Texture} texture - The texture.
  39783. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39784. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39785. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  39786. * @return {string} The GLSL snippet.
  39787. */
  39788. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  39789. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  39790. }
  39791. /**
  39792. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  39793. *
  39794. * @param {Texture} texture - The texture.
  39795. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39796. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39797. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  39798. * @return {string} The GLSL snippet.
  39799. */
  39800. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  39801. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  39802. }
  39803. /**
  39804. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  39805. *
  39806. * @param {Texture} texture - The texture.
  39807. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39808. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39809. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  39810. * @return {string} The GLSL snippet.
  39811. */
  39812. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  39813. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  39814. }
  39815. /**
  39816. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  39817. * against a reference value.
  39818. *
  39819. * @param {Texture} texture - The texture.
  39820. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39821. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39822. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  39823. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  39824. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  39825. * @return {string} The GLSL snippet.
  39826. */
  39827. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  39828. if ( shaderStage === 'fragment' ) {
  39829. if ( depthSnippet ) {
  39830. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  39831. }
  39832. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  39833. } else {
  39834. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  39835. }
  39836. }
  39837. /**
  39838. * Returns the variables of the given shader stage as a GLSL string.
  39839. *
  39840. * @param {string} shaderStage - The shader stage.
  39841. * @return {string} The GLSL snippet that defines the variables.
  39842. */
  39843. getVars( shaderStage ) {
  39844. const snippets = [];
  39845. const vars = this.vars[ shaderStage ];
  39846. if ( vars !== undefined ) {
  39847. for ( const variable of vars ) {
  39848. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  39849. }
  39850. }
  39851. return snippets.join( '\n\t' );
  39852. }
  39853. /**
  39854. * Returns the uniforms of the given shader stage as a GLSL string.
  39855. *
  39856. * @param {string} shaderStage - The shader stage.
  39857. * @return {string} The GLSL snippet that defines the uniforms.
  39858. */
  39859. getUniforms( shaderStage ) {
  39860. const uniforms = this.uniforms[ shaderStage ];
  39861. const bindingSnippets = [];
  39862. const uniformGroups = {};
  39863. for ( const uniform of uniforms ) {
  39864. let snippet = null;
  39865. let group = false;
  39866. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  39867. const texture = uniform.node.value;
  39868. let typePrefix = '';
  39869. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  39870. if ( texture.type === UnsignedIntType ) {
  39871. typePrefix = 'u';
  39872. } else if ( texture.type === IntType ) {
  39873. typePrefix = 'i';
  39874. }
  39875. }
  39876. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  39877. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  39878. } else if ( texture.compareFunction ) {
  39879. if ( texture.isArrayTexture === true ) {
  39880. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  39881. } else {
  39882. snippet = `sampler2DShadow ${ uniform.name };`;
  39883. }
  39884. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39885. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  39886. } else {
  39887. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  39888. }
  39889. } else if ( uniform.type === 'cubeTexture' ) {
  39890. snippet = `samplerCube ${ uniform.name };`;
  39891. } else if ( uniform.type === 'buffer' ) {
  39892. const bufferNode = uniform.node;
  39893. const bufferType = this.getType( bufferNode.bufferType );
  39894. const bufferCount = bufferNode.bufferCount;
  39895. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  39896. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  39897. } else {
  39898. const vectorType = this.getVectorType( uniform.type );
  39899. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  39900. group = true;
  39901. }
  39902. const precision = uniform.node.precision;
  39903. if ( precision !== null ) {
  39904. snippet = precisionLib[ precision ] + ' ' + snippet;
  39905. }
  39906. if ( group ) {
  39907. snippet = '\t' + snippet;
  39908. const groupName = uniform.groupNode.name;
  39909. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  39910. groupSnippets.push( snippet );
  39911. } else {
  39912. snippet = 'uniform ' + snippet;
  39913. bindingSnippets.push( snippet );
  39914. }
  39915. }
  39916. let output = '';
  39917. for ( const name in uniformGroups ) {
  39918. const groupSnippets = uniformGroups[ name ];
  39919. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  39920. }
  39921. output += bindingSnippets.join( '\n' );
  39922. return output;
  39923. }
  39924. /**
  39925. * Returns the type for a given buffer attribute.
  39926. *
  39927. * @param {BufferAttribute} attribute - The buffer attribute.
  39928. * @return {string} The type.
  39929. */
  39930. getTypeFromAttribute( attribute ) {
  39931. let nodeType = super.getTypeFromAttribute( attribute );
  39932. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  39933. let dataAttribute = attribute;
  39934. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  39935. const array = dataAttribute.array;
  39936. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  39937. nodeType = nodeType.slice( 1 );
  39938. }
  39939. }
  39940. return nodeType;
  39941. }
  39942. /**
  39943. * Returns the shader attributes of the given shader stage as a GLSL string.
  39944. *
  39945. * @param {string} shaderStage - The shader stage.
  39946. * @return {string} The GLSL snippet that defines the shader attributes.
  39947. */
  39948. getAttributes( shaderStage ) {
  39949. let snippet = '';
  39950. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39951. const attributes = this.getAttributesArray();
  39952. let location = 0;
  39953. for ( const attribute of attributes ) {
  39954. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  39955. }
  39956. }
  39957. return snippet;
  39958. }
  39959. /**
  39960. * Returns the members of the given struct type node as a GLSL string.
  39961. *
  39962. * @param {StructTypeNode} struct - The struct type node.
  39963. * @return {string} The GLSL snippet that defines the struct members.
  39964. */
  39965. getStructMembers( struct ) {
  39966. const snippets = [];
  39967. for ( const member of struct.members ) {
  39968. snippets.push( `\t${ member.type } ${ member.name };` );
  39969. }
  39970. return snippets.join( '\n' );
  39971. }
  39972. /**
  39973. * Returns the structs of the given shader stage as a GLSL string.
  39974. *
  39975. * @param {string} shaderStage - The shader stage.
  39976. * @return {string} The GLSL snippet that defines the structs.
  39977. */
  39978. getStructs( shaderStage ) {
  39979. const snippets = [];
  39980. const structs = this.structs[ shaderStage ];
  39981. const outputSnippet = [];
  39982. for ( const struct of structs ) {
  39983. if ( struct.output ) {
  39984. for ( const member of struct.members ) {
  39985. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  39986. }
  39987. } else {
  39988. let snippet = 'struct ' + struct.name + ' {\n';
  39989. snippet += this.getStructMembers( struct );
  39990. snippet += '\n};\n';
  39991. snippets.push( snippet );
  39992. }
  39993. }
  39994. if ( outputSnippet.length === 0 ) {
  39995. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  39996. }
  39997. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  39998. }
  39999. /**
  40000. * Returns the varyings of the given shader stage as a GLSL string.
  40001. *
  40002. * @param {string} shaderStage - The shader stage.
  40003. * @return {string} The GLSL snippet that defines the varyings.
  40004. */
  40005. getVaryings( shaderStage ) {
  40006. let snippet = '';
  40007. const varyings = this.varyings;
  40008. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  40009. for ( const varying of varyings ) {
  40010. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  40011. const type = this.getType( varying.type );
  40012. if ( varying.needsInterpolation ) {
  40013. if ( varying.interpolationType ) {
  40014. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  40015. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  40016. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  40017. } else {
  40018. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  40019. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  40020. }
  40021. } else {
  40022. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  40023. }
  40024. }
  40025. } else if ( shaderStage === 'fragment' ) {
  40026. for ( const varying of varyings ) {
  40027. if ( varying.needsInterpolation ) {
  40028. const type = this.getType( varying.type );
  40029. if ( varying.interpolationType ) {
  40030. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  40031. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  40032. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  40033. } else {
  40034. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  40035. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  40036. }
  40037. }
  40038. }
  40039. }
  40040. for ( const builtin of this.builtins[ shaderStage ] ) {
  40041. snippet += `${builtin};\n`;
  40042. }
  40043. return snippet;
  40044. }
  40045. /**
  40046. * Returns the vertex index builtin.
  40047. *
  40048. * @return {string} The vertex index.
  40049. */
  40050. getVertexIndex() {
  40051. return 'uint( gl_VertexID )';
  40052. }
  40053. /**
  40054. * Returns the instance index builtin.
  40055. *
  40056. * @return {string} The instance index.
  40057. */
  40058. getInstanceIndex() {
  40059. return 'uint( gl_InstanceID )';
  40060. }
  40061. /**
  40062. * Returns the invocation local index builtin.
  40063. *
  40064. * @return {string} The invocation local index.
  40065. */
  40066. getInvocationLocalIndex() {
  40067. const workgroupSize = this.object.workgroupSize;
  40068. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  40069. return `uint( gl_InstanceID ) % ${size}u`;
  40070. }
  40071. /**
  40072. * Returns the draw index builtin.
  40073. *
  40074. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  40075. */
  40076. getDrawIndex() {
  40077. const extensions = this.renderer.backend.extensions;
  40078. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  40079. return 'uint( gl_DrawID )';
  40080. }
  40081. return null;
  40082. }
  40083. /**
  40084. * Returns the front facing builtin.
  40085. *
  40086. * @return {string} The front facing builtin.
  40087. */
  40088. getFrontFacing() {
  40089. return 'gl_FrontFacing';
  40090. }
  40091. /**
  40092. * Returns the frag coord builtin.
  40093. *
  40094. * @return {string} The frag coord builtin.
  40095. */
  40096. getFragCoord() {
  40097. return 'gl_FragCoord.xy';
  40098. }
  40099. /**
  40100. * Returns the frag depth builtin.
  40101. *
  40102. * @return {string} The frag depth builtin.
  40103. */
  40104. getFragDepth() {
  40105. return 'gl_FragDepth';
  40106. }
  40107. /**
  40108. * Enables the given extension.
  40109. *
  40110. * @param {string} name - The extension name.
  40111. * @param {string} behavior - The extension behavior.
  40112. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  40113. */
  40114. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  40115. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  40116. if ( map.has( name ) === false ) {
  40117. map.set( name, {
  40118. name,
  40119. behavior
  40120. } );
  40121. }
  40122. }
  40123. /**
  40124. * Returns the enabled extensions of the given shader stage as a GLSL string.
  40125. *
  40126. * @param {string} shaderStage - The shader stage.
  40127. * @return {string} The GLSL snippet that defines the enabled extensions.
  40128. */
  40129. getExtensions( shaderStage ) {
  40130. const snippets = [];
  40131. if ( shaderStage === 'vertex' ) {
  40132. const ext = this.renderer.backend.extensions;
  40133. const isBatchedMesh = this.object.isBatchedMesh;
  40134. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  40135. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  40136. }
  40137. }
  40138. const extensions = this.extensions[ shaderStage ];
  40139. if ( extensions !== undefined ) {
  40140. for ( const { name, behavior } of extensions.values() ) {
  40141. snippets.push( `#extension ${name} : ${behavior}` );
  40142. }
  40143. }
  40144. return snippets.join( '\n' );
  40145. }
  40146. /**
  40147. * Returns the clip distances builtin.
  40148. *
  40149. * @return {string} The clip distances builtin.
  40150. */
  40151. getClipDistance() {
  40152. return 'gl_ClipDistance';
  40153. }
  40154. /**
  40155. * Whether the requested feature is available or not.
  40156. *
  40157. * @param {string} name - The requested feature.
  40158. * @return {boolean} Whether the requested feature is supported or not.
  40159. */
  40160. isAvailable( name ) {
  40161. let result = supports$1[ name ];
  40162. if ( result === undefined ) {
  40163. let extensionName;
  40164. result = false;
  40165. switch ( name ) {
  40166. case 'float32Filterable':
  40167. extensionName = 'OES_texture_float_linear';
  40168. break;
  40169. case 'clipDistance':
  40170. extensionName = 'WEBGL_clip_cull_distance';
  40171. break;
  40172. }
  40173. if ( extensionName !== undefined ) {
  40174. const extensions = this.renderer.backend.extensions;
  40175. if ( extensions.has( extensionName ) ) {
  40176. extensions.get( extensionName );
  40177. result = true;
  40178. }
  40179. }
  40180. supports$1[ name ] = result;
  40181. }
  40182. return result;
  40183. }
  40184. /**
  40185. * Whether to flip texture data along its vertical axis or not.
  40186. *
  40187. * @return {boolean} Returns always `true` in context of GLSL.
  40188. */
  40189. isFlipY() {
  40190. return true;
  40191. }
  40192. /**
  40193. * Enables hardware clipping.
  40194. *
  40195. * @param {string} planeCount - The clipping plane count.
  40196. */
  40197. enableHardwareClipping( planeCount ) {
  40198. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  40199. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  40200. }
  40201. /**
  40202. * Enables multiview.
  40203. */
  40204. enableMultiview() {
  40205. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  40206. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  40207. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  40208. }
  40209. /**
  40210. * Registers a transform in context of Transform Feedback.
  40211. *
  40212. * @param {string} varyingName - The varying name.
  40213. * @param {AttributeNode} attributeNode - The attribute node.
  40214. */
  40215. registerTransform( varyingName, attributeNode ) {
  40216. this.transforms.push( { varyingName, attributeNode } );
  40217. }
  40218. /**
  40219. * Returns the transforms of the given shader stage as a GLSL string.
  40220. *
  40221. * @param {string} shaderStage - The shader stage.
  40222. * @return {string} The GLSL snippet that defines the transforms.
  40223. */
  40224. getTransforms( /* shaderStage */ ) {
  40225. const transforms = this.transforms;
  40226. let snippet = '';
  40227. for ( let i = 0; i < transforms.length; i ++ ) {
  40228. const transform = transforms[ i ];
  40229. const attributeName = this.getPropertyName( transform.attributeNode );
  40230. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  40231. }
  40232. return snippet;
  40233. }
  40234. /**
  40235. * Returns a GLSL struct based on the given name and variables.
  40236. *
  40237. * @private
  40238. * @param {string} name - The struct name.
  40239. * @param {string} vars - The struct variables.
  40240. * @return {string} The GLSL snippet representing a struct.
  40241. */
  40242. _getGLSLUniformStruct( name, vars ) {
  40243. return `
  40244. layout( std140 ) uniform ${name} {
  40245. ${vars}
  40246. };`;
  40247. }
  40248. /**
  40249. * Returns a GLSL vertex shader based on the given shader data.
  40250. *
  40251. * @private
  40252. * @param {Object} shaderData - The shader data.
  40253. * @return {string} The vertex shader.
  40254. */
  40255. _getGLSLVertexCode( shaderData ) {
  40256. return `#version 300 es
  40257. ${ this.getSignature() }
  40258. // extensions
  40259. ${shaderData.extensions}
  40260. // precision
  40261. ${ defaultPrecisions }
  40262. // uniforms
  40263. ${shaderData.uniforms}
  40264. // varyings
  40265. ${shaderData.varyings}
  40266. // attributes
  40267. ${shaderData.attributes}
  40268. // codes
  40269. ${shaderData.codes}
  40270. void main() {
  40271. // vars
  40272. ${shaderData.vars}
  40273. // transforms
  40274. ${shaderData.transforms}
  40275. // flow
  40276. ${shaderData.flow}
  40277. gl_PointSize = 1.0;
  40278. }
  40279. `;
  40280. }
  40281. /**
  40282. * Returns a GLSL fragment shader based on the given shader data.
  40283. *
  40284. * @private
  40285. * @param {Object} shaderData - The shader data.
  40286. * @return {string} The vertex shader.
  40287. */
  40288. _getGLSLFragmentCode( shaderData ) {
  40289. return `#version 300 es
  40290. ${ this.getSignature() }
  40291. // extensions
  40292. ${shaderData.extensions}
  40293. // precision
  40294. ${ defaultPrecisions }
  40295. // uniforms
  40296. ${shaderData.uniforms}
  40297. // varyings
  40298. ${shaderData.varyings}
  40299. // codes
  40300. ${shaderData.codes}
  40301. // structs
  40302. ${shaderData.structs}
  40303. void main() {
  40304. // vars
  40305. ${shaderData.vars}
  40306. // flow
  40307. ${shaderData.flow}
  40308. }
  40309. `;
  40310. }
  40311. /**
  40312. * Controls the code build of the shader stages.
  40313. */
  40314. buildCode() {
  40315. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  40316. this.sortBindingGroups();
  40317. for ( const shaderStage in shadersData ) {
  40318. let flow = '// code\n\n';
  40319. flow += this.flowCode[ shaderStage ];
  40320. const flowNodes = this.flowNodes[ shaderStage ];
  40321. const mainNode = flowNodes[ flowNodes.length - 1 ];
  40322. for ( const node of flowNodes ) {
  40323. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  40324. const slotName = node.name;
  40325. if ( slotName ) {
  40326. if ( flow.length > 0 ) flow += '\n';
  40327. flow += `\t// flow -> ${ slotName }\n\t`;
  40328. }
  40329. flow += `${ flowSlotData.code }\n\t`;
  40330. if ( node === mainNode && shaderStage !== 'compute' ) {
  40331. flow += '// result\n\t';
  40332. if ( shaderStage === 'vertex' ) {
  40333. flow += 'gl_Position = ';
  40334. flow += `${ flowSlotData.result };`;
  40335. } else if ( shaderStage === 'fragment' ) {
  40336. if ( ! node.outputNode.isOutputStructNode ) {
  40337. flow += 'fragColor = ';
  40338. flow += `${ flowSlotData.result };`;
  40339. }
  40340. }
  40341. }
  40342. }
  40343. const stageData = shadersData[ shaderStage ];
  40344. stageData.extensions = this.getExtensions( shaderStage );
  40345. stageData.uniforms = this.getUniforms( shaderStage );
  40346. stageData.attributes = this.getAttributes( shaderStage );
  40347. stageData.varyings = this.getVaryings( shaderStage );
  40348. stageData.vars = this.getVars( shaderStage );
  40349. stageData.structs = this.getStructs( shaderStage );
  40350. stageData.codes = this.getCodes( shaderStage );
  40351. stageData.transforms = this.getTransforms( shaderStage );
  40352. stageData.flow = flow;
  40353. }
  40354. if ( this.material !== null ) {
  40355. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  40356. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  40357. } else {
  40358. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  40359. }
  40360. }
  40361. /**
  40362. * This method is one of the more important ones since it's responsible
  40363. * for generating a matching binding instance for the given uniform node.
  40364. *
  40365. * These bindings are later used in the renderer to create bind groups
  40366. * and layouts.
  40367. *
  40368. * @param {UniformNode} node - The uniform node.
  40369. * @param {string} type - The node data type.
  40370. * @param {string} shaderStage - The shader stage.
  40371. * @param {?string} [name=null] - An optional uniform name.
  40372. * @return {NodeUniform} The node uniform object.
  40373. */
  40374. getUniformFromNode( node, type, shaderStage, name = null ) {
  40375. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  40376. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  40377. let uniformGPU = nodeData.uniformGPU;
  40378. if ( uniformGPU === undefined ) {
  40379. const group = node.groupNode;
  40380. const groupName = group.name;
  40381. const bindings = this.getBindGroupArray( groupName, shaderStage );
  40382. if ( type === 'texture' ) {
  40383. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  40384. bindings.push( uniformGPU );
  40385. } else if ( type === 'cubeTexture' ) {
  40386. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  40387. bindings.push( uniformGPU );
  40388. } else if ( type === 'texture3D' ) {
  40389. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  40390. bindings.push( uniformGPU );
  40391. } else if ( type === 'buffer' ) {
  40392. node.name = `NodeBuffer_${ node.id }`;
  40393. uniformNode.name = `buffer${ node.id }`;
  40394. const buffer = new NodeUniformBuffer( node, group );
  40395. buffer.name = node.name;
  40396. bindings.push( buffer );
  40397. uniformGPU = buffer;
  40398. } else {
  40399. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  40400. let uniformsGroup = uniformsStage[ groupName ];
  40401. if ( uniformsGroup === undefined ) {
  40402. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  40403. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  40404. uniformsStage[ groupName ] = uniformsGroup;
  40405. bindings.push( uniformsGroup );
  40406. }
  40407. uniformGPU = this.getNodeUniform( uniformNode, type );
  40408. uniformsGroup.addUniform( uniformGPU );
  40409. }
  40410. nodeData.uniformGPU = uniformGPU;
  40411. }
  40412. return uniformNode;
  40413. }
  40414. }
  40415. let _vector2 = null;
  40416. let _color4 = null;
  40417. /**
  40418. * Most of the rendering related logic is implemented in the
  40419. * {@link Renderer} module and related management components.
  40420. * Sometimes it is required though to execute commands which are
  40421. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  40422. * This abstract base class defines an interface that encapsulates
  40423. * all backend-related logic. Derived classes for each backend must
  40424. * implement the interface.
  40425. *
  40426. * @abstract
  40427. * @private
  40428. */
  40429. class Backend {
  40430. /**
  40431. * Constructs a new backend.
  40432. *
  40433. * @param {Object} parameters - An object holding parameters for the backend.
  40434. */
  40435. constructor( parameters = {} ) {
  40436. /**
  40437. * The parameters of the backend.
  40438. *
  40439. * @type {Object}
  40440. */
  40441. this.parameters = Object.assign( {}, parameters );
  40442. /**
  40443. * This weak map holds backend-specific data of objects
  40444. * like textures, attributes or render targets.
  40445. *
  40446. * @type {WeakMap}
  40447. */
  40448. this.data = new WeakMap();
  40449. /**
  40450. * A reference to the renderer.
  40451. *
  40452. * @type {?Renderer}
  40453. * @default null
  40454. */
  40455. this.renderer = null;
  40456. /**
  40457. * A reference to the canvas element the renderer is drawing to.
  40458. *
  40459. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  40460. * @default null
  40461. */
  40462. this.domElement = null;
  40463. /**
  40464. * A reference to the timestamp query pool.
  40465. *
  40466. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  40467. */
  40468. this.timestampQueryPool = {
  40469. 'render': null,
  40470. 'compute': null
  40471. };
  40472. /**
  40473. * Whether to track timestamps with a Timestamp Query API or not.
  40474. *
  40475. * @type {boolean}
  40476. * @default false
  40477. */
  40478. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40479. }
  40480. /**
  40481. * Initializes the backend so it is ready for usage. Concrete backends
  40482. * are supposed to implement their rendering context creation and related
  40483. * operations in this method.
  40484. *
  40485. * @async
  40486. * @param {Renderer} renderer - The renderer.
  40487. * @return {Promise} A Promise that resolves when the backend has been initialized.
  40488. */
  40489. async init( renderer ) {
  40490. this.renderer = renderer;
  40491. }
  40492. /**
  40493. * The coordinate system of the backend.
  40494. *
  40495. * @abstract
  40496. * @type {number}
  40497. * @readonly
  40498. */
  40499. get coordinateSystem() {}
  40500. // render context
  40501. /**
  40502. * This method is executed at the beginning of a render call and
  40503. * can be used by the backend to prepare the state for upcoming
  40504. * draw calls.
  40505. *
  40506. * @abstract
  40507. * @param {RenderContext} renderContext - The render context.
  40508. */
  40509. beginRender( /*renderContext*/ ) {}
  40510. /**
  40511. * This method is executed at the end of a render call and
  40512. * can be used by the backend to finalize work after draw
  40513. * calls.
  40514. *
  40515. * @abstract
  40516. * @param {RenderContext} renderContext - The render context.
  40517. */
  40518. finishRender( /*renderContext*/ ) {}
  40519. /**
  40520. * This method is executed at the beginning of a compute call and
  40521. * can be used by the backend to prepare the state for upcoming
  40522. * compute tasks.
  40523. *
  40524. * @abstract
  40525. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40526. */
  40527. beginCompute( /*computeGroup*/ ) {}
  40528. /**
  40529. * This method is executed at the end of a compute call and
  40530. * can be used by the backend to finalize work after compute
  40531. * tasks.
  40532. *
  40533. * @abstract
  40534. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40535. */
  40536. finishCompute( /*computeGroup*/ ) {}
  40537. // render object
  40538. /**
  40539. * Executes a draw command for the given render object.
  40540. *
  40541. * @abstract
  40542. * @param {RenderObject} renderObject - The render object to draw.
  40543. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  40544. */
  40545. draw( /*renderObject, info*/ ) { }
  40546. // compute node
  40547. /**
  40548. * Executes a compute command for the given compute node.
  40549. *
  40550. * @abstract
  40551. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  40552. * @param {Node} computeNode - The compute node.
  40553. * @param {Array<BindGroup>} bindings - The bindings.
  40554. * @param {ComputePipeline} computePipeline - The compute pipeline.
  40555. */
  40556. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  40557. // program
  40558. /**
  40559. * Creates a shader program from the given programmable stage.
  40560. *
  40561. * @abstract
  40562. * @param {ProgrammableStage} program - The programmable stage.
  40563. */
  40564. createProgram( /*program*/ ) { }
  40565. /**
  40566. * Destroys the shader program of the given programmable stage.
  40567. *
  40568. * @abstract
  40569. * @param {ProgrammableStage} program - The programmable stage.
  40570. */
  40571. destroyProgram( /*program*/ ) { }
  40572. // bindings
  40573. /**
  40574. * Creates bindings from the given bind group definition.
  40575. *
  40576. * @abstract
  40577. * @param {BindGroup} bindGroup - The bind group.
  40578. * @param {Array<BindGroup>} bindings - Array of bind groups.
  40579. * @param {number} cacheIndex - The cache index.
  40580. * @param {number} version - The version.
  40581. */
  40582. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  40583. /**
  40584. * Updates the given bind group definition.
  40585. *
  40586. * @abstract
  40587. * @param {BindGroup} bindGroup - The bind group.
  40588. * @param {Array<BindGroup>} bindings - Array of bind groups.
  40589. * @param {number} cacheIndex - The cache index.
  40590. * @param {number} version - The version.
  40591. */
  40592. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  40593. /**
  40594. * Updates a buffer binding.
  40595. *
  40596. * @abstract
  40597. * @param {Buffer} binding - The buffer binding to update.
  40598. */
  40599. updateBinding( /*binding*/ ) { }
  40600. // pipeline
  40601. /**
  40602. * Creates a render pipeline for the given render object.
  40603. *
  40604. * @abstract
  40605. * @param {RenderObject} renderObject - The render object.
  40606. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  40607. */
  40608. createRenderPipeline( /*renderObject, promises*/ ) { }
  40609. /**
  40610. * Creates a compute pipeline for the given compute node.
  40611. *
  40612. * @abstract
  40613. * @param {ComputePipeline} computePipeline - The compute pipeline.
  40614. * @param {Array<BindGroup>} bindings - The bindings.
  40615. */
  40616. createComputePipeline( /*computePipeline, bindings*/ ) { }
  40617. // cache key
  40618. /**
  40619. * Returns `true` if the render pipeline requires an update.
  40620. *
  40621. * @abstract
  40622. * @param {RenderObject} renderObject - The render object.
  40623. * @return {boolean} Whether the render pipeline requires an update or not.
  40624. */
  40625. needsRenderUpdate( /*renderObject*/ ) { }
  40626. /**
  40627. * Returns a cache key that is used to identify render pipelines.
  40628. *
  40629. * @abstract
  40630. * @param {RenderObject} renderObject - The render object.
  40631. * @return {string} The cache key.
  40632. */
  40633. getRenderCacheKey( /*renderObject*/ ) { }
  40634. // node builder
  40635. /**
  40636. * Returns a node builder for the given render object.
  40637. *
  40638. * @abstract
  40639. * @param {RenderObject} renderObject - The render object.
  40640. * @param {Renderer} renderer - The renderer.
  40641. * @return {NodeBuilder} The node builder.
  40642. */
  40643. createNodeBuilder( /*renderObject, renderer*/ ) { }
  40644. // textures
  40645. /**
  40646. * Creates a GPU sampler for the given texture.
  40647. *
  40648. * @abstract
  40649. * @param {Texture} texture - The texture to create the sampler for.
  40650. */
  40651. createSampler( /*texture*/ ) { }
  40652. /**
  40653. * Destroys the GPU sampler for the given texture.
  40654. *
  40655. * @abstract
  40656. * @param {Texture} texture - The texture to destroy the sampler for.
  40657. */
  40658. destroySampler( /*texture*/ ) {}
  40659. /**
  40660. * Creates a default texture for the given texture that can be used
  40661. * as a placeholder until the actual texture is ready for usage.
  40662. *
  40663. * @abstract
  40664. * @param {Texture} texture - The texture to create a default texture for.
  40665. */
  40666. createDefaultTexture( /*texture*/ ) { }
  40667. /**
  40668. * Defines a texture on the GPU for the given texture object.
  40669. *
  40670. * @abstract
  40671. * @param {Texture} texture - The texture.
  40672. * @param {Object} [options={}] - Optional configuration parameter.
  40673. */
  40674. createTexture( /*texture, options={}*/ ) { }
  40675. /**
  40676. * Uploads the updated texture data to the GPU.
  40677. *
  40678. * @abstract
  40679. * @param {Texture} texture - The texture.
  40680. * @param {Object} [options={}] - Optional configuration parameter.
  40681. */
  40682. updateTexture( /*texture, options = {}*/ ) { }
  40683. /**
  40684. * Generates mipmaps for the given texture.
  40685. *
  40686. * @abstract
  40687. * @param {Texture} texture - The texture.
  40688. */
  40689. generateMipmaps( /*texture*/ ) { }
  40690. /**
  40691. * Destroys the GPU data for the given texture object.
  40692. *
  40693. * @abstract
  40694. * @param {Texture} texture - The texture.
  40695. */
  40696. destroyTexture( /*texture*/ ) { }
  40697. /**
  40698. * Returns texture data as a typed array.
  40699. *
  40700. * @abstract
  40701. * @async
  40702. * @param {Texture} texture - The texture to copy.
  40703. * @param {number} x - The x coordinate of the copy origin.
  40704. * @param {number} y - The y coordinate of the copy origin.
  40705. * @param {number} width - The width of the copy.
  40706. * @param {number} height - The height of the copy.
  40707. * @param {number} faceIndex - The face index.
  40708. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  40709. */
  40710. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  40711. /**
  40712. * Copies data of the given source texture to the given destination texture.
  40713. *
  40714. * @abstract
  40715. * @param {Texture} srcTexture - The source texture.
  40716. * @param {Texture} dstTexture - The destination texture.
  40717. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  40718. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  40719. * @param {number} [srcLevel=0] - The source mip level to copy from.
  40720. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  40721. */
  40722. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  40723. /**
  40724. * Copies the current bound framebuffer to the given texture.
  40725. *
  40726. * @abstract
  40727. * @param {Texture} texture - The destination texture.
  40728. * @param {RenderContext} renderContext - The render context.
  40729. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  40730. */
  40731. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  40732. // attributes
  40733. /**
  40734. * Creates the GPU buffer of a shader attribute.
  40735. *
  40736. * @abstract
  40737. * @param {BufferAttribute} attribute - The buffer attribute.
  40738. */
  40739. createAttribute( /*attribute*/ ) { }
  40740. /**
  40741. * Creates the GPU buffer of an indexed shader attribute.
  40742. *
  40743. * @abstract
  40744. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  40745. */
  40746. createIndexAttribute( /*attribute*/ ) { }
  40747. /**
  40748. * Creates the GPU buffer of a storage attribute.
  40749. *
  40750. * @abstract
  40751. * @param {BufferAttribute} attribute - The buffer attribute.
  40752. */
  40753. createStorageAttribute( /*attribute*/ ) { }
  40754. /**
  40755. * Updates the GPU buffer of a shader attribute.
  40756. *
  40757. * @abstract
  40758. * @param {BufferAttribute} attribute - The buffer attribute to update.
  40759. */
  40760. updateAttribute( /*attribute*/ ) { }
  40761. /**
  40762. * Destroys the GPU buffer of a shader attribute.
  40763. *
  40764. * @abstract
  40765. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  40766. */
  40767. destroyAttribute( /*attribute*/ ) { }
  40768. // canvas
  40769. /**
  40770. * Returns the backend's rendering context.
  40771. *
  40772. * @abstract
  40773. * @return {Object} The rendering context.
  40774. */
  40775. getContext() { }
  40776. /**
  40777. * Backends can use this method if they have to run
  40778. * logic when the renderer gets resized.
  40779. *
  40780. * @abstract
  40781. */
  40782. updateSize() { }
  40783. /**
  40784. * Updates the viewport with the values from the given render context.
  40785. *
  40786. * @abstract
  40787. * @param {RenderContext} renderContext - The render context.
  40788. */
  40789. updateViewport( /*renderContext*/ ) {}
  40790. // utils
  40791. /**
  40792. * Returns `true` if the given 3D object is fully occluded by other
  40793. * 3D objects in the scene. Backends must implement this method by using
  40794. * a Occlusion Query API.
  40795. *
  40796. * @abstract
  40797. * @param {RenderContext} renderContext - The render context.
  40798. * @param {Object3D} object - The 3D object to test.
  40799. * @return {boolean} Whether the 3D object is fully occluded or not.
  40800. */
  40801. isOccluded( /*renderContext, object*/ ) {}
  40802. /**
  40803. * Resolves the time stamp for the given render context and type.
  40804. *
  40805. * @async
  40806. * @abstract
  40807. * @param {string} [type='render'] - The type of the time stamp.
  40808. * @return {Promise<number>} A Promise that resolves with the time stamp.
  40809. */
  40810. async resolveTimestampsAsync( type = 'render' ) {
  40811. if ( ! this.trackTimestamp ) {
  40812. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  40813. return;
  40814. }
  40815. const queryPool = this.timestampQueryPool[ type ];
  40816. if ( ! queryPool ) {
  40817. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  40818. return;
  40819. }
  40820. const duration = await queryPool.resolveQueriesAsync();
  40821. this.renderer.info[ type ].timestamp = duration;
  40822. return duration;
  40823. }
  40824. /**
  40825. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40826. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40827. *
  40828. * @async
  40829. * @abstract
  40830. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40831. */
  40832. async waitForGPU() {}
  40833. /**
  40834. * This method performs a readback operation by moving buffer data from
  40835. * a storage buffer attribute from the GPU to the CPU.
  40836. *
  40837. * @async
  40838. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40839. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40840. */
  40841. async getArrayBufferAsync( /* attribute */ ) {}
  40842. /**
  40843. * Checks if the given feature is supported by the backend.
  40844. *
  40845. * @async
  40846. * @abstract
  40847. * @param {string} name - The feature's name.
  40848. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  40849. */
  40850. async hasFeatureAsync( /*name*/ ) { }
  40851. /**
  40852. * Checks if the given feature is supported by the backend.
  40853. *
  40854. * @abstract
  40855. * @param {string} name - The feature's name.
  40856. * @return {boolean} Whether the feature is supported or not.
  40857. */
  40858. hasFeature( /*name*/ ) {}
  40859. /**
  40860. * Returns the maximum anisotropy texture filtering value.
  40861. *
  40862. * @abstract
  40863. * @return {number} The maximum anisotropy texture filtering value.
  40864. */
  40865. getMaxAnisotropy() {}
  40866. /**
  40867. * Returns the drawing buffer size.
  40868. *
  40869. * @return {Vector2} The drawing buffer size.
  40870. */
  40871. getDrawingBufferSize() {
  40872. _vector2 = _vector2 || new Vector2();
  40873. return this.renderer.getDrawingBufferSize( _vector2 );
  40874. }
  40875. /**
  40876. * Defines the scissor test.
  40877. *
  40878. * @abstract
  40879. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40880. */
  40881. setScissorTest( /*boolean*/ ) { }
  40882. /**
  40883. * Returns the clear color and alpha into a single
  40884. * color object.
  40885. *
  40886. * @return {Color4} The clear color.
  40887. */
  40888. getClearColor() {
  40889. const renderer = this.renderer;
  40890. _color4 = _color4 || new Color4();
  40891. renderer.getClearColor( _color4 );
  40892. _color4.getRGB( _color4 );
  40893. return _color4;
  40894. }
  40895. /**
  40896. * Returns the DOM element. If no DOM element exists, the backend
  40897. * creates a new one.
  40898. *
  40899. * @return {HTMLCanvasElement} The DOM element.
  40900. */
  40901. getDomElement() {
  40902. let domElement = this.domElement;
  40903. if ( domElement === null ) {
  40904. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  40905. // OffscreenCanvas does not have setAttribute, see #22811
  40906. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  40907. this.domElement = domElement;
  40908. }
  40909. return domElement;
  40910. }
  40911. /**
  40912. * Sets a dictionary for the given object into the
  40913. * internal data structure.
  40914. *
  40915. * @param {Object} object - The object.
  40916. * @param {Object} value - The dictionary to set.
  40917. */
  40918. set( object, value ) {
  40919. this.data.set( object, value );
  40920. }
  40921. /**
  40922. * Returns the dictionary for the given object.
  40923. *
  40924. * @param {Object} object - The object.
  40925. * @return {Object} The object's dictionary.
  40926. */
  40927. get( object ) {
  40928. let map = this.data.get( object );
  40929. if ( map === undefined ) {
  40930. map = {};
  40931. this.data.set( object, map );
  40932. }
  40933. return map;
  40934. }
  40935. /**
  40936. * Checks if the given object has a dictionary
  40937. * with data defined.
  40938. *
  40939. * @param {Object} object - The object.
  40940. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  40941. */
  40942. has( object ) {
  40943. return this.data.has( object );
  40944. }
  40945. /**
  40946. * Deletes an object from the internal data structure.
  40947. *
  40948. * @param {Object} object - The object to delete.
  40949. */
  40950. delete( object ) {
  40951. this.data.delete( object );
  40952. }
  40953. /**
  40954. * Frees internal resources.
  40955. *
  40956. * @abstract
  40957. */
  40958. dispose() { }
  40959. }
  40960. let _id$1 = 0;
  40961. /**
  40962. * This module is internally used in context of compute shaders.
  40963. * This type of shader is not natively supported in WebGL 2 and
  40964. * thus implemented via Transform Feedback. `DualAttributeData`
  40965. * manages the related data.
  40966. *
  40967. * @private
  40968. */
  40969. class DualAttributeData {
  40970. constructor( attributeData, dualBuffer ) {
  40971. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  40972. this.type = attributeData.type;
  40973. this.bufferType = attributeData.bufferType;
  40974. this.pbo = attributeData.pbo;
  40975. this.byteLength = attributeData.byteLength;
  40976. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  40977. this.version = attributeData.version;
  40978. this.isInteger = attributeData.isInteger;
  40979. this.activeBufferIndex = 0;
  40980. this.baseId = attributeData.id;
  40981. }
  40982. get id() {
  40983. return `${ this.baseId }|${ this.activeBufferIndex }`;
  40984. }
  40985. get bufferGPU() {
  40986. return this.buffers[ this.activeBufferIndex ];
  40987. }
  40988. get transformBuffer() {
  40989. return this.buffers[ this.activeBufferIndex ^ 1 ];
  40990. }
  40991. switchBuffers() {
  40992. this.activeBufferIndex ^= 1;
  40993. }
  40994. }
  40995. /**
  40996. * A WebGL 2 backend utility module for managing shader attributes.
  40997. *
  40998. * @private
  40999. */
  41000. class WebGLAttributeUtils {
  41001. /**
  41002. * Constructs a new utility object.
  41003. *
  41004. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41005. */
  41006. constructor( backend ) {
  41007. /**
  41008. * A reference to the WebGL 2 backend.
  41009. *
  41010. * @type {WebGLBackend}
  41011. */
  41012. this.backend = backend;
  41013. }
  41014. /**
  41015. * Creates the GPU buffer for the given buffer attribute.
  41016. *
  41017. * @param {BufferAttribute} attribute - The buffer attribute.
  41018. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  41019. */
  41020. createAttribute( attribute, bufferType ) {
  41021. const backend = this.backend;
  41022. const { gl } = backend;
  41023. const array = attribute.array;
  41024. const usage = attribute.usage || gl.STATIC_DRAW;
  41025. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  41026. const bufferData = backend.get( bufferAttribute );
  41027. let bufferGPU = bufferData.bufferGPU;
  41028. if ( bufferGPU === undefined ) {
  41029. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  41030. bufferData.bufferGPU = bufferGPU;
  41031. bufferData.bufferType = bufferType;
  41032. bufferData.version = bufferAttribute.version;
  41033. }
  41034. //attribute.onUploadCallback();
  41035. let type;
  41036. if ( array instanceof Float32Array ) {
  41037. type = gl.FLOAT;
  41038. } else if ( array instanceof Uint16Array ) {
  41039. if ( attribute.isFloat16BufferAttribute ) {
  41040. type = gl.HALF_FLOAT;
  41041. } else {
  41042. type = gl.UNSIGNED_SHORT;
  41043. }
  41044. } else if ( array instanceof Int16Array ) {
  41045. type = gl.SHORT;
  41046. } else if ( array instanceof Uint32Array ) {
  41047. type = gl.UNSIGNED_INT;
  41048. } else if ( array instanceof Int32Array ) {
  41049. type = gl.INT;
  41050. } else if ( array instanceof Int8Array ) {
  41051. type = gl.BYTE;
  41052. } else if ( array instanceof Uint8Array ) {
  41053. type = gl.UNSIGNED_BYTE;
  41054. } else if ( array instanceof Uint8ClampedArray ) {
  41055. type = gl.UNSIGNED_BYTE;
  41056. } else {
  41057. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  41058. }
  41059. let attributeData = {
  41060. bufferGPU,
  41061. bufferType,
  41062. type,
  41063. byteLength: array.byteLength,
  41064. bytesPerElement: array.BYTES_PER_ELEMENT,
  41065. version: attribute.version,
  41066. pbo: attribute.pbo,
  41067. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  41068. id: _id$1 ++
  41069. };
  41070. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  41071. // create buffer for transform feedback use
  41072. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  41073. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  41074. }
  41075. backend.set( attribute, attributeData );
  41076. }
  41077. /**
  41078. * Updates the GPU buffer of the given buffer attribute.
  41079. *
  41080. * @param {BufferAttribute} attribute - The buffer attribute.
  41081. */
  41082. updateAttribute( attribute ) {
  41083. const backend = this.backend;
  41084. const { gl } = backend;
  41085. const array = attribute.array;
  41086. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  41087. const bufferData = backend.get( bufferAttribute );
  41088. const bufferType = bufferData.bufferType;
  41089. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  41090. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  41091. if ( updateRanges.length === 0 ) {
  41092. // Not using update ranges
  41093. gl.bufferSubData( bufferType, 0, array );
  41094. } else {
  41095. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  41096. const range = updateRanges[ i ];
  41097. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  41098. array, range.start, range.count );
  41099. }
  41100. bufferAttribute.clearUpdateRanges();
  41101. }
  41102. gl.bindBuffer( bufferType, null );
  41103. bufferData.version = bufferAttribute.version;
  41104. }
  41105. /**
  41106. * Destroys the GPU buffer of the given buffer attribute.
  41107. *
  41108. * @param {BufferAttribute} attribute - The buffer attribute.
  41109. */
  41110. destroyAttribute( attribute ) {
  41111. const backend = this.backend;
  41112. const { gl } = backend;
  41113. if ( attribute.isInterleavedBufferAttribute ) {
  41114. backend.delete( attribute.data );
  41115. }
  41116. const attributeData = backend.get( attribute );
  41117. gl.deleteBuffer( attributeData.bufferGPU );
  41118. backend.delete( attribute );
  41119. }
  41120. /**
  41121. * This method performs a readback operation by moving buffer data from
  41122. * a storage buffer attribute from the GPU to the CPU.
  41123. *
  41124. * @async
  41125. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  41126. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  41127. */
  41128. async getArrayBufferAsync( attribute ) {
  41129. const backend = this.backend;
  41130. const { gl } = backend;
  41131. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  41132. const { bufferGPU } = backend.get( bufferAttribute );
  41133. const array = attribute.array;
  41134. const byteLength = array.byteLength;
  41135. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  41136. const writeBuffer = gl.createBuffer();
  41137. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  41138. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  41139. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  41140. await backend.utils._clientWaitAsync();
  41141. const dstBuffer = new attribute.array.constructor( array.length );
  41142. // Ensure the buffer is bound before reading
  41143. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  41144. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  41145. gl.deleteBuffer( writeBuffer );
  41146. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  41147. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  41148. return dstBuffer.buffer;
  41149. }
  41150. /**
  41151. * Creates a WebGL buffer with the given data.
  41152. *
  41153. * @private
  41154. * @param {WebGL2RenderingContext} gl - The rendering context.
  41155. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  41156. * @param {TypedArray} array - The array of the buffer attribute.
  41157. * @param {GLenum} usage - The usage.
  41158. * @return {WebGLBuffer} The WebGL buffer.
  41159. */
  41160. _createBuffer( gl, bufferType, array, usage ) {
  41161. const bufferGPU = gl.createBuffer();
  41162. gl.bindBuffer( bufferType, bufferGPU );
  41163. gl.bufferData( bufferType, array, usage );
  41164. gl.bindBuffer( bufferType, null );
  41165. return bufferGPU;
  41166. }
  41167. }
  41168. let equationToGL, factorToGL;
  41169. /**
  41170. * A WebGL 2 backend utility module for managing the WebGL state.
  41171. *
  41172. * The major goal of this module is to reduce the number of state changes
  41173. * by caching the WEbGL state with a series of variables. In this way, the
  41174. * renderer only executes state change commands when necessary which
  41175. * improves the overall performance.
  41176. *
  41177. * @private
  41178. */
  41179. class WebGLState {
  41180. /**
  41181. * Constructs a new utility object.
  41182. *
  41183. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41184. */
  41185. constructor( backend ) {
  41186. /**
  41187. * A reference to the WebGL 2 backend.
  41188. *
  41189. * @type {WebGLBackend}
  41190. */
  41191. this.backend = backend;
  41192. /**
  41193. * A reference to the rendering context.
  41194. *
  41195. * @type {WebGL2RenderingContext}
  41196. */
  41197. this.gl = this.backend.gl;
  41198. // Below properties are intended to cache
  41199. // the WebGL state and are not explicitly
  41200. // documented for convenience reasons.
  41201. this.enabled = {};
  41202. this.currentFlipSided = null;
  41203. this.currentCullFace = null;
  41204. this.currentProgram = null;
  41205. this.currentBlendingEnabled = false;
  41206. this.currentBlending = null;
  41207. this.currentBlendSrc = null;
  41208. this.currentBlendDst = null;
  41209. this.currentBlendSrcAlpha = null;
  41210. this.currentBlendDstAlpha = null;
  41211. this.currentPremultipledAlpha = null;
  41212. this.currentPolygonOffsetFactor = null;
  41213. this.currentPolygonOffsetUnits = null;
  41214. this.currentColorMask = null;
  41215. this.currentDepthFunc = null;
  41216. this.currentDepthMask = null;
  41217. this.currentStencilFunc = null;
  41218. this.currentStencilRef = null;
  41219. this.currentStencilFuncMask = null;
  41220. this.currentStencilFail = null;
  41221. this.currentStencilZFail = null;
  41222. this.currentStencilZPass = null;
  41223. this.currentStencilMask = null;
  41224. this.currentLineWidth = null;
  41225. this.currentClippingPlanes = 0;
  41226. this.currentVAO = null;
  41227. this.currentIndex = null;
  41228. this.currentBoundFramebuffers = {};
  41229. this.currentDrawbuffers = new WeakMap();
  41230. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  41231. this.currentTextureSlot = null;
  41232. this.currentBoundTextures = {};
  41233. this.currentBoundBufferBases = {};
  41234. this._init();
  41235. }
  41236. /**
  41237. * Inits the state of the utility.
  41238. *
  41239. * @private
  41240. */
  41241. _init() {
  41242. const gl = this.gl;
  41243. // Store only WebGL constants here.
  41244. equationToGL = {
  41245. [ AddEquation ]: gl.FUNC_ADD,
  41246. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  41247. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  41248. };
  41249. factorToGL = {
  41250. [ ZeroFactor ]: gl.ZERO,
  41251. [ OneFactor ]: gl.ONE,
  41252. [ SrcColorFactor ]: gl.SRC_COLOR,
  41253. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  41254. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  41255. [ DstColorFactor ]: gl.DST_COLOR,
  41256. [ DstAlphaFactor ]: gl.DST_ALPHA,
  41257. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  41258. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  41259. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  41260. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  41261. };
  41262. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  41263. const viewportParam = gl.getParameter( gl.VIEWPORT );
  41264. this.currentScissor = new Vector4().fromArray( scissorParam );
  41265. this.currentViewport = new Vector4().fromArray( viewportParam );
  41266. this._tempVec4 = new Vector4();
  41267. }
  41268. /**
  41269. * Enables the given WebGL capability.
  41270. *
  41271. * This method caches the capability state so
  41272. * `gl.enable()` is only called when necessary.
  41273. *
  41274. * @param {GLenum} id - The capability to enable.
  41275. */
  41276. enable( id ) {
  41277. const { enabled } = this;
  41278. if ( enabled[ id ] !== true ) {
  41279. this.gl.enable( id );
  41280. enabled[ id ] = true;
  41281. }
  41282. }
  41283. /**
  41284. * Disables the given WebGL capability.
  41285. *
  41286. * This method caches the capability state so
  41287. * `gl.disable()` is only called when necessary.
  41288. *
  41289. * @param {GLenum} id - The capability to enable.
  41290. */
  41291. disable( id ) {
  41292. const { enabled } = this;
  41293. if ( enabled[ id ] !== false ) {
  41294. this.gl.disable( id );
  41295. enabled[ id ] = false;
  41296. }
  41297. }
  41298. /**
  41299. * Specifies whether polygons are front- or back-facing
  41300. * by setting the winding orientation.
  41301. *
  41302. * This method caches the state so `gl.frontFace()` is only
  41303. * called when necessary.
  41304. *
  41305. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  41306. */
  41307. setFlipSided( flipSided ) {
  41308. if ( this.currentFlipSided !== flipSided ) {
  41309. const { gl } = this;
  41310. if ( flipSided ) {
  41311. gl.frontFace( gl.CW );
  41312. } else {
  41313. gl.frontFace( gl.CCW );
  41314. }
  41315. this.currentFlipSided = flipSided;
  41316. }
  41317. }
  41318. /**
  41319. * Specifies whether or not front- and/or back-facing
  41320. * polygons can be culled.
  41321. *
  41322. * This method caches the state so `gl.cullFace()` is only
  41323. * called when necessary.
  41324. *
  41325. * @param {number} cullFace - Defines which polygons are candidates for culling.
  41326. */
  41327. setCullFace( cullFace ) {
  41328. const { gl } = this;
  41329. if ( cullFace !== CullFaceNone ) {
  41330. this.enable( gl.CULL_FACE );
  41331. if ( cullFace !== this.currentCullFace ) {
  41332. if ( cullFace === CullFaceBack ) {
  41333. gl.cullFace( gl.BACK );
  41334. } else if ( cullFace === CullFaceFront ) {
  41335. gl.cullFace( gl.FRONT );
  41336. } else {
  41337. gl.cullFace( gl.FRONT_AND_BACK );
  41338. }
  41339. }
  41340. } else {
  41341. this.disable( gl.CULL_FACE );
  41342. }
  41343. this.currentCullFace = cullFace;
  41344. }
  41345. /**
  41346. * Specifies the width of line primitives.
  41347. *
  41348. * This method caches the state so `gl.lineWidth()` is only
  41349. * called when necessary.
  41350. *
  41351. * @param {number} width - The line width.
  41352. */
  41353. setLineWidth( width ) {
  41354. const { currentLineWidth, gl } = this;
  41355. if ( width !== currentLineWidth ) {
  41356. gl.lineWidth( width );
  41357. this.currentLineWidth = width;
  41358. }
  41359. }
  41360. /**
  41361. * Defines the blending.
  41362. *
  41363. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  41364. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  41365. *
  41366. * @param {number} blending - The blending type.
  41367. * @param {number} blendEquation - The blending equation.
  41368. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  41369. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  41370. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  41371. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  41372. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  41373. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  41374. */
  41375. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  41376. const { gl } = this;
  41377. if ( blending === NoBlending ) {
  41378. if ( this.currentBlendingEnabled === true ) {
  41379. this.disable( gl.BLEND );
  41380. this.currentBlendingEnabled = false;
  41381. }
  41382. return;
  41383. }
  41384. if ( this.currentBlendingEnabled === false ) {
  41385. this.enable( gl.BLEND );
  41386. this.currentBlendingEnabled = true;
  41387. }
  41388. if ( blending !== CustomBlending ) {
  41389. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  41390. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  41391. gl.blendEquation( gl.FUNC_ADD );
  41392. this.currentBlendEquation = AddEquation;
  41393. this.currentBlendEquationAlpha = AddEquation;
  41394. }
  41395. if ( premultipliedAlpha ) {
  41396. switch ( blending ) {
  41397. case NormalBlending:
  41398. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  41399. break;
  41400. case AdditiveBlending:
  41401. gl.blendFunc( gl.ONE, gl.ONE );
  41402. break;
  41403. case SubtractiveBlending:
  41404. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  41405. break;
  41406. case MultiplyBlending:
  41407. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  41408. break;
  41409. default:
  41410. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  41411. break;
  41412. }
  41413. } else {
  41414. switch ( blending ) {
  41415. case NormalBlending:
  41416. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  41417. break;
  41418. case AdditiveBlending:
  41419. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  41420. break;
  41421. case SubtractiveBlending:
  41422. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  41423. break;
  41424. case MultiplyBlending:
  41425. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  41426. break;
  41427. default:
  41428. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  41429. break;
  41430. }
  41431. }
  41432. this.currentBlendSrc = null;
  41433. this.currentBlendDst = null;
  41434. this.currentBlendSrcAlpha = null;
  41435. this.currentBlendDstAlpha = null;
  41436. this.currentBlending = blending;
  41437. this.currentPremultipledAlpha = premultipliedAlpha;
  41438. }
  41439. return;
  41440. }
  41441. // custom blending
  41442. blendEquationAlpha = blendEquationAlpha || blendEquation;
  41443. blendSrcAlpha = blendSrcAlpha || blendSrc;
  41444. blendDstAlpha = blendDstAlpha || blendDst;
  41445. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  41446. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  41447. this.currentBlendEquation = blendEquation;
  41448. this.currentBlendEquationAlpha = blendEquationAlpha;
  41449. }
  41450. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  41451. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  41452. this.currentBlendSrc = blendSrc;
  41453. this.currentBlendDst = blendDst;
  41454. this.currentBlendSrcAlpha = blendSrcAlpha;
  41455. this.currentBlendDstAlpha = blendDstAlpha;
  41456. }
  41457. this.currentBlending = blending;
  41458. this.currentPremultipledAlpha = false;
  41459. }
  41460. /**
  41461. * Specifies whether colors can be written when rendering
  41462. * into a framebuffer or not.
  41463. *
  41464. * This method caches the state so `gl.colorMask()` is only
  41465. * called when necessary.
  41466. *
  41467. * @param {boolean} colorMask - The color mask.
  41468. */
  41469. setColorMask( colorMask ) {
  41470. if ( this.currentColorMask !== colorMask ) {
  41471. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  41472. this.currentColorMask = colorMask;
  41473. }
  41474. }
  41475. /**
  41476. * Specifies whether the depth test is enabled or not.
  41477. *
  41478. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  41479. */
  41480. setDepthTest( depthTest ) {
  41481. const { gl } = this;
  41482. if ( depthTest ) {
  41483. this.enable( gl.DEPTH_TEST );
  41484. } else {
  41485. this.disable( gl.DEPTH_TEST );
  41486. }
  41487. }
  41488. /**
  41489. * Specifies whether depth values can be written when rendering
  41490. * into a framebuffer or not.
  41491. *
  41492. * This method caches the state so `gl.depthMask()` is only
  41493. * called when necessary.
  41494. *
  41495. * @param {boolean} depthMask - The depth mask.
  41496. */
  41497. setDepthMask( depthMask ) {
  41498. if ( this.currentDepthMask !== depthMask ) {
  41499. this.gl.depthMask( depthMask );
  41500. this.currentDepthMask = depthMask;
  41501. }
  41502. }
  41503. /**
  41504. * Specifies the depth compare function.
  41505. *
  41506. * This method caches the state so `gl.depthFunc()` is only
  41507. * called when necessary.
  41508. *
  41509. * @param {number} depthFunc - The depth compare function.
  41510. */
  41511. setDepthFunc( depthFunc ) {
  41512. if ( this.currentDepthFunc !== depthFunc ) {
  41513. const { gl } = this;
  41514. switch ( depthFunc ) {
  41515. case NeverDepth:
  41516. gl.depthFunc( gl.NEVER );
  41517. break;
  41518. case AlwaysDepth:
  41519. gl.depthFunc( gl.ALWAYS );
  41520. break;
  41521. case LessDepth:
  41522. gl.depthFunc( gl.LESS );
  41523. break;
  41524. case LessEqualDepth:
  41525. gl.depthFunc( gl.LEQUAL );
  41526. break;
  41527. case EqualDepth:
  41528. gl.depthFunc( gl.EQUAL );
  41529. break;
  41530. case GreaterEqualDepth:
  41531. gl.depthFunc( gl.GEQUAL );
  41532. break;
  41533. case GreaterDepth:
  41534. gl.depthFunc( gl.GREATER );
  41535. break;
  41536. case NotEqualDepth:
  41537. gl.depthFunc( gl.NOTEQUAL );
  41538. break;
  41539. default:
  41540. gl.depthFunc( gl.LEQUAL );
  41541. }
  41542. this.currentDepthFunc = depthFunc;
  41543. }
  41544. }
  41545. /**
  41546. * Specifies the scissor box.
  41547. *
  41548. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  41549. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  41550. * @param {number} width - The width of the viewport.
  41551. * @param {number} height - The height of the viewport.
  41552. *
  41553. */
  41554. scissor( x, y, width, height ) {
  41555. const scissor = this._tempVec4.set( x, y, width, height );
  41556. if ( this.currentScissor.equals( scissor ) === false ) {
  41557. const { gl } = this;
  41558. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  41559. this.currentScissor.copy( scissor );
  41560. }
  41561. }
  41562. /**
  41563. * Specifies the viewport.
  41564. *
  41565. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  41566. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  41567. * @param {number} width - The width of the viewport.
  41568. * @param {number} height - The height of the viewport.
  41569. *
  41570. */
  41571. viewport( x, y, width, height ) {
  41572. const viewport = this._tempVec4.set( x, y, width, height );
  41573. if ( this.currentViewport.equals( viewport ) === false ) {
  41574. const { gl } = this;
  41575. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  41576. this.currentViewport.copy( viewport );
  41577. }
  41578. }
  41579. /**
  41580. * Defines the scissor test.
  41581. *
  41582. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41583. */
  41584. setScissorTest( boolean ) {
  41585. const gl = this.gl;
  41586. if ( boolean ) {
  41587. gl.enable( gl.SCISSOR_TEST );
  41588. } else {
  41589. gl.disable( gl.SCISSOR_TEST );
  41590. }
  41591. }
  41592. /**
  41593. * Specifies whether the stencil test is enabled or not.
  41594. *
  41595. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  41596. */
  41597. setStencilTest( stencilTest ) {
  41598. const { gl } = this;
  41599. if ( stencilTest ) {
  41600. this.enable( gl.STENCIL_TEST );
  41601. } else {
  41602. this.disable( gl.STENCIL_TEST );
  41603. }
  41604. }
  41605. /**
  41606. * Specifies whether stencil values can be written when rendering
  41607. * into a framebuffer or not.
  41608. *
  41609. * This method caches the state so `gl.stencilMask()` is only
  41610. * called when necessary.
  41611. *
  41612. * @param {boolean} stencilMask - The stencil mask.
  41613. */
  41614. setStencilMask( stencilMask ) {
  41615. if ( this.currentStencilMask !== stencilMask ) {
  41616. this.gl.stencilMask( stencilMask );
  41617. this.currentStencilMask = stencilMask;
  41618. }
  41619. }
  41620. /**
  41621. * Specifies whether the stencil test functions.
  41622. *
  41623. * This method caches the state so `gl.stencilFunc()` is only
  41624. * called when necessary.
  41625. *
  41626. * @param {number} stencilFunc - The stencil compare function.
  41627. * @param {number} stencilRef - The reference value for the stencil test.
  41628. * @param {number} stencilMask - A bit-wise mask that is used to AND the reference value and the stored stencil value when the test is done.
  41629. */
  41630. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  41631. if ( this.currentStencilFunc !== stencilFunc ||
  41632. this.currentStencilRef !== stencilRef ||
  41633. this.currentStencilFuncMask !== stencilMask ) {
  41634. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  41635. this.currentStencilFunc = stencilFunc;
  41636. this.currentStencilRef = stencilRef;
  41637. this.currentStencilFuncMask = stencilMask;
  41638. }
  41639. }
  41640. /**
  41641. * Specifies whether the stencil test operation.
  41642. *
  41643. * This method caches the state so `gl.stencilOp()` is only
  41644. * called when necessary.
  41645. *
  41646. * @param {number} stencilFail - The function to use when the stencil test fails.
  41647. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  41648. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  41649. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  41650. */
  41651. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  41652. if ( this.currentStencilFail !== stencilFail ||
  41653. this.currentStencilZFail !== stencilZFail ||
  41654. this.currentStencilZPass !== stencilZPass ) {
  41655. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  41656. this.currentStencilFail = stencilFail;
  41657. this.currentStencilZFail = stencilZFail;
  41658. this.currentStencilZPass = stencilZPass;
  41659. }
  41660. }
  41661. /**
  41662. * Configures the WebGL state for the given material.
  41663. *
  41664. * @param {Material} material - The material to configure the state for.
  41665. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  41666. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  41667. */
  41668. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  41669. const { gl } = this;
  41670. material.side === DoubleSide
  41671. ? this.disable( gl.CULL_FACE )
  41672. : this.enable( gl.CULL_FACE );
  41673. let flipSided = ( material.side === BackSide );
  41674. if ( frontFaceCW ) flipSided = ! flipSided;
  41675. this.setFlipSided( flipSided );
  41676. ( material.blending === NormalBlending && material.transparent === false )
  41677. ? this.setBlending( NoBlending )
  41678. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  41679. this.setDepthFunc( material.depthFunc );
  41680. this.setDepthTest( material.depthTest );
  41681. this.setDepthMask( material.depthWrite );
  41682. this.setColorMask( material.colorWrite );
  41683. const stencilWrite = material.stencilWrite;
  41684. this.setStencilTest( stencilWrite );
  41685. if ( stencilWrite ) {
  41686. this.setStencilMask( material.stencilWriteMask );
  41687. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  41688. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  41689. }
  41690. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  41691. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  41692. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  41693. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  41694. if ( hardwareClippingPlanes > 0 ) {
  41695. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  41696. const CLIP_DISTANCE0_WEBGL = 0x3000;
  41697. for ( let i = 0; i < 8; i ++ ) {
  41698. if ( i < hardwareClippingPlanes ) {
  41699. this.enable( CLIP_DISTANCE0_WEBGL + i );
  41700. } else {
  41701. this.disable( CLIP_DISTANCE0_WEBGL + i );
  41702. }
  41703. }
  41704. }
  41705. }
  41706. }
  41707. /**
  41708. * Specifies the polygon offset.
  41709. *
  41710. * This method caches the state so `gl.polygonOffset()` is only
  41711. * called when necessary.
  41712. *
  41713. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  41714. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  41715. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  41716. */
  41717. setPolygonOffset( polygonOffset, factor, units ) {
  41718. const { gl } = this;
  41719. if ( polygonOffset ) {
  41720. this.enable( gl.POLYGON_OFFSET_FILL );
  41721. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  41722. gl.polygonOffset( factor, units );
  41723. this.currentPolygonOffsetFactor = factor;
  41724. this.currentPolygonOffsetUnits = units;
  41725. }
  41726. } else {
  41727. this.disable( gl.POLYGON_OFFSET_FILL );
  41728. }
  41729. }
  41730. /**
  41731. * Defines the usage of the given WebGL program.
  41732. *
  41733. * This method caches the state so `gl.useProgram()` is only
  41734. * called when necessary.
  41735. *
  41736. * @param {WebGLProgram} program - The WebGL program to use.
  41737. * @return {boolean} Whether a program change has been executed or not.
  41738. */
  41739. useProgram( program ) {
  41740. if ( this.currentProgram !== program ) {
  41741. this.gl.useProgram( program );
  41742. this.currentProgram = program;
  41743. return true;
  41744. }
  41745. return false;
  41746. }
  41747. /**
  41748. * Sets the vertex state by binding the given VAO and element buffer.
  41749. *
  41750. * @param {WebGLVertexArrayObject} vao - The VAO.
  41751. * @param {WebGLBuffer} indexBuffer - The index buffer.
  41752. * @return {boolean} Whether a vertex state has been changed or not.
  41753. */
  41754. setVertexState( vao, indexBuffer = null ) {
  41755. const gl = this.gl;
  41756. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  41757. gl.bindVertexArray( vao );
  41758. if ( indexBuffer !== null ) {
  41759. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  41760. }
  41761. this.currentVAO = vao;
  41762. this.currentIndex = indexBuffer;
  41763. return true;
  41764. }
  41765. return false;
  41766. }
  41767. /**
  41768. * Resets the vertex array state by resetting the VAO and element buffer.
  41769. */
  41770. resetVertexState() {
  41771. const gl = this.gl;
  41772. gl.bindVertexArray( null );
  41773. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  41774. this.currentVAO = null;
  41775. this.currentIndex = null;
  41776. }
  41777. // framebuffer
  41778. /**
  41779. * Binds the given framebuffer.
  41780. *
  41781. * This method caches the state so `gl.bindFramebuffer()` is only
  41782. * called when necessary.
  41783. *
  41784. * @param {number} target - The binding point (target).
  41785. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  41786. * @return {boolean} Whether a bind has been executed or not.
  41787. */
  41788. bindFramebuffer( target, framebuffer ) {
  41789. const { gl, currentBoundFramebuffers } = this;
  41790. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  41791. gl.bindFramebuffer( target, framebuffer );
  41792. currentBoundFramebuffers[ target ] = framebuffer;
  41793. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  41794. if ( target === gl.DRAW_FRAMEBUFFER ) {
  41795. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  41796. }
  41797. if ( target === gl.FRAMEBUFFER ) {
  41798. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  41799. }
  41800. return true;
  41801. }
  41802. return false;
  41803. }
  41804. /**
  41805. * Defines draw buffers to which fragment colors are written into.
  41806. * Configures the MRT setup of custom framebuffers.
  41807. *
  41808. * This method caches the state so `gl.drawBuffers()` is only
  41809. * called when necessary.
  41810. *
  41811. * @param {RenderContext} renderContext - The render context.
  41812. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  41813. */
  41814. drawBuffers( renderContext, framebuffer ) {
  41815. const { gl } = this;
  41816. let drawBuffers = [];
  41817. let needsUpdate = false;
  41818. if ( renderContext.textures !== null ) {
  41819. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  41820. if ( drawBuffers === undefined ) {
  41821. drawBuffers = [];
  41822. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  41823. }
  41824. const textures = renderContext.textures;
  41825. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  41826. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  41827. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  41828. }
  41829. drawBuffers.length = textures.length;
  41830. needsUpdate = true;
  41831. }
  41832. } else {
  41833. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  41834. drawBuffers[ 0 ] = gl.BACK;
  41835. needsUpdate = true;
  41836. }
  41837. }
  41838. if ( needsUpdate ) {
  41839. gl.drawBuffers( drawBuffers );
  41840. }
  41841. }
  41842. // texture
  41843. /**
  41844. * Makes the given texture unit active.
  41845. *
  41846. * This method caches the state so `gl.activeTexture()` is only
  41847. * called when necessary.
  41848. *
  41849. * @param {number} webglSlot - The texture unit to make active.
  41850. */
  41851. activeTexture( webglSlot ) {
  41852. const { gl, currentTextureSlot, maxTextures } = this;
  41853. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  41854. if ( currentTextureSlot !== webglSlot ) {
  41855. gl.activeTexture( webglSlot );
  41856. this.currentTextureSlot = webglSlot;
  41857. }
  41858. }
  41859. /**
  41860. * Binds the given WebGL texture to a target.
  41861. *
  41862. * This method caches the state so `gl.bindTexture()` is only
  41863. * called when necessary.
  41864. *
  41865. * @param {number} webglType - The binding point (target).
  41866. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  41867. * @param {number} webglSlot - The texture.
  41868. */
  41869. bindTexture( webglType, webglTexture, webglSlot ) {
  41870. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  41871. if ( webglSlot === undefined ) {
  41872. if ( currentTextureSlot === null ) {
  41873. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  41874. } else {
  41875. webglSlot = currentTextureSlot;
  41876. }
  41877. }
  41878. let boundTexture = currentBoundTextures[ webglSlot ];
  41879. if ( boundTexture === undefined ) {
  41880. boundTexture = { type: undefined, texture: undefined };
  41881. currentBoundTextures[ webglSlot ] = boundTexture;
  41882. }
  41883. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  41884. if ( currentTextureSlot !== webglSlot ) {
  41885. gl.activeTexture( webglSlot );
  41886. this.currentTextureSlot = webglSlot;
  41887. }
  41888. gl.bindTexture( webglType, webglTexture );
  41889. boundTexture.type = webglType;
  41890. boundTexture.texture = webglTexture;
  41891. }
  41892. }
  41893. /**
  41894. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  41895. *
  41896. * This method caches the state so `gl.bindBufferBase()` is only
  41897. * called when necessary.
  41898. *
  41899. * @param {number} target - The target for the bind operation.
  41900. * @param {number} index - The index of the target.
  41901. * @param {WebGLBuffer} buffer - The WebGL buffer.
  41902. * @return {boolean} Whether a bind has been executed or not.
  41903. */
  41904. bindBufferBase( target, index, buffer ) {
  41905. const { gl } = this;
  41906. const key = `${target}-${index}`;
  41907. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  41908. gl.bindBufferBase( target, index, buffer );
  41909. this.currentBoundBufferBases[ key ] = buffer;
  41910. return true;
  41911. }
  41912. return false;
  41913. }
  41914. /**
  41915. * Unbinds the current bound texture.
  41916. *
  41917. * This method caches the state so `gl.bindTexture()` is only
  41918. * called when necessary.
  41919. */
  41920. unbindTexture() {
  41921. const { gl, currentTextureSlot, currentBoundTextures } = this;
  41922. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  41923. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  41924. gl.bindTexture( boundTexture.type, null );
  41925. boundTexture.type = undefined;
  41926. boundTexture.texture = undefined;
  41927. }
  41928. }
  41929. }
  41930. /**
  41931. * A WebGL 2 backend utility module with common helpers.
  41932. *
  41933. * @private
  41934. */
  41935. class WebGLUtils {
  41936. /**
  41937. * Constructs a new utility object.
  41938. *
  41939. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41940. */
  41941. constructor( backend ) {
  41942. /**
  41943. * A reference to the WebGL 2 backend.
  41944. *
  41945. * @type {WebGLBackend}
  41946. */
  41947. this.backend = backend;
  41948. /**
  41949. * A reference to the rendering context.
  41950. *
  41951. * @type {WebGL2RenderingContext}
  41952. */
  41953. this.gl = this.backend.gl;
  41954. /**
  41955. * A reference to a backend module holding extension-related
  41956. * utility functions.
  41957. *
  41958. * @type {WebGLExtensions}
  41959. */
  41960. this.extensions = backend.extensions;
  41961. }
  41962. /**
  41963. * Converts the given three.js constant into a WebGL constant.
  41964. * The method currently supports the conversion of texture formats
  41965. * and types.
  41966. *
  41967. * @param {number} p - The three.js constant.
  41968. * @param {string} [colorSpace=NoColorSpace] - The color space.
  41969. * @return {?number} The corresponding WebGL constant.
  41970. */
  41971. convert( p, colorSpace = NoColorSpace ) {
  41972. const { gl, extensions } = this;
  41973. let extension;
  41974. const transfer = ColorManagement.getTransfer( colorSpace );
  41975. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  41976. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  41977. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  41978. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  41979. if ( p === ByteType ) return gl.BYTE;
  41980. if ( p === ShortType ) return gl.SHORT;
  41981. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  41982. if ( p === IntType ) return gl.INT;
  41983. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  41984. if ( p === FloatType ) return gl.FLOAT;
  41985. if ( p === HalfFloatType ) {
  41986. return gl.HALF_FLOAT;
  41987. }
  41988. if ( p === AlphaFormat ) return gl.ALPHA;
  41989. if ( p === RGBFormat ) return gl.RGB;
  41990. if ( p === RGBAFormat ) return gl.RGBA;
  41991. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  41992. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  41993. // WebGL2 formats.
  41994. if ( p === RedFormat ) return gl.RED;
  41995. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  41996. if ( p === RGFormat ) return gl.RG;
  41997. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  41998. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  41999. // S3TC
  42000. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  42001. if ( transfer === SRGBTransfer ) {
  42002. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  42003. if ( extension !== null ) {
  42004. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  42005. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  42006. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  42007. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  42008. } else {
  42009. return null;
  42010. }
  42011. } else {
  42012. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  42013. if ( extension !== null ) {
  42014. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  42015. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  42016. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  42017. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  42018. } else {
  42019. return null;
  42020. }
  42021. }
  42022. }
  42023. // PVRTC
  42024. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  42025. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  42026. if ( extension !== null ) {
  42027. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  42028. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  42029. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  42030. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  42031. } else {
  42032. return null;
  42033. }
  42034. }
  42035. // ETC
  42036. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  42037. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  42038. if ( extension !== null ) {
  42039. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  42040. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  42041. } else {
  42042. return null;
  42043. }
  42044. }
  42045. // ASTC
  42046. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  42047. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  42048. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  42049. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  42050. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  42051. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  42052. if ( extension !== null ) {
  42053. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  42054. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  42055. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  42056. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  42057. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  42058. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  42059. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  42060. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  42061. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  42062. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  42063. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  42064. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  42065. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  42066. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  42067. } else {
  42068. return null;
  42069. }
  42070. }
  42071. // BPTC
  42072. if ( p === RGBA_BPTC_Format ) {
  42073. extension = extensions.get( 'EXT_texture_compression_bptc' );
  42074. if ( extension !== null ) {
  42075. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  42076. } else {
  42077. return null;
  42078. }
  42079. }
  42080. // RGTC
  42081. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  42082. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  42083. if ( extension !== null ) {
  42084. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  42085. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  42086. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  42087. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  42088. } else {
  42089. return null;
  42090. }
  42091. }
  42092. //
  42093. if ( p === UnsignedInt248Type ) {
  42094. return gl.UNSIGNED_INT_24_8;
  42095. }
  42096. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  42097. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  42098. }
  42099. /**
  42100. * This method can be used to synchronize the CPU with the GPU by waiting until
  42101. * ongoing GPU commands have been completed.
  42102. *
  42103. * @private
  42104. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  42105. */
  42106. _clientWaitAsync() {
  42107. const { gl } = this;
  42108. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  42109. gl.flush();
  42110. return new Promise( ( resolve, reject ) => {
  42111. function test() {
  42112. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  42113. if ( res === gl.WAIT_FAILED ) {
  42114. gl.deleteSync( sync );
  42115. reject();
  42116. return;
  42117. }
  42118. if ( res === gl.TIMEOUT_EXPIRED ) {
  42119. requestAnimationFrame( test );
  42120. return;
  42121. }
  42122. gl.deleteSync( sync );
  42123. resolve();
  42124. }
  42125. test();
  42126. } );
  42127. }
  42128. }
  42129. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  42130. /**
  42131. * A WebGL 2 backend utility module for managing textures.
  42132. *
  42133. * @private
  42134. */
  42135. class WebGLTextureUtils {
  42136. /**
  42137. * Constructs a new utility object.
  42138. *
  42139. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42140. */
  42141. constructor( backend ) {
  42142. /**
  42143. * A reference to the WebGL 2 backend.
  42144. *
  42145. * @type {WebGLBackend}
  42146. */
  42147. this.backend = backend;
  42148. /**
  42149. * A reference to the rendering context.
  42150. *
  42151. * @type {WebGL2RenderingContext}
  42152. */
  42153. this.gl = backend.gl;
  42154. /**
  42155. * A reference to a backend module holding extension-related
  42156. * utility functions.
  42157. *
  42158. * @type {WebGLExtensions}
  42159. */
  42160. this.extensions = backend.extensions;
  42161. /**
  42162. * A dictionary for managing default textures. The key
  42163. * is the binding point (target), the value the WEbGL texture object.
  42164. *
  42165. * @type {Object<GLenum,WebGLTexture>}
  42166. */
  42167. this.defaultTextures = {};
  42168. if ( initialized === false ) {
  42169. this._init();
  42170. initialized = true;
  42171. }
  42172. }
  42173. /**
  42174. * Inits the state of the utility.
  42175. *
  42176. * @private
  42177. */
  42178. _init() {
  42179. const gl = this.gl;
  42180. // Store only WebGL constants here.
  42181. wrappingToGL = {
  42182. [ RepeatWrapping ]: gl.REPEAT,
  42183. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  42184. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  42185. };
  42186. filterToGL = {
  42187. [ NearestFilter ]: gl.NEAREST,
  42188. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  42189. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  42190. [ LinearFilter ]: gl.LINEAR,
  42191. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  42192. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  42193. };
  42194. compareToGL = {
  42195. [ NeverCompare ]: gl.NEVER,
  42196. [ AlwaysCompare ]: gl.ALWAYS,
  42197. [ LessCompare ]: gl.LESS,
  42198. [ LessEqualCompare ]: gl.LEQUAL,
  42199. [ EqualCompare ]: gl.EQUAL,
  42200. [ GreaterEqualCompare ]: gl.GEQUAL,
  42201. [ GreaterCompare ]: gl.GREATER,
  42202. [ NotEqualCompare ]: gl.NOTEQUAL
  42203. };
  42204. }
  42205. /**
  42206. * Returns the native texture type for the given texture.
  42207. *
  42208. * @param {Texture} texture - The texture.
  42209. * @return {GLenum} The native texture type.
  42210. */
  42211. getGLTextureType( texture ) {
  42212. const { gl } = this;
  42213. let glTextureType;
  42214. if ( texture.isCubeTexture === true ) {
  42215. glTextureType = gl.TEXTURE_CUBE_MAP;
  42216. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  42217. glTextureType = gl.TEXTURE_2D_ARRAY;
  42218. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  42219. glTextureType = gl.TEXTURE_3D;
  42220. } else {
  42221. glTextureType = gl.TEXTURE_2D;
  42222. }
  42223. return glTextureType;
  42224. }
  42225. /**
  42226. * Returns the native texture type for the given texture.
  42227. *
  42228. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  42229. * @param {GLenum} glFormat - The WebGL format.
  42230. * @param {GLenum} glType - The WebGL type.
  42231. * @param {string} colorSpace - The texture's color space.
  42232. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  42233. * @return {GLenum} The internal format.
  42234. */
  42235. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  42236. const { gl, extensions } = this;
  42237. if ( internalFormatName !== null ) {
  42238. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  42239. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  42240. }
  42241. let internalFormat = glFormat;
  42242. if ( glFormat === gl.RED ) {
  42243. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  42244. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  42245. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  42246. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  42247. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  42248. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  42249. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  42250. if ( glType === gl.INT ) internalFormat = gl.R32I;
  42251. }
  42252. if ( glFormat === gl.RED_INTEGER ) {
  42253. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  42254. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  42255. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  42256. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  42257. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  42258. if ( glType === gl.INT ) internalFormat = gl.R32I;
  42259. }
  42260. if ( glFormat === gl.RG ) {
  42261. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  42262. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  42263. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  42264. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  42265. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  42266. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  42267. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  42268. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  42269. }
  42270. if ( glFormat === gl.RG_INTEGER ) {
  42271. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  42272. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  42273. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  42274. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  42275. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  42276. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  42277. }
  42278. if ( glFormat === gl.RGB ) {
  42279. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  42280. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  42281. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  42282. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  42283. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  42284. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  42285. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  42286. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  42287. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  42288. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  42289. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  42290. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  42291. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  42292. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  42293. }
  42294. if ( glFormat === gl.RGB_INTEGER ) {
  42295. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  42296. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  42297. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  42298. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  42299. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  42300. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  42301. }
  42302. if ( glFormat === gl.RGBA ) {
  42303. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  42304. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  42305. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  42306. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  42307. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  42308. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  42309. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  42310. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  42311. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  42312. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  42313. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  42314. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  42315. }
  42316. if ( glFormat === gl.RGBA_INTEGER ) {
  42317. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  42318. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  42319. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  42320. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  42321. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  42322. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  42323. }
  42324. if ( glFormat === gl.DEPTH_COMPONENT ) {
  42325. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  42326. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  42327. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  42328. }
  42329. if ( glFormat === gl.DEPTH_STENCIL ) {
  42330. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  42331. }
  42332. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  42333. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  42334. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  42335. extensions.get( 'EXT_color_buffer_float' );
  42336. }
  42337. return internalFormat;
  42338. }
  42339. /**
  42340. * Sets the texture parameters for the given texture.
  42341. *
  42342. * @param {GLenum} textureType - The texture type.
  42343. * @param {Texture} texture - The texture.
  42344. */
  42345. setTextureParameters( textureType, texture ) {
  42346. const { gl, extensions, backend } = this;
  42347. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  42348. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  42349. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  42350. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  42351. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  42352. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  42353. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  42354. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  42355. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  42356. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  42357. // WebGL 2 does not support wrapping for depth 2D array textures
  42358. if ( ! texture.isArrayTexture ) {
  42359. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  42360. }
  42361. }
  42362. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  42363. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  42364. // follow WebGPU backend mapping for texture filtering
  42365. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  42366. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  42367. if ( texture.compareFunction ) {
  42368. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  42369. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  42370. }
  42371. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  42372. if ( texture.magFilter === NearestFilter ) return;
  42373. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  42374. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  42375. if ( texture.anisotropy > 1 ) {
  42376. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  42377. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  42378. }
  42379. }
  42380. }
  42381. /**
  42382. * Creates a default texture for the given texture that can be used
  42383. * as a placeholder until the actual texture is ready for usage.
  42384. *
  42385. * @param {Texture} texture - The texture to create a default texture for.
  42386. */
  42387. createDefaultTexture( texture ) {
  42388. const { gl, backend, defaultTextures } = this;
  42389. const glTextureType = this.getGLTextureType( texture );
  42390. let textureGPU = defaultTextures[ glTextureType ];
  42391. if ( textureGPU === undefined ) {
  42392. textureGPU = gl.createTexture();
  42393. backend.state.bindTexture( glTextureType, textureGPU );
  42394. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  42395. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  42396. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  42397. defaultTextures[ glTextureType ] = textureGPU;
  42398. }
  42399. backend.set( texture, {
  42400. textureGPU,
  42401. glTextureType,
  42402. isDefault: true
  42403. } );
  42404. }
  42405. /**
  42406. * Defines a texture on the GPU for the given texture object.
  42407. *
  42408. * @param {Texture} texture - The texture.
  42409. * @param {Object} [options={}] - Optional configuration parameter.
  42410. * @return {undefined}
  42411. */
  42412. createTexture( texture, options ) {
  42413. const { gl, backend } = this;
  42414. const { levels, width, height, depth } = options;
  42415. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  42416. const glType = backend.utils.convert( texture.type );
  42417. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  42418. const textureGPU = gl.createTexture();
  42419. const glTextureType = this.getGLTextureType( texture );
  42420. backend.state.bindTexture( glTextureType, textureGPU );
  42421. this.setTextureParameters( glTextureType, texture );
  42422. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  42423. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  42424. } else if ( texture.isData3DTexture ) {
  42425. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  42426. } else if ( ! texture.isVideoTexture ) {
  42427. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  42428. }
  42429. backend.set( texture, {
  42430. textureGPU,
  42431. glTextureType,
  42432. glFormat,
  42433. glType,
  42434. glInternalFormat
  42435. } );
  42436. }
  42437. /**
  42438. * Uploads texture buffer data to the GPU memory.
  42439. *
  42440. * @param {WebGLBuffer} buffer - The buffer data.
  42441. * @param {Texture} texture - The texture,
  42442. */
  42443. copyBufferToTexture( buffer, texture ) {
  42444. const { gl, backend } = this;
  42445. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  42446. const { width, height } = texture.source.data;
  42447. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  42448. backend.state.bindTexture( glTextureType, textureGPU );
  42449. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  42450. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  42451. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  42452. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  42453. backend.state.unbindTexture();
  42454. // debug
  42455. // const framebuffer = gl.createFramebuffer();
  42456. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  42457. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  42458. // const readout = new Float32Array( width * height * 4 );
  42459. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  42460. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  42461. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  42462. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  42463. // console.log( readout );
  42464. }
  42465. /**
  42466. * Uploads the updated texture data to the GPU.
  42467. *
  42468. * @param {Texture} texture - The texture.
  42469. * @param {Object} [options={}] - Optional configuration parameter.
  42470. */
  42471. updateTexture( texture, options ) {
  42472. const { gl } = this;
  42473. const { width, height } = options;
  42474. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  42475. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  42476. return;
  42477. const getImage = ( source ) => {
  42478. if ( source.isDataTexture ) {
  42479. return source.image.data;
  42480. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  42481. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  42482. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  42483. source instanceof OffscreenCanvas ) {
  42484. return source;
  42485. }
  42486. return source.data;
  42487. };
  42488. this.backend.state.bindTexture( glTextureType, textureGPU );
  42489. this.setTextureParameters( glTextureType, texture );
  42490. if ( texture.isCompressedTexture ) {
  42491. const mipmaps = texture.mipmaps;
  42492. const image = options.image;
  42493. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42494. const mipmap = mipmaps[ i ];
  42495. if ( texture.isCompressedArrayTexture ) {
  42496. if ( texture.format !== gl.RGBA ) {
  42497. if ( glFormat !== null ) {
  42498. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  42499. } else {
  42500. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  42501. }
  42502. } else {
  42503. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  42504. }
  42505. } else {
  42506. if ( glFormat !== null ) {
  42507. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  42508. } else {
  42509. console.warn( 'Unsupported compressed texture format' );
  42510. }
  42511. }
  42512. }
  42513. } else if ( texture.isCubeTexture ) {
  42514. const images = options.images;
  42515. for ( let i = 0; i < 6; i ++ ) {
  42516. const image = getImage( images[ i ] );
  42517. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  42518. }
  42519. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  42520. const image = options.image;
  42521. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  42522. } else if ( texture.isData3DTexture ) {
  42523. const image = options.image;
  42524. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  42525. } else if ( texture.isVideoTexture ) {
  42526. texture.update();
  42527. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  42528. } else {
  42529. const image = getImage( options.image );
  42530. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  42531. }
  42532. }
  42533. /**
  42534. * Generates mipmaps for the given texture.
  42535. *
  42536. * @param {Texture} texture - The texture.
  42537. */
  42538. generateMipmaps( texture ) {
  42539. const { gl, backend } = this;
  42540. const { textureGPU, glTextureType } = backend.get( texture );
  42541. backend.state.bindTexture( glTextureType, textureGPU );
  42542. gl.generateMipmap( glTextureType );
  42543. }
  42544. /**
  42545. * Deallocates the render buffers of the given render target.
  42546. *
  42547. * @param {RenderTarget} renderTarget - The render target.
  42548. */
  42549. deallocateRenderBuffers( renderTarget ) {
  42550. const { gl, backend } = this;
  42551. // remove framebuffer reference
  42552. if ( renderTarget ) {
  42553. const renderContextData = backend.get( renderTarget );
  42554. renderContextData.renderBufferStorageSetup = undefined;
  42555. if ( renderContextData.framebuffers ) {
  42556. for ( const cacheKey in renderContextData.framebuffers ) {
  42557. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  42558. }
  42559. delete renderContextData.framebuffers;
  42560. }
  42561. if ( renderContextData.depthRenderbuffer ) {
  42562. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  42563. delete renderContextData.depthRenderbuffer;
  42564. }
  42565. if ( renderContextData.stencilRenderbuffer ) {
  42566. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  42567. delete renderContextData.stencilRenderbuffer;
  42568. }
  42569. if ( renderContextData.msaaFrameBuffer ) {
  42570. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  42571. delete renderContextData.msaaFrameBuffer;
  42572. }
  42573. if ( renderContextData.msaaRenderbuffers ) {
  42574. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  42575. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  42576. }
  42577. delete renderContextData.msaaRenderbuffers;
  42578. }
  42579. }
  42580. }
  42581. /**
  42582. * Destroys the GPU data for the given texture object.
  42583. *
  42584. * @param {Texture} texture - The texture.
  42585. */
  42586. destroyTexture( texture ) {
  42587. const { gl, backend } = this;
  42588. const { textureGPU, renderTarget } = backend.get( texture );
  42589. this.deallocateRenderBuffers( renderTarget );
  42590. gl.deleteTexture( textureGPU );
  42591. backend.delete( texture );
  42592. }
  42593. /**
  42594. * Copies data of the given source texture to the given destination texture.
  42595. *
  42596. * @param {Texture} srcTexture - The source texture.
  42597. * @param {Texture} dstTexture - The destination texture.
  42598. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  42599. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  42600. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42601. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42602. */
  42603. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  42604. const { gl, backend } = this;
  42605. const { state } = this.backend;
  42606. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  42607. state.bindTexture( glTextureType, dstTextureGPU );
  42608. // gather the necessary dimensions to copy
  42609. let width, height, depth, minX, minY, minZ;
  42610. let dstX, dstY, dstZ;
  42611. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  42612. if ( srcRegion !== null ) {
  42613. width = srcRegion.max.x - srcRegion.min.x;
  42614. height = srcRegion.max.y - srcRegion.min.y;
  42615. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  42616. minX = srcRegion.min.x;
  42617. minY = srcRegion.min.y;
  42618. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  42619. } else {
  42620. const levelScale = Math.pow( 2, - srcLevel );
  42621. width = Math.floor( image.width * levelScale );
  42622. height = Math.floor( image.height * levelScale );
  42623. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  42624. depth = image.depth;
  42625. } else if ( srcTexture.isData3DTexture ) {
  42626. depth = Math.floor( image.depth * levelScale );
  42627. } else {
  42628. depth = 1;
  42629. }
  42630. minX = 0;
  42631. minY = 0;
  42632. minZ = 0;
  42633. }
  42634. if ( dstPosition !== null ) {
  42635. dstX = dstPosition.x;
  42636. dstY = dstPosition.y;
  42637. dstZ = dstPosition.z;
  42638. } else {
  42639. dstX = 0;
  42640. dstY = 0;
  42641. dstZ = 0;
  42642. }
  42643. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  42644. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  42645. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  42646. // used for copying data from cpu
  42647. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  42648. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  42649. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  42650. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  42651. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  42652. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  42653. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  42654. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  42655. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  42656. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  42657. // set up the src texture
  42658. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  42659. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  42660. const srcTextureData = backend.get( srcTexture );
  42661. const dstTextureData = backend.get( dstTexture );
  42662. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  42663. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  42664. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  42665. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  42666. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  42667. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  42668. let mask = gl.COLOR_BUFFER_BIT;
  42669. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  42670. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  42671. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  42672. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  42673. } else {
  42674. if ( isDst3D ) {
  42675. // copy data into the 3d texture
  42676. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  42677. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  42678. } else if ( dstTexture.isCompressedArrayTexture ) {
  42679. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  42680. } else {
  42681. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  42682. }
  42683. } else {
  42684. // copy data into the 2d texture
  42685. if ( srcTexture.isDataTexture ) {
  42686. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  42687. } else if ( srcTexture.isCompressedTexture ) {
  42688. gl.compressedTexSubImage2D( glTextureType, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  42689. } else {
  42690. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  42691. }
  42692. }
  42693. }
  42694. // reset values
  42695. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  42696. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  42697. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  42698. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  42699. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  42700. // Generate mipmaps only when copying level 0
  42701. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  42702. gl.generateMipmap( glTextureType );
  42703. }
  42704. state.unbindTexture();
  42705. }
  42706. /**
  42707. * Copies the current bound framebuffer to the given texture.
  42708. *
  42709. * @param {Texture} texture - The destination texture.
  42710. * @param {RenderContext} renderContext - The render context.
  42711. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  42712. */
  42713. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  42714. const { gl } = this;
  42715. const { state } = this.backend;
  42716. const { textureGPU } = this.backend.get( texture );
  42717. const { x, y, z: width, w: height } = rectangle;
  42718. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  42719. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  42720. if ( requireDrawFrameBuffer ) {
  42721. const partial = ( x !== 0 || y !== 0 );
  42722. let mask;
  42723. let attachment;
  42724. if ( texture.isDepthTexture === true ) {
  42725. mask = gl.DEPTH_BUFFER_BIT;
  42726. attachment = gl.DEPTH_ATTACHMENT;
  42727. if ( renderContext.stencil ) {
  42728. mask |= gl.STENCIL_BUFFER_BIT;
  42729. }
  42730. } else {
  42731. mask = gl.COLOR_BUFFER_BIT;
  42732. attachment = gl.COLOR_ATTACHMENT0;
  42733. }
  42734. if ( partial ) {
  42735. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  42736. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  42737. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42738. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  42739. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  42740. const flippedY = srcHeight - y - height;
  42741. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  42742. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  42743. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  42744. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  42745. state.unbindTexture();
  42746. } else {
  42747. const fb = gl.createFramebuffer();
  42748. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  42749. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  42750. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  42751. gl.deleteFramebuffer( fb );
  42752. }
  42753. } else {
  42754. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  42755. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  42756. state.unbindTexture();
  42757. }
  42758. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  42759. this.backend._setFramebuffer( renderContext );
  42760. }
  42761. /**
  42762. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  42763. *
  42764. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  42765. * @param {RenderContext} renderContext - The render context.
  42766. * @param {number} samples - The MSAA sample count.
  42767. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  42768. */
  42769. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  42770. const { gl } = this;
  42771. const renderTarget = renderContext.renderTarget;
  42772. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  42773. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  42774. if ( depthBuffer && ! stencilBuffer ) {
  42775. let glInternalFormat = gl.DEPTH_COMPONENT24;
  42776. if ( useMultisampledRTT === true ) {
  42777. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  42778. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  42779. } else if ( samples > 0 ) {
  42780. if ( depthTexture && depthTexture.isDepthTexture ) {
  42781. if ( depthTexture.type === gl.FLOAT ) {
  42782. glInternalFormat = gl.DEPTH_COMPONENT32F;
  42783. }
  42784. }
  42785. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  42786. } else {
  42787. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  42788. }
  42789. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  42790. } else if ( depthBuffer && stencilBuffer ) {
  42791. if ( samples > 0 ) {
  42792. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  42793. } else {
  42794. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  42795. }
  42796. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  42797. }
  42798. }
  42799. /**
  42800. * Returns texture data as a typed array.
  42801. *
  42802. * @async
  42803. * @param {Texture} texture - The texture to copy.
  42804. * @param {number} x - The x coordinate of the copy origin.
  42805. * @param {number} y - The y coordinate of the copy origin.
  42806. * @param {number} width - The width of the copy.
  42807. * @param {number} height - The height of the copy.
  42808. * @param {number} faceIndex - The face index.
  42809. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42810. */
  42811. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42812. const { backend, gl } = this;
  42813. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  42814. const fb = gl.createFramebuffer();
  42815. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  42816. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  42817. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  42818. const typedArrayType = this._getTypedArrayType( glType );
  42819. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  42820. const elementCount = width * height;
  42821. const byteLength = elementCount * bytesPerTexel;
  42822. const buffer = gl.createBuffer();
  42823. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  42824. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  42825. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  42826. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  42827. await backend.utils._clientWaitAsync();
  42828. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  42829. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  42830. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  42831. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  42832. gl.deleteFramebuffer( fb );
  42833. return dstBuffer;
  42834. }
  42835. /**
  42836. * Returns the corresponding typed array type for the given WebGL data type.
  42837. *
  42838. * @private
  42839. * @param {GLenum} glType - The WebGL data type.
  42840. * @return {TypedArray.constructor} The typed array type.
  42841. */
  42842. _getTypedArrayType( glType ) {
  42843. const { gl } = this;
  42844. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  42845. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  42846. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  42847. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  42848. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  42849. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  42850. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  42851. if ( glType === gl.FLOAT ) return Float32Array;
  42852. throw new Error( `Unsupported WebGL type: ${glType}` );
  42853. }
  42854. /**
  42855. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  42856. *
  42857. * @private
  42858. * @param {GLenum} glType - The WebGL data type.
  42859. * @param {GLenum} glFormat - The WebGL texture format.
  42860. * @return {number} The bytes-per-texel.
  42861. */
  42862. _getBytesPerTexel( glType, glFormat ) {
  42863. const { gl } = this;
  42864. let bytesPerComponent = 0;
  42865. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  42866. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  42867. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  42868. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  42869. glType === gl.UNSIGNED_SHORT ||
  42870. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  42871. if ( glType === gl.UNSIGNED_INT ||
  42872. glType === gl.FLOAT ) bytesPerComponent = 4;
  42873. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  42874. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  42875. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  42876. }
  42877. }
  42878. /**
  42879. * A WebGL 2 backend utility module for managing extensions.
  42880. *
  42881. * @private
  42882. */
  42883. class WebGLExtensions {
  42884. /**
  42885. * Constructs a new utility object.
  42886. *
  42887. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42888. */
  42889. constructor( backend ) {
  42890. /**
  42891. * A reference to the WebGL 2 backend.
  42892. *
  42893. * @type {WebGLBackend}
  42894. */
  42895. this.backend = backend;
  42896. /**
  42897. * A reference to the rendering context.
  42898. *
  42899. * @type {WebGL2RenderingContext}
  42900. */
  42901. this.gl = this.backend.gl;
  42902. /**
  42903. * A list with all the supported WebGL extensions.
  42904. *
  42905. * @type {Array<string>}
  42906. */
  42907. this.availableExtensions = this.gl.getSupportedExtensions();
  42908. /**
  42909. * A dictionary with requested WebGL extensions.
  42910. * The key is the name of the extension, the value
  42911. * the requested extension object.
  42912. *
  42913. * @type {Object<string,Object>}
  42914. */
  42915. this.extensions = {};
  42916. }
  42917. /**
  42918. * Returns the extension object for the given extension name.
  42919. *
  42920. * @param {string} name - The extension name.
  42921. * @return {Object} The extension object.
  42922. */
  42923. get( name ) {
  42924. let extension = this.extensions[ name ];
  42925. if ( extension === undefined ) {
  42926. extension = this.gl.getExtension( name );
  42927. this.extensions[ name ] = extension;
  42928. }
  42929. return extension;
  42930. }
  42931. /**
  42932. * Returns `true` if the requested extension is available.
  42933. *
  42934. * @param {string} name - The extension name.
  42935. * @return {boolean} Whether the given extension is available or not.
  42936. */
  42937. has( name ) {
  42938. return this.availableExtensions.includes( name );
  42939. }
  42940. }
  42941. /**
  42942. * A WebGL 2 backend utility module for managing the device's capabilities.
  42943. *
  42944. * @private
  42945. */
  42946. class WebGLCapabilities {
  42947. /**
  42948. * Constructs a new utility object.
  42949. *
  42950. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42951. */
  42952. constructor( backend ) {
  42953. /**
  42954. * A reference to the WebGL 2 backend.
  42955. *
  42956. * @type {WebGLBackend}
  42957. */
  42958. this.backend = backend;
  42959. /**
  42960. * This value holds the cached max anisotropy value.
  42961. *
  42962. * @type {?number}
  42963. * @default null
  42964. */
  42965. this.maxAnisotropy = null;
  42966. }
  42967. /**
  42968. * Returns the maximum anisotropy texture filtering value. This value
  42969. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  42970. * WebGL extension.
  42971. *
  42972. * @return {number} The maximum anisotropy texture filtering value.
  42973. */
  42974. getMaxAnisotropy() {
  42975. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  42976. const gl = this.backend.gl;
  42977. const extensions = this.backend.extensions;
  42978. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  42979. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  42980. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  42981. } else {
  42982. this.maxAnisotropy = 0;
  42983. }
  42984. return this.maxAnisotropy;
  42985. }
  42986. }
  42987. const GLFeatureName = {
  42988. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  42989. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  42990. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  42991. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  42992. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  42993. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  42994. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  42995. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  42996. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  42997. 'OVR_multiview2': 'OVR_multiview2'
  42998. };
  42999. class WebGLBufferRenderer {
  43000. constructor( backend ) {
  43001. this.gl = backend.gl;
  43002. this.extensions = backend.extensions;
  43003. this.info = backend.renderer.info;
  43004. this.mode = null;
  43005. this.index = 0;
  43006. this.type = null;
  43007. this.object = null;
  43008. }
  43009. render( start, count ) {
  43010. const { gl, mode, object, type, info, index } = this;
  43011. if ( index !== 0 ) {
  43012. gl.drawElements( mode, count, type, start );
  43013. } else {
  43014. gl.drawArrays( mode, start, count );
  43015. }
  43016. info.update( object, count, 1 );
  43017. }
  43018. renderInstances( start, count, primcount ) {
  43019. const { gl, mode, type, index, object, info } = this;
  43020. if ( primcount === 0 ) return;
  43021. if ( index !== 0 ) {
  43022. gl.drawElementsInstanced( mode, count, type, start, primcount );
  43023. } else {
  43024. gl.drawArraysInstanced( mode, start, count, primcount );
  43025. }
  43026. info.update( object, count, primcount );
  43027. }
  43028. renderMultiDraw( starts, counts, drawCount ) {
  43029. const { extensions, mode, object, info } = this;
  43030. if ( drawCount === 0 ) return;
  43031. const extension = extensions.get( 'WEBGL_multi_draw' );
  43032. if ( extension === null ) {
  43033. for ( let i = 0; i < drawCount; i ++ ) {
  43034. this.render( starts[ i ], counts[ i ] );
  43035. }
  43036. } else {
  43037. if ( this.index !== 0 ) {
  43038. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  43039. } else {
  43040. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  43041. }
  43042. let elementCount = 0;
  43043. for ( let i = 0; i < drawCount; i ++ ) {
  43044. elementCount += counts[ i ];
  43045. }
  43046. info.update( object, elementCount, 1 );
  43047. }
  43048. }
  43049. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  43050. const { extensions, mode, object, info } = this;
  43051. if ( drawCount === 0 ) return;
  43052. const extension = extensions.get( 'WEBGL_multi_draw' );
  43053. if ( extension === null ) {
  43054. for ( let i = 0; i < drawCount; i ++ ) {
  43055. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  43056. }
  43057. } else {
  43058. if ( this.index !== 0 ) {
  43059. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  43060. } else {
  43061. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  43062. }
  43063. let elementCount = 0;
  43064. for ( let i = 0; i < drawCount; i ++ ) {
  43065. elementCount += counts[ i ] * primcount[ i ];
  43066. }
  43067. info.update( object, elementCount, 1 );
  43068. }
  43069. }
  43070. //
  43071. }
  43072. /**
  43073. * Abstract base class of a timestamp query pool.
  43074. *
  43075. * @abstract
  43076. */
  43077. class TimestampQueryPool {
  43078. /**
  43079. * Creates a new timestamp query pool.
  43080. *
  43081. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  43082. */
  43083. constructor( maxQueries = 256 ) {
  43084. /**
  43085. * Whether to track timestamps or not.
  43086. *
  43087. * @type {boolean}
  43088. * @default true
  43089. */
  43090. this.trackTimestamp = true;
  43091. /**
  43092. * Maximum number of queries this pool can hold.
  43093. *
  43094. * @type {number}
  43095. * @default 256
  43096. */
  43097. this.maxQueries = maxQueries;
  43098. /**
  43099. * How many queries allocated so far.
  43100. *
  43101. * @type {number}
  43102. * @default 0
  43103. */
  43104. this.currentQueryIndex = 0;
  43105. /**
  43106. * Tracks offsets for different contexts.
  43107. *
  43108. * @type {Map<string, number>}
  43109. */
  43110. this.queryOffsets = new Map();
  43111. /**
  43112. * Whether the pool has been disposed or not.
  43113. *
  43114. * @type {boolean}
  43115. * @default false
  43116. */
  43117. this.isDisposed = false;
  43118. /**
  43119. * TODO
  43120. *
  43121. * @type {number}
  43122. * @default 0
  43123. */
  43124. this.lastValue = 0;
  43125. /**
  43126. * TODO
  43127. *
  43128. * @type {boolean}
  43129. * @default false
  43130. */
  43131. this.pendingResolve = false;
  43132. }
  43133. /**
  43134. * Allocate queries for a specific renderContext.
  43135. *
  43136. * @abstract
  43137. * @param {Object} renderContext - The render context to allocate queries for.
  43138. * @returns {?number}
  43139. */
  43140. allocateQueriesForContext( /* renderContext */ ) {}
  43141. /**
  43142. * Resolve all timestamps and return data (or process them).
  43143. *
  43144. * @abstract
  43145. * @async
  43146. * @returns {Promise<number>|number} The resolved timestamp value.
  43147. */
  43148. async resolveQueriesAsync() {}
  43149. /**
  43150. * Dispose of the query pool.
  43151. *
  43152. * @abstract
  43153. */
  43154. dispose() {}
  43155. }
  43156. /**
  43157. * Manages a pool of WebGL timestamp queries for performance measurement.
  43158. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  43159. *
  43160. * @augments TimestampQueryPool
  43161. */
  43162. class WebGLTimestampQueryPool extends TimestampQueryPool {
  43163. /**
  43164. * Creates a new WebGL timestamp query pool.
  43165. *
  43166. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  43167. * @param {string} type - The type identifier for this query pool.
  43168. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  43169. */
  43170. constructor( gl, type, maxQueries = 2048 ) {
  43171. super( maxQueries );
  43172. this.gl = gl;
  43173. this.type = type;
  43174. // Check for timer query extensions
  43175. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  43176. gl.getExtension( 'EXT_disjoint_timer_query' );
  43177. if ( ! this.ext ) {
  43178. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  43179. this.trackTimestamp = false;
  43180. return;
  43181. }
  43182. // Create query objects
  43183. this.queries = [];
  43184. for ( let i = 0; i < this.maxQueries; i ++ ) {
  43185. this.queries.push( gl.createQuery() );
  43186. }
  43187. this.activeQuery = null;
  43188. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  43189. }
  43190. /**
  43191. * Allocates a pair of queries for a given render context.
  43192. *
  43193. * @param {Object} renderContext - The render context to allocate queries for.
  43194. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  43195. */
  43196. allocateQueriesForContext( renderContext ) {
  43197. if ( ! this.trackTimestamp ) return null;
  43198. // Check if we have enough space for a new query pair
  43199. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  43200. warnOnce( `WebGPUTimestampQueryPool [${ this.type }]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${ this.type.toUpperCase() } ).` );
  43201. return null;
  43202. }
  43203. const baseOffset = this.currentQueryIndex;
  43204. this.currentQueryIndex += 2;
  43205. // Initialize query states
  43206. this.queryStates.set( baseOffset, 'inactive' );
  43207. this.queryOffsets.set( renderContext.id, baseOffset );
  43208. return baseOffset;
  43209. }
  43210. /**
  43211. * Begins a timestamp query for the specified render context.
  43212. *
  43213. * @param {Object} renderContext - The render context to begin timing for.
  43214. */
  43215. beginQuery( renderContext ) {
  43216. if ( ! this.trackTimestamp || this.isDisposed ) {
  43217. return;
  43218. }
  43219. const baseOffset = this.queryOffsets.get( renderContext.id );
  43220. if ( baseOffset == null ) {
  43221. return;
  43222. }
  43223. // Don't start a new query if there's an active one
  43224. if ( this.activeQuery !== null ) {
  43225. return;
  43226. }
  43227. const query = this.queries[ baseOffset ];
  43228. if ( ! query ) {
  43229. return;
  43230. }
  43231. try {
  43232. // Only begin if query is inactive
  43233. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  43234. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  43235. this.activeQuery = baseOffset;
  43236. this.queryStates.set( baseOffset, 'started' );
  43237. }
  43238. } catch ( error ) {
  43239. console.error( 'Error in beginQuery:', error );
  43240. this.activeQuery = null;
  43241. this.queryStates.set( baseOffset, 'inactive' );
  43242. }
  43243. }
  43244. /**
  43245. * Ends the active timestamp query for the specified render context.
  43246. *
  43247. * @param {Object} renderContext - The render context to end timing for.
  43248. * @param {string} renderContext.id - Unique identifier for the render context.
  43249. */
  43250. endQuery( renderContext ) {
  43251. if ( ! this.trackTimestamp || this.isDisposed ) {
  43252. return;
  43253. }
  43254. const baseOffset = this.queryOffsets.get( renderContext.id );
  43255. if ( baseOffset == null ) {
  43256. return;
  43257. }
  43258. // Only end if this is the active query
  43259. if ( this.activeQuery !== baseOffset ) {
  43260. return;
  43261. }
  43262. try {
  43263. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  43264. this.queryStates.set( baseOffset, 'ended' );
  43265. this.activeQuery = null;
  43266. } catch ( error ) {
  43267. console.error( 'Error in endQuery:', error );
  43268. // Reset state on error
  43269. this.queryStates.set( baseOffset, 'inactive' );
  43270. this.activeQuery = null;
  43271. }
  43272. }
  43273. /**
  43274. * Asynchronously resolves all completed queries and returns the total duration.
  43275. *
  43276. * @async
  43277. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  43278. */
  43279. async resolveQueriesAsync() {
  43280. if ( ! this.trackTimestamp || this.pendingResolve ) {
  43281. return this.lastValue;
  43282. }
  43283. this.pendingResolve = true;
  43284. try {
  43285. // Wait for all ended queries to complete
  43286. const resolvePromises = [];
  43287. for ( const [ baseOffset, state ] of this.queryStates ) {
  43288. if ( state === 'ended' ) {
  43289. const query = this.queries[ baseOffset ];
  43290. resolvePromises.push( this.resolveQuery( query ) );
  43291. }
  43292. }
  43293. if ( resolvePromises.length === 0 ) {
  43294. return this.lastValue;
  43295. }
  43296. const results = await Promise.all( resolvePromises );
  43297. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  43298. // Store the last valid result
  43299. this.lastValue = totalDuration;
  43300. // Reset states
  43301. this.currentQueryIndex = 0;
  43302. this.queryOffsets.clear();
  43303. this.queryStates.clear();
  43304. this.activeQuery = null;
  43305. return totalDuration;
  43306. } catch ( error ) {
  43307. console.error( 'Error resolving queries:', error );
  43308. return this.lastValue;
  43309. } finally {
  43310. this.pendingResolve = false;
  43311. }
  43312. }
  43313. /**
  43314. * Resolves a single query, checking for completion and disjoint operation.
  43315. *
  43316. * @async
  43317. * @param {WebGLQuery} query - The query object to resolve.
  43318. * @returns {Promise<number>} The elapsed time in milliseconds.
  43319. */
  43320. async resolveQuery( query ) {
  43321. return new Promise( ( resolve ) => {
  43322. if ( this.isDisposed ) {
  43323. resolve( this.lastValue );
  43324. return;
  43325. }
  43326. let timeoutId;
  43327. let isResolved = false;
  43328. const cleanup = () => {
  43329. if ( timeoutId ) {
  43330. clearTimeout( timeoutId );
  43331. timeoutId = null;
  43332. }
  43333. };
  43334. const finalizeResolution = ( value ) => {
  43335. if ( ! isResolved ) {
  43336. isResolved = true;
  43337. cleanup();
  43338. resolve( value );
  43339. }
  43340. };
  43341. const checkQuery = () => {
  43342. if ( this.isDisposed ) {
  43343. finalizeResolution( this.lastValue );
  43344. return;
  43345. }
  43346. try {
  43347. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  43348. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  43349. if ( disjoint ) {
  43350. finalizeResolution( this.lastValue );
  43351. return;
  43352. }
  43353. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  43354. if ( ! available ) {
  43355. timeoutId = setTimeout( checkQuery, 1 );
  43356. return;
  43357. }
  43358. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  43359. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  43360. } catch ( error ) {
  43361. console.error( 'Error checking query:', error );
  43362. resolve( this.lastValue );
  43363. }
  43364. };
  43365. checkQuery();
  43366. } );
  43367. }
  43368. /**
  43369. * Releases all resources held by this query pool.
  43370. * This includes deleting all query objects and clearing internal state.
  43371. */
  43372. dispose() {
  43373. if ( this.isDisposed ) {
  43374. return;
  43375. }
  43376. this.isDisposed = true;
  43377. if ( ! this.trackTimestamp ) return;
  43378. for ( const query of this.queries ) {
  43379. this.gl.deleteQuery( query );
  43380. }
  43381. this.queries = [];
  43382. this.queryStates.clear();
  43383. this.queryOffsets.clear();
  43384. this.lastValue = 0;
  43385. this.activeQuery = null;
  43386. }
  43387. }
  43388. /**
  43389. * A backend implementation targeting WebGL 2.
  43390. *
  43391. * @private
  43392. * @augments Backend
  43393. */
  43394. class WebGLBackend extends Backend {
  43395. /**
  43396. * WebGLBackend options.
  43397. *
  43398. * @typedef {Object} WebGLBackend~Options
  43399. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  43400. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  43401. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  43402. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  43403. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  43404. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  43405. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  43406. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  43407. */
  43408. /**
  43409. * Constructs a new WebGPU backend.
  43410. *
  43411. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  43412. */
  43413. constructor( parameters = {} ) {
  43414. super( parameters );
  43415. /**
  43416. * This flag can be used for type testing.
  43417. *
  43418. * @type {boolean}
  43419. * @readonly
  43420. * @default true
  43421. */
  43422. this.isWebGLBackend = true;
  43423. /**
  43424. * A reference to a backend module holding shader attribute-related
  43425. * utility functions.
  43426. *
  43427. * @type {?WebGLAttributeUtils}
  43428. * @default null
  43429. */
  43430. this.attributeUtils = null;
  43431. /**
  43432. * A reference to a backend module holding extension-related
  43433. * utility functions.
  43434. *
  43435. * @type {?WebGLExtensions}
  43436. * @default null
  43437. */
  43438. this.extensions = null;
  43439. /**
  43440. * A reference to a backend module holding capability-related
  43441. * utility functions.
  43442. *
  43443. * @type {?WebGLCapabilities}
  43444. * @default null
  43445. */
  43446. this.capabilities = null;
  43447. /**
  43448. * A reference to a backend module holding texture-related
  43449. * utility functions.
  43450. *
  43451. * @type {?WebGLTextureUtils}
  43452. * @default null
  43453. */
  43454. this.textureUtils = null;
  43455. /**
  43456. * A reference to a backend module holding renderer-related
  43457. * utility functions.
  43458. *
  43459. * @type {?WebGLBufferRenderer}
  43460. * @default null
  43461. */
  43462. this.bufferRenderer = null;
  43463. /**
  43464. * A reference to the rendering context.
  43465. *
  43466. * @type {?WebGL2RenderingContext}
  43467. * @default null
  43468. */
  43469. this.gl = null;
  43470. /**
  43471. * A reference to a backend module holding state-related
  43472. * utility functions.
  43473. *
  43474. * @type {?WebGLState}
  43475. * @default null
  43476. */
  43477. this.state = null;
  43478. /**
  43479. * A reference to a backend module holding common
  43480. * utility functions.
  43481. *
  43482. * @type {?WebGLUtils}
  43483. * @default null
  43484. */
  43485. this.utils = null;
  43486. /**
  43487. * Dictionary for caching VAOs.
  43488. *
  43489. * @type {Object<string,WebGLVertexArrayObject>}
  43490. */
  43491. this.vaoCache = {};
  43492. /**
  43493. * Dictionary for caching transform feedback objects.
  43494. *
  43495. * @type {Object<string,WebGLTransformFeedback>}
  43496. */
  43497. this.transformFeedbackCache = {};
  43498. /**
  43499. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  43500. * Only relevant when using compute shaders.
  43501. *
  43502. * @type {boolean}
  43503. * @default false
  43504. */
  43505. this.discard = false;
  43506. /**
  43507. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  43508. * device does not support the extension.
  43509. *
  43510. * @type {?EXTDisjointTimerQueryWebGL2}
  43511. * @default null
  43512. */
  43513. this.disjoint = null;
  43514. /**
  43515. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  43516. * device does not support the extension.
  43517. *
  43518. * @type {?KHRParallelShaderCompile}
  43519. * @default null
  43520. */
  43521. this.parallel = null;
  43522. /**
  43523. * A reference to the current render context.
  43524. *
  43525. * @private
  43526. * @type {RenderContext}
  43527. * @default null
  43528. */
  43529. this._currentContext = null;
  43530. /**
  43531. * A unique collection of bindings.
  43532. *
  43533. * @private
  43534. * @type {WeakSet}
  43535. */
  43536. this._knownBindings = new WeakSet();
  43537. /**
  43538. * Whether the device supports framebuffers invalidation or not.
  43539. *
  43540. * @private
  43541. * @type {boolean}
  43542. */
  43543. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  43544. /**
  43545. * The target framebuffer when rendering with
  43546. * the WebXR device API.
  43547. *
  43548. * @private
  43549. * @type {WebGLFramebuffer}
  43550. * @default null
  43551. */
  43552. this._xrFramebuffer = null;
  43553. }
  43554. /**
  43555. * Initializes the backend so it is ready for usage.
  43556. *
  43557. * @param {Renderer} renderer - The renderer.
  43558. */
  43559. init( renderer ) {
  43560. super.init( renderer );
  43561. //
  43562. const parameters = this.parameters;
  43563. const contextAttributes = {
  43564. antialias: renderer.samples > 0,
  43565. alpha: true, // always true for performance reasons
  43566. depth: renderer.depth,
  43567. stencil: renderer.stencil
  43568. };
  43569. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  43570. function onContextLost( event ) {
  43571. event.preventDefault();
  43572. const contextLossInfo = {
  43573. api: 'WebGL',
  43574. message: event.statusMessage || 'Unknown reason',
  43575. reason: null,
  43576. originalEvent: event
  43577. };
  43578. renderer.onDeviceLost( contextLossInfo );
  43579. }
  43580. this._onContextLost = onContextLost;
  43581. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  43582. this.gl = glContext;
  43583. this.extensions = new WebGLExtensions( this );
  43584. this.capabilities = new WebGLCapabilities( this );
  43585. this.attributeUtils = new WebGLAttributeUtils( this );
  43586. this.textureUtils = new WebGLTextureUtils( this );
  43587. this.bufferRenderer = new WebGLBufferRenderer( this );
  43588. this.state = new WebGLState( this );
  43589. this.utils = new WebGLUtils( this );
  43590. this.extensions.get( 'EXT_color_buffer_float' );
  43591. this.extensions.get( 'WEBGL_clip_cull_distance' );
  43592. this.extensions.get( 'OES_texture_float_linear' );
  43593. this.extensions.get( 'EXT_color_buffer_half_float' );
  43594. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  43595. this.extensions.get( 'WEBGL_render_shared_exponent' );
  43596. this.extensions.get( 'WEBGL_multi_draw' );
  43597. this.extensions.get( 'OVR_multiview2' );
  43598. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  43599. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  43600. }
  43601. /**
  43602. * The coordinate system of the backend.
  43603. *
  43604. * @type {number}
  43605. * @readonly
  43606. */
  43607. get coordinateSystem() {
  43608. return WebGLCoordinateSystem;
  43609. }
  43610. /**
  43611. * This method performs a readback operation by moving buffer data from
  43612. * a storage buffer attribute from the GPU to the CPU.
  43613. *
  43614. * @async
  43615. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  43616. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  43617. */
  43618. async getArrayBufferAsync( attribute ) {
  43619. return await this.attributeUtils.getArrayBufferAsync( attribute );
  43620. }
  43621. /**
  43622. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  43623. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  43624. *
  43625. * @async
  43626. * @return {Promise} A Promise that resolves when synchronization has been finished.
  43627. */
  43628. async waitForGPU() {
  43629. await this.utils._clientWaitAsync();
  43630. }
  43631. /**
  43632. * Ensures the backend is XR compatible.
  43633. *
  43634. * @async
  43635. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  43636. */
  43637. async makeXRCompatible() {
  43638. const attributes = this.gl.getContextAttributes();
  43639. if ( attributes.xrCompatible !== true ) {
  43640. await this.gl.makeXRCompatible();
  43641. }
  43642. }
  43643. /**
  43644. * Sets the XR rendering destination.
  43645. *
  43646. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  43647. */
  43648. setXRTarget( xrFramebuffer ) {
  43649. this._xrFramebuffer = xrFramebuffer;
  43650. }
  43651. /**
  43652. * Configures the given XR render target with external textures.
  43653. *
  43654. * This method is only relevant when using the WebXR Layers API.
  43655. *
  43656. * @param {XRRenderTarget} renderTarget - The XR render target.
  43657. * @param {WebGLTexture} colorTexture - A native color texture.
  43658. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  43659. */
  43660. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  43661. const gl = this.gl;
  43662. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  43663. if ( depthTexture !== null ) {
  43664. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  43665. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  43666. // The multisample_render_to_texture extension doesn't work properly if there
  43667. // are midframe flushes and an external depth texture.
  43668. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget.autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  43669. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  43670. }
  43671. renderTarget.autoAllocateDepthBuffer = false;
  43672. }
  43673. }
  43674. /**
  43675. * Inits a time stamp query for the given render context.
  43676. *
  43677. * @param {RenderContext} renderContext - The render context.
  43678. */
  43679. initTimestampQuery( renderContext ) {
  43680. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  43681. const type = renderContext.isComputeNode ? 'compute' : 'render';
  43682. if ( ! this.timestampQueryPool[ type ] ) {
  43683. // TODO: Variable maxQueries?
  43684. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  43685. }
  43686. const timestampQueryPool = this.timestampQueryPool[ type ];
  43687. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  43688. if ( baseOffset !== null ) {
  43689. timestampQueryPool.beginQuery( renderContext );
  43690. }
  43691. }
  43692. // timestamp utils
  43693. /**
  43694. * Prepares the timestamp buffer.
  43695. *
  43696. * @param {RenderContext} renderContext - The render context.
  43697. */
  43698. prepareTimestampBuffer( renderContext ) {
  43699. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  43700. const type = renderContext.isComputeNode ? 'compute' : 'render';
  43701. const timestampQueryPool = this.timestampQueryPool[ type ];
  43702. timestampQueryPool.endQuery( renderContext );
  43703. }
  43704. /**
  43705. * Returns the backend's rendering context.
  43706. *
  43707. * @return {WebGL2RenderingContext} The rendering context.
  43708. */
  43709. getContext() {
  43710. return this.gl;
  43711. }
  43712. /**
  43713. * This method is executed at the beginning of a render call and prepares
  43714. * the WebGL state for upcoming render calls
  43715. *
  43716. * @param {RenderContext} renderContext - The render context.
  43717. */
  43718. beginRender( renderContext ) {
  43719. const { state, gl } = this;
  43720. const renderContextData = this.get( renderContext );
  43721. //
  43722. if ( renderContext.viewport ) {
  43723. this.updateViewport( renderContext );
  43724. } else {
  43725. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  43726. }
  43727. if ( renderContext.scissor ) {
  43728. const { x, y, width, height } = renderContext.scissorValue;
  43729. state.scissor( x, renderContext.height - height - y, width, height );
  43730. }
  43731. //
  43732. this.initTimestampQuery( renderContext );
  43733. renderContextData.previousContext = this._currentContext;
  43734. this._currentContext = renderContext;
  43735. this._setFramebuffer( renderContext );
  43736. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  43737. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43738. if ( occlusionQueryCount > 0 ) {
  43739. // Get a reference to the array of objects with queries. The renderContextData property
  43740. // can be changed by another render pass before the async reading of all previous queries complete
  43741. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  43742. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  43743. renderContextData.lastOcclusionObject = null;
  43744. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  43745. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  43746. renderContextData.occlusionQueryIndex = 0;
  43747. }
  43748. }
  43749. /**
  43750. * This method is executed at the end of a render call and finalizes work
  43751. * after draw calls.
  43752. *
  43753. * @param {RenderContext} renderContext - The render context.
  43754. */
  43755. finishRender( renderContext ) {
  43756. const { gl, state } = this;
  43757. const renderContextData = this.get( renderContext );
  43758. const previousContext = renderContextData.previousContext;
  43759. state.resetVertexState();
  43760. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43761. if ( occlusionQueryCount > 0 ) {
  43762. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  43763. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  43764. }
  43765. this.resolveOccludedAsync( renderContext );
  43766. }
  43767. const textures = renderContext.textures;
  43768. if ( textures !== null ) {
  43769. for ( let i = 0; i < textures.length; i ++ ) {
  43770. const texture = textures[ i ];
  43771. if ( texture.generateMipmaps ) {
  43772. this.generateMipmaps( texture );
  43773. }
  43774. }
  43775. }
  43776. this._currentContext = previousContext;
  43777. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  43778. const renderTargetContextData = this.get( renderContext.renderTarget );
  43779. const { resolveDepthBuffer, samples } = renderContext.renderTarget;
  43780. if ( samples > 0 && this._useMultisampledExtension( renderContext.renderTarget ) === false ) {
  43781. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  43782. const mask = gl.COLOR_BUFFER_BIT;
  43783. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  43784. const textures = renderContext.textures;
  43785. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  43786. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43787. for ( let i = 0; i < textures.length; i ++ ) {
  43788. // TODO Add support for MRT
  43789. if ( renderContext.scissor ) {
  43790. const { x, y, width, height } = renderContext.scissorValue;
  43791. const viewY = renderContext.height - height - y;
  43792. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  43793. if ( this._supportsInvalidateFramebuffer === true ) {
  43794. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  43795. }
  43796. } else {
  43797. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  43798. if ( this._supportsInvalidateFramebuffer === true ) {
  43799. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  43800. }
  43801. }
  43802. }
  43803. } else if ( resolveDepthBuffer === false ) {
  43804. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  43805. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43806. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  43807. }
  43808. }
  43809. if ( previousContext !== null ) {
  43810. this._setFramebuffer( previousContext );
  43811. if ( previousContext.viewport ) {
  43812. this.updateViewport( previousContext );
  43813. } else {
  43814. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  43815. }
  43816. }
  43817. this.prepareTimestampBuffer( renderContext );
  43818. }
  43819. /**
  43820. * This method processes the result of occlusion queries and writes it
  43821. * into render context data.
  43822. *
  43823. * @async
  43824. * @param {RenderContext} renderContext - The render context.
  43825. */
  43826. resolveOccludedAsync( renderContext ) {
  43827. const renderContextData = this.get( renderContext );
  43828. // handle occlusion query results
  43829. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  43830. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  43831. const occluded = new WeakSet();
  43832. const { gl } = this;
  43833. renderContextData.currentOcclusionQueryObjects = null;
  43834. renderContextData.currentOcclusionQueries = null;
  43835. const check = () => {
  43836. let completed = 0;
  43837. // check all queries and requeue as appropriate
  43838. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  43839. const query = currentOcclusionQueries[ i ];
  43840. if ( query === null ) continue;
  43841. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  43842. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  43843. currentOcclusionQueries[ i ] = null;
  43844. gl.deleteQuery( query );
  43845. completed ++;
  43846. }
  43847. }
  43848. if ( completed < currentOcclusionQueries.length ) {
  43849. requestAnimationFrame( check );
  43850. } else {
  43851. renderContextData.occluded = occluded;
  43852. }
  43853. };
  43854. check();
  43855. }
  43856. }
  43857. /**
  43858. * Returns `true` if the given 3D object is fully occluded by other
  43859. * 3D objects in the scene.
  43860. *
  43861. * @param {RenderContext} renderContext - The render context.
  43862. * @param {Object3D} object - The 3D object to test.
  43863. * @return {boolean} Whether the 3D object is fully occluded or not.
  43864. */
  43865. isOccluded( renderContext, object ) {
  43866. const renderContextData = this.get( renderContext );
  43867. return renderContextData.occluded && renderContextData.occluded.has( object );
  43868. }
  43869. /**
  43870. * Updates the viewport with the values from the given render context.
  43871. *
  43872. * @param {RenderContext} renderContext - The render context.
  43873. */
  43874. updateViewport( renderContext ) {
  43875. const { state } = this;
  43876. const { x, y, width, height } = renderContext.viewportValue;
  43877. state.viewport( x, renderContext.height - height - y, width, height );
  43878. }
  43879. /**
  43880. * Defines the scissor test.
  43881. *
  43882. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  43883. */
  43884. setScissorTest( boolean ) {
  43885. const state = this.state;
  43886. state.setScissorTest( boolean );
  43887. }
  43888. /**
  43889. * Returns the clear color and alpha into a single
  43890. * color object.
  43891. *
  43892. * @return {Color4} The clear color.
  43893. */
  43894. getClearColor() {
  43895. const clearColor = super.getClearColor();
  43896. // Since the canvas is always created with alpha: true,
  43897. // WebGL must always premultiply the clear color.
  43898. clearColor.r *= clearColor.a;
  43899. clearColor.g *= clearColor.a;
  43900. clearColor.b *= clearColor.a;
  43901. return clearColor;
  43902. }
  43903. /**
  43904. * Performs a clear operation.
  43905. *
  43906. * @param {boolean} color - Whether the color buffer should be cleared or not.
  43907. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  43908. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  43909. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  43910. * @param {boolean} [setFrameBuffer=true] - TODO.
  43911. */
  43912. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  43913. const { gl, renderer } = this;
  43914. if ( descriptor === null ) {
  43915. const clearColor = this.getClearColor();
  43916. descriptor = {
  43917. textures: null,
  43918. clearColorValue: clearColor
  43919. };
  43920. }
  43921. //
  43922. let clear = 0;
  43923. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  43924. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  43925. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  43926. if ( clear !== 0 ) {
  43927. let clearColor;
  43928. if ( descriptor.clearColorValue ) {
  43929. clearColor = descriptor.clearColorValue;
  43930. } else {
  43931. clearColor = this.getClearColor();
  43932. }
  43933. const clearDepth = renderer.getClearDepth();
  43934. const clearStencil = renderer.getClearStencil();
  43935. if ( depth ) this.state.setDepthMask( true );
  43936. if ( descriptor.textures === null ) {
  43937. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  43938. gl.clear( clear );
  43939. } else {
  43940. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  43941. if ( color ) {
  43942. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  43943. if ( i === 0 ) {
  43944. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  43945. } else {
  43946. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  43947. }
  43948. }
  43949. }
  43950. if ( depth && stencil ) {
  43951. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  43952. } else if ( depth ) {
  43953. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  43954. } else if ( stencil ) {
  43955. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  43956. }
  43957. }
  43958. }
  43959. }
  43960. /**
  43961. * This method is executed at the beginning of a compute call and
  43962. * prepares the state for upcoming compute tasks.
  43963. *
  43964. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43965. */
  43966. beginCompute( computeGroup ) {
  43967. const { state, gl } = this;
  43968. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  43969. this.initTimestampQuery( computeGroup );
  43970. }
  43971. /**
  43972. * Executes a compute command for the given compute node.
  43973. *
  43974. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  43975. * @param {Node} computeNode - The compute node.
  43976. * @param {Array<BindGroup>} bindings - The bindings.
  43977. * @param {ComputePipeline} pipeline - The compute pipeline.
  43978. */
  43979. compute( computeGroup, computeNode, bindings, pipeline ) {
  43980. const { state, gl } = this;
  43981. if ( this.discard === false ) {
  43982. // required here to handle async behaviour of render.compute()
  43983. gl.enable( gl.RASTERIZER_DISCARD );
  43984. this.discard = true;
  43985. }
  43986. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  43987. const vaoKey = this._getVaoKey( attributes );
  43988. const vaoGPU = this.vaoCache[ vaoKey ];
  43989. if ( vaoGPU === undefined ) {
  43990. this._createVao( attributes );
  43991. } else {
  43992. state.setVertexState( vaoGPU );
  43993. }
  43994. state.useProgram( programGPU );
  43995. this._bindUniforms( bindings );
  43996. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  43997. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  43998. gl.beginTransformFeedback( gl.POINTS );
  43999. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  44000. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  44001. } else {
  44002. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  44003. }
  44004. gl.endTransformFeedback();
  44005. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  44006. // switch active buffers
  44007. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  44008. const dualAttributeData = transformBuffers[ i ];
  44009. if ( dualAttributeData.pbo ) {
  44010. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  44011. }
  44012. dualAttributeData.switchBuffers();
  44013. }
  44014. }
  44015. /**
  44016. * This method is executed at the end of a compute call and
  44017. * finalizes work after compute tasks.
  44018. *
  44019. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  44020. */
  44021. finishCompute( computeGroup ) {
  44022. const gl = this.gl;
  44023. this.discard = false;
  44024. gl.disable( gl.RASTERIZER_DISCARD );
  44025. this.prepareTimestampBuffer( computeGroup );
  44026. if ( this._currentContext ) {
  44027. this._setFramebuffer( this._currentContext );
  44028. }
  44029. }
  44030. /**
  44031. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  44032. *
  44033. * @param {RenderContext} renderContext - The render context.
  44034. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  44035. *
  44036. * @private
  44037. */
  44038. _isRenderCameraDepthArray( renderContext ) {
  44039. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  44040. }
  44041. /**
  44042. * Executes a draw command for the given render object.
  44043. *
  44044. * @param {RenderObject} renderObject - The render object to draw.
  44045. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  44046. */
  44047. draw( renderObject/*, info*/ ) {
  44048. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  44049. const { programGPU } = this.get( pipeline );
  44050. const { gl, state } = this;
  44051. const contextData = this.get( context );
  44052. const drawParams = renderObject.getDrawParameters();
  44053. if ( drawParams === null ) return;
  44054. //
  44055. this._bindUniforms( renderObject.getBindings() );
  44056. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  44057. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  44058. state.useProgram( programGPU );
  44059. // vertex state
  44060. const renderObjectData = this.get( renderObject );
  44061. let vaoGPU = renderObjectData.staticVao;
  44062. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  44063. const vaoKey = this._getVaoKey( renderObject.getAttributes() );
  44064. vaoGPU = this.vaoCache[ vaoKey ];
  44065. if ( vaoGPU === undefined ) {
  44066. let staticVao;
  44067. ( { vaoGPU, staticVao } = this._createVao( renderObject.getAttributes() ) );
  44068. if ( staticVao ) {
  44069. renderObjectData.staticVao = vaoGPU;
  44070. renderObjectData.geometryId = renderObject.geometry.id;
  44071. }
  44072. }
  44073. }
  44074. const index = renderObject.getIndex();
  44075. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  44076. state.setVertexState( vaoGPU, indexGPU );
  44077. //
  44078. const lastObject = contextData.lastOcclusionObject;
  44079. if ( lastObject !== object && lastObject !== undefined ) {
  44080. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  44081. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  44082. contextData.occlusionQueryIndex ++;
  44083. }
  44084. if ( object.occlusionTest === true ) {
  44085. const query = gl.createQuery();
  44086. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  44087. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  44088. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  44089. }
  44090. contextData.lastOcclusionObject = object;
  44091. }
  44092. //
  44093. const renderer = this.bufferRenderer;
  44094. if ( object.isPoints ) renderer.mode = gl.POINTS;
  44095. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  44096. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  44097. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  44098. else {
  44099. if ( material.wireframe === true ) {
  44100. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  44101. renderer.mode = gl.LINES;
  44102. } else {
  44103. renderer.mode = gl.TRIANGLES;
  44104. }
  44105. }
  44106. //
  44107. const { vertexCount, instanceCount } = drawParams;
  44108. let { firstVertex } = drawParams;
  44109. renderer.object = object;
  44110. if ( index !== null ) {
  44111. firstVertex *= index.array.BYTES_PER_ELEMENT;
  44112. const indexData = this.get( index );
  44113. renderer.index = index.count;
  44114. renderer.type = indexData.type;
  44115. } else {
  44116. renderer.index = 0;
  44117. }
  44118. const draw = () => {
  44119. if ( object.isBatchedMesh ) {
  44120. if ( object._multiDrawInstances !== null ) {
  44121. // @deprecated, r174
  44122. warnOnce( 'THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  44123. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  44124. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  44125. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  44126. } else {
  44127. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  44128. }
  44129. } else if ( instanceCount > 1 ) {
  44130. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  44131. } else {
  44132. renderer.render( firstVertex, vertexCount );
  44133. }
  44134. };
  44135. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  44136. const cameraData = this.get( renderObject.camera );
  44137. const cameras = renderObject.camera.cameras;
  44138. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  44139. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  44140. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  44141. const indexesGPU = [];
  44142. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  44143. const bufferGPU = gl.createBuffer();
  44144. data[ 0 ] = i;
  44145. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44146. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  44147. indexesGPU.push( bufferGPU );
  44148. }
  44149. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  44150. }
  44151. const cameraIndexData = this.get( cameraIndex );
  44152. const pixelRatio = this.renderer.getPixelRatio();
  44153. const renderTarget = this._currentContext.renderTarget;
  44154. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  44155. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  44156. if ( isRenderCameraDepthArray ) {
  44157. // Clear the depth texture
  44158. const textureData = this.get( renderTarget.depthTexture );
  44159. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  44160. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  44161. const { stencilBuffer } = renderTarget;
  44162. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  44163. this.renderer._activeCubeFace = i;
  44164. this._currentContext.activeCubeFace = i;
  44165. this._setFramebuffer( this._currentContext );
  44166. this.clear( false, true, stencilBuffer, this._currentContext, false );
  44167. }
  44168. this.renderer._activeCubeFace = prevActiveCubeFace;
  44169. this._currentContext.activeCubeFace = prevActiveCubeFace;
  44170. }
  44171. }
  44172. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  44173. const subCamera = cameras[ i ];
  44174. if ( object.layers.test( subCamera.layers ) ) {
  44175. if ( isRenderCameraDepthArray ) {
  44176. // Update the active layer
  44177. this.renderer._activeCubeFace = i;
  44178. this._currentContext.activeCubeFace = i;
  44179. this._setFramebuffer( this._currentContext );
  44180. }
  44181. const vp = subCamera.viewport;
  44182. if ( vp !== undefined ) {
  44183. const x = vp.x * pixelRatio;
  44184. const y = vp.y * pixelRatio;
  44185. const width = vp.width * pixelRatio;
  44186. const height = vp.height * pixelRatio;
  44187. state.viewport(
  44188. Math.floor( x ),
  44189. Math.floor( renderObject.context.height - height - y ),
  44190. Math.floor( width ),
  44191. Math.floor( height )
  44192. );
  44193. }
  44194. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  44195. draw();
  44196. }
  44197. this._currentContext.activeCubeFace = prevActiveCubeFace;
  44198. this.renderer._activeCubeFace = prevActiveCubeFace;
  44199. }
  44200. } else {
  44201. draw();
  44202. }
  44203. }
  44204. /**
  44205. * Explain why always null is returned.
  44206. *
  44207. * @param {RenderObject} renderObject - The render object.
  44208. * @return {boolean} Whether the render pipeline requires an update or not.
  44209. */
  44210. needsRenderUpdate( /*renderObject*/ ) {
  44211. return false;
  44212. }
  44213. /**
  44214. * Explain why no cache key is computed.
  44215. *
  44216. * @param {RenderObject} renderObject - The render object.
  44217. * @return {string} The cache key.
  44218. */
  44219. getRenderCacheKey( /*renderObject*/ ) {
  44220. return '';
  44221. }
  44222. // textures
  44223. /**
  44224. * Creates a default texture for the given texture that can be used
  44225. * as a placeholder until the actual texture is ready for usage.
  44226. *
  44227. * @param {Texture} texture - The texture to create a default texture for.
  44228. */
  44229. createDefaultTexture( texture ) {
  44230. this.textureUtils.createDefaultTexture( texture );
  44231. }
  44232. /**
  44233. * Defines a texture on the GPU for the given texture object.
  44234. *
  44235. * @param {Texture} texture - The texture.
  44236. * @param {Object} [options={}] - Optional configuration parameter.
  44237. */
  44238. createTexture( texture, options ) {
  44239. this.textureUtils.createTexture( texture, options );
  44240. }
  44241. /**
  44242. * Uploads the updated texture data to the GPU.
  44243. *
  44244. * @param {Texture} texture - The texture.
  44245. * @param {Object} [options={}] - Optional configuration parameter.
  44246. */
  44247. updateTexture( texture, options ) {
  44248. this.textureUtils.updateTexture( texture, options );
  44249. }
  44250. /**
  44251. * Generates mipmaps for the given texture.
  44252. *
  44253. * @param {Texture} texture - The texture.
  44254. */
  44255. generateMipmaps( texture ) {
  44256. this.textureUtils.generateMipmaps( texture );
  44257. }
  44258. /**
  44259. * Destroys the GPU data for the given texture object.
  44260. *
  44261. * @param {Texture} texture - The texture.
  44262. */
  44263. destroyTexture( texture ) {
  44264. this.textureUtils.destroyTexture( texture );
  44265. }
  44266. /**
  44267. * Returns texture data as a typed array.
  44268. *
  44269. * @async
  44270. * @param {Texture} texture - The texture to copy.
  44271. * @param {number} x - The x coordinate of the copy origin.
  44272. * @param {number} y - The y coordinate of the copy origin.
  44273. * @param {number} width - The width of the copy.
  44274. * @param {number} height - The height of the copy.
  44275. * @param {number} faceIndex - The face index.
  44276. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  44277. */
  44278. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44279. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  44280. }
  44281. /**
  44282. * This method does nothing since WebGL 2 has no concept of samplers.
  44283. *
  44284. * @param {Texture} texture - The texture to create the sampler for.
  44285. */
  44286. createSampler( /*texture*/ ) {
  44287. //console.warn( 'Abstract class.' );
  44288. }
  44289. /**
  44290. * This method does nothing since WebGL 2 has no concept of samplers.
  44291. *
  44292. * @param {Texture} texture - The texture to destroy the sampler for.
  44293. */
  44294. destroySampler( /*texture*/ ) {}
  44295. // node builder
  44296. /**
  44297. * Returns a node builder for the given render object.
  44298. *
  44299. * @param {RenderObject} object - The render object.
  44300. * @param {Renderer} renderer - The renderer.
  44301. * @return {GLSLNodeBuilder} The node builder.
  44302. */
  44303. createNodeBuilder( object, renderer ) {
  44304. return new GLSLNodeBuilder( object, renderer );
  44305. }
  44306. // program
  44307. /**
  44308. * Creates a shader program from the given programmable stage.
  44309. *
  44310. * @param {ProgrammableStage} program - The programmable stage.
  44311. */
  44312. createProgram( program ) {
  44313. const gl = this.gl;
  44314. const { stage, code } = program;
  44315. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  44316. gl.shaderSource( shader, code );
  44317. gl.compileShader( shader );
  44318. this.set( program, {
  44319. shaderGPU: shader
  44320. } );
  44321. }
  44322. /**
  44323. * Destroys the shader program of the given programmable stage.
  44324. *
  44325. * @param {ProgrammableStage} program - The programmable stage.
  44326. */
  44327. destroyProgram( program ) {
  44328. this.delete( program );
  44329. }
  44330. /**
  44331. * Creates a render pipeline for the given render object.
  44332. *
  44333. * @param {RenderObject} renderObject - The render object.
  44334. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  44335. */
  44336. createRenderPipeline( renderObject, promises ) {
  44337. const gl = this.gl;
  44338. const pipeline = renderObject.pipeline;
  44339. // Program
  44340. const { fragmentProgram, vertexProgram } = pipeline;
  44341. const programGPU = gl.createProgram();
  44342. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  44343. const vertexShader = this.get( vertexProgram ).shaderGPU;
  44344. gl.attachShader( programGPU, fragmentShader );
  44345. gl.attachShader( programGPU, vertexShader );
  44346. gl.linkProgram( programGPU );
  44347. this.set( pipeline, {
  44348. programGPU,
  44349. fragmentShader,
  44350. vertexShader
  44351. } );
  44352. if ( promises !== null && this.parallel ) {
  44353. const p = new Promise( ( resolve /*, reject*/ ) => {
  44354. const parallel = this.parallel;
  44355. const checkStatus = () => {
  44356. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  44357. this._completeCompile( renderObject, pipeline );
  44358. resolve();
  44359. } else {
  44360. requestAnimationFrame( checkStatus );
  44361. }
  44362. };
  44363. checkStatus();
  44364. } );
  44365. promises.push( p );
  44366. return;
  44367. }
  44368. this._completeCompile( renderObject, pipeline );
  44369. }
  44370. /**
  44371. * Formats the source code of error messages.
  44372. *
  44373. * @private
  44374. * @param {string} string - The code.
  44375. * @param {number} errorLine - The error line.
  44376. * @return {string} The formatted code.
  44377. */
  44378. _handleSource( string, errorLine ) {
  44379. const lines = string.split( '\n' );
  44380. const lines2 = [];
  44381. const from = Math.max( errorLine - 6, 0 );
  44382. const to = Math.min( errorLine + 6, lines.length );
  44383. for ( let i = from; i < to; i ++ ) {
  44384. const line = i + 1;
  44385. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  44386. }
  44387. return lines2.join( '\n' );
  44388. }
  44389. /**
  44390. * Gets the shader compilation errors from the info log.
  44391. *
  44392. * @private
  44393. * @param {WebGL2RenderingContext} gl - The rendering context.
  44394. * @param {WebGLShader} shader - The WebGL shader object.
  44395. * @param {string} type - The shader type.
  44396. * @return {string} The shader errors.
  44397. */
  44398. _getShaderErrors( gl, shader, type ) {
  44399. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  44400. const errors = gl.getShaderInfoLog( shader ).trim();
  44401. if ( status && errors === '' ) return '';
  44402. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  44403. if ( errorMatches ) {
  44404. const errorLine = parseInt( errorMatches[ 1 ] );
  44405. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  44406. } else {
  44407. return errors;
  44408. }
  44409. }
  44410. /**
  44411. * Logs shader compilation errors.
  44412. *
  44413. * @private
  44414. * @param {WebGLProgram} programGPU - The WebGL program.
  44415. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  44416. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  44417. */
  44418. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  44419. if ( this.renderer.debug.checkShaderErrors ) {
  44420. const gl = this.gl;
  44421. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  44422. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44423. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  44424. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  44425. } else {
  44426. // default error reporting
  44427. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  44428. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  44429. console.error(
  44430. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  44431. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  44432. 'Program Info Log: ' + programLog + '\n' +
  44433. vertexErrors + '\n' +
  44434. fragmentErrors
  44435. );
  44436. }
  44437. } else if ( programLog !== '' ) {
  44438. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  44439. }
  44440. }
  44441. }
  44442. /**
  44443. * Completes the shader program setup for the given render object.
  44444. *
  44445. * @private
  44446. * @param {RenderObject} renderObject - The render object.
  44447. * @param {RenderPipeline} pipeline - The render pipeline.
  44448. */
  44449. _completeCompile( renderObject, pipeline ) {
  44450. const { state, gl } = this;
  44451. const pipelineData = this.get( pipeline );
  44452. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  44453. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44454. this._logProgramError( programGPU, fragmentShader, vertexShader );
  44455. }
  44456. state.useProgram( programGPU );
  44457. // Bindings
  44458. const bindings = renderObject.getBindings();
  44459. this._setupBindings( bindings, programGPU );
  44460. //
  44461. this.set( pipeline, {
  44462. programGPU
  44463. } );
  44464. }
  44465. /**
  44466. * Creates a compute pipeline for the given compute node.
  44467. *
  44468. * @param {ComputePipeline} computePipeline - The compute pipeline.
  44469. * @param {Array<BindGroup>} bindings - The bindings.
  44470. */
  44471. createComputePipeline( computePipeline, bindings ) {
  44472. const { state, gl } = this;
  44473. // Program
  44474. const fragmentProgram = {
  44475. stage: 'fragment',
  44476. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  44477. };
  44478. this.createProgram( fragmentProgram );
  44479. const { computeProgram } = computePipeline;
  44480. const programGPU = gl.createProgram();
  44481. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  44482. const vertexShader = this.get( computeProgram ).shaderGPU;
  44483. const transforms = computeProgram.transforms;
  44484. const transformVaryingNames = [];
  44485. const transformAttributeNodes = [];
  44486. for ( let i = 0; i < transforms.length; i ++ ) {
  44487. const transform = transforms[ i ];
  44488. transformVaryingNames.push( transform.varyingName );
  44489. transformAttributeNodes.push( transform.attributeNode );
  44490. }
  44491. gl.attachShader( programGPU, fragmentShader );
  44492. gl.attachShader( programGPU, vertexShader );
  44493. gl.transformFeedbackVaryings(
  44494. programGPU,
  44495. transformVaryingNames,
  44496. gl.SEPARATE_ATTRIBS
  44497. );
  44498. gl.linkProgram( programGPU );
  44499. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44500. this._logProgramError( programGPU, fragmentShader, vertexShader );
  44501. }
  44502. state.useProgram( programGPU );
  44503. // Bindings
  44504. this._setupBindings( bindings, programGPU );
  44505. const attributeNodes = computeProgram.attributes;
  44506. const attributes = [];
  44507. const transformBuffers = [];
  44508. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  44509. const attribute = attributeNodes[ i ].node.attribute;
  44510. attributes.push( attribute );
  44511. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44512. }
  44513. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  44514. const attribute = transformAttributeNodes[ i ].attribute;
  44515. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44516. const attributeData = this.get( attribute );
  44517. transformBuffers.push( attributeData );
  44518. }
  44519. //
  44520. this.set( computePipeline, {
  44521. programGPU,
  44522. transformBuffers,
  44523. attributes
  44524. } );
  44525. }
  44526. /**
  44527. * Creates bindings from the given bind group definition.
  44528. *
  44529. * @param {BindGroup} bindGroup - The bind group.
  44530. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44531. * @param {number} cacheIndex - The cache index.
  44532. * @param {number} version - The version.
  44533. */
  44534. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  44535. if ( this._knownBindings.has( bindings ) === false ) {
  44536. this._knownBindings.add( bindings );
  44537. let uniformBuffers = 0;
  44538. let textures = 0;
  44539. for ( const bindGroup of bindings ) {
  44540. this.set( bindGroup, {
  44541. textures: textures,
  44542. uniformBuffers: uniformBuffers
  44543. } );
  44544. for ( const binding of bindGroup.bindings ) {
  44545. if ( binding.isUniformBuffer ) uniformBuffers ++;
  44546. if ( binding.isSampledTexture ) textures ++;
  44547. }
  44548. }
  44549. }
  44550. this.updateBindings( bindGroup, bindings );
  44551. }
  44552. /**
  44553. * Updates the given bind group definition.
  44554. *
  44555. * @param {BindGroup} bindGroup - The bind group.
  44556. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44557. * @param {number} cacheIndex - The cache index.
  44558. * @param {number} version - The version.
  44559. */
  44560. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  44561. const { gl } = this;
  44562. const bindGroupData = this.get( bindGroup );
  44563. let i = bindGroupData.uniformBuffers;
  44564. let t = bindGroupData.textures;
  44565. for ( const binding of bindGroup.bindings ) {
  44566. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44567. const data = binding.buffer;
  44568. const bufferGPU = gl.createBuffer();
  44569. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44570. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  44571. this.set( binding, {
  44572. index: i ++,
  44573. bufferGPU
  44574. } );
  44575. } else if ( binding.isSampledTexture ) {
  44576. const { textureGPU, glTextureType } = this.get( binding.texture );
  44577. this.set( binding, {
  44578. index: t ++,
  44579. textureGPU,
  44580. glTextureType
  44581. } );
  44582. }
  44583. }
  44584. }
  44585. /**
  44586. * Updates a buffer binding.
  44587. *
  44588. * @param {Buffer} binding - The buffer binding to update.
  44589. */
  44590. updateBinding( binding ) {
  44591. const gl = this.gl;
  44592. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44593. const bindingData = this.get( binding );
  44594. const bufferGPU = bindingData.bufferGPU;
  44595. const data = binding.buffer;
  44596. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44597. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  44598. }
  44599. }
  44600. // attributes
  44601. /**
  44602. * Creates the GPU buffer of an indexed shader attribute.
  44603. *
  44604. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  44605. */
  44606. createIndexAttribute( attribute ) {
  44607. const gl = this.gl;
  44608. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  44609. }
  44610. /**
  44611. * Creates the GPU buffer of a shader attribute.
  44612. *
  44613. * @param {BufferAttribute} attribute - The buffer attribute.
  44614. */
  44615. createAttribute( attribute ) {
  44616. if ( this.has( attribute ) ) return;
  44617. const gl = this.gl;
  44618. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44619. }
  44620. /**
  44621. * Creates the GPU buffer of a storage attribute.
  44622. *
  44623. * @param {BufferAttribute} attribute - The buffer attribute.
  44624. */
  44625. createStorageAttribute( attribute ) {
  44626. if ( this.has( attribute ) ) return;
  44627. const gl = this.gl;
  44628. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44629. }
  44630. /**
  44631. * Updates the GPU buffer of a shader attribute.
  44632. *
  44633. * @param {BufferAttribute} attribute - The buffer attribute to update.
  44634. */
  44635. updateAttribute( attribute ) {
  44636. this.attributeUtils.updateAttribute( attribute );
  44637. }
  44638. /**
  44639. * Destroys the GPU buffer of a shader attribute.
  44640. *
  44641. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  44642. */
  44643. destroyAttribute( attribute ) {
  44644. this.attributeUtils.destroyAttribute( attribute );
  44645. }
  44646. /**
  44647. * Checks if the given feature is supported by the backend.
  44648. *
  44649. * @param {string} name - The feature's name.
  44650. * @return {boolean} Whether the feature is supported or not.
  44651. */
  44652. hasFeature( name ) {
  44653. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  44654. const extensions = this.extensions;
  44655. for ( let i = 0; i < keysMatching.length; i ++ ) {
  44656. if ( extensions.has( keysMatching[ i ] ) ) return true;
  44657. }
  44658. return false;
  44659. }
  44660. /**
  44661. * Returns the maximum anisotropy texture filtering value.
  44662. *
  44663. * @return {number} The maximum anisotropy texture filtering value.
  44664. */
  44665. getMaxAnisotropy() {
  44666. return this.capabilities.getMaxAnisotropy();
  44667. }
  44668. /**
  44669. * Copies data of the given source texture to the given destination texture.
  44670. *
  44671. * @param {Texture} srcTexture - The source texture.
  44672. * @param {Texture} dstTexture - The destination texture.
  44673. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  44674. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  44675. * @param {number} [srcLevel=0] - The source mip level to copy from.
  44676. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  44677. */
  44678. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  44679. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  44680. }
  44681. /**
  44682. * Copies the current bound framebuffer to the given texture.
  44683. *
  44684. * @param {Texture} texture - The destination texture.
  44685. * @param {RenderContext} renderContext - The render context.
  44686. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  44687. */
  44688. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  44689. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  44690. }
  44691. /**
  44692. * Configures the active framebuffer from the given render context.
  44693. *
  44694. * @private
  44695. * @param {RenderContext} descriptor - The render context.
  44696. */
  44697. _setFramebuffer( descriptor ) {
  44698. const { gl, state } = this;
  44699. let currentFrameBuffer = null;
  44700. if ( descriptor.textures !== null ) {
  44701. const renderTarget = descriptor.renderTarget;
  44702. const renderTargetContextData = this.get( renderTarget );
  44703. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  44704. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  44705. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  44706. const isRenderTargetArray = renderTarget.depth > 1;
  44707. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  44708. const hasExternalTextures = ( isXRRenderTarget === true && renderTarget.hasExternalTextures === true );
  44709. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  44710. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  44711. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  44712. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  44713. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  44714. const cacheKey = getCacheKey( descriptor );
  44715. let fb;
  44716. if ( isCube ) {
  44717. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  44718. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  44719. } else if ( isXRRenderTarget && hasExternalTextures === false ) {
  44720. fb = this._xrFramebuffer;
  44721. } else {
  44722. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  44723. fb = renderTargetContextData.framebuffers[ cacheKey ];
  44724. }
  44725. if ( fb === undefined ) {
  44726. fb = gl.createFramebuffer();
  44727. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44728. const textures = descriptor.textures;
  44729. const depthInvalidationArray = [];
  44730. if ( isCube ) {
  44731. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  44732. const { textureGPU } = this.get( textures[ 0 ] );
  44733. const cubeFace = this.renderer._activeCubeFace;
  44734. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  44735. } else {
  44736. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  44737. for ( let i = 0; i < textures.length; i ++ ) {
  44738. const texture = textures[ i ];
  44739. const textureData = this.get( texture );
  44740. textureData.renderTarget = descriptor.renderTarget;
  44741. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  44742. const attachment = gl.COLOR_ATTACHMENT0 + i;
  44743. if ( renderTarget.multiview ) {
  44744. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  44745. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  44746. const layer = this.renderer._activeCubeFace;
  44747. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  44748. } else {
  44749. if ( hasExternalTextures && useMultisampledRTT ) {
  44750. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44751. } else {
  44752. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44753. }
  44754. }
  44755. }
  44756. state.drawBuffers( descriptor, fb );
  44757. }
  44758. if ( renderTarget.isXRRenderTarget && renderTarget.autoAllocateDepthBuffer === true ) {
  44759. const renderbuffer = gl.createRenderbuffer();
  44760. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  44761. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  44762. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  44763. } else {
  44764. if ( descriptor.depthTexture !== null ) {
  44765. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  44766. const textureData = this.get( descriptor.depthTexture );
  44767. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44768. textureData.renderTarget = descriptor.renderTarget;
  44769. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  44770. if ( renderTarget.multiview ) {
  44771. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  44772. } else if ( hasExternalTextures && useMultisampledRTT ) {
  44773. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44774. } else {
  44775. if ( descriptor.depthTexture.isArrayTexture ) {
  44776. const layer = this.renderer._activeCubeFace;
  44777. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  44778. } else {
  44779. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44780. }
  44781. }
  44782. }
  44783. }
  44784. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  44785. } else {
  44786. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  44787. if ( isRenderCameraDepthArray ) {
  44788. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44789. const layer = this.renderer._activeCubeFace;
  44790. const depthData = this.get( descriptor.depthTexture );
  44791. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44792. gl.framebufferTextureLayer(
  44793. gl.FRAMEBUFFER,
  44794. depthStyle,
  44795. depthData.textureGPU,
  44796. 0,
  44797. layer
  44798. );
  44799. }
  44800. // rebind external XR textures
  44801. if ( ( isXRRenderTarget && hasExternalTextures ) || renderTarget.multiview ) {
  44802. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44803. // rebind color
  44804. const textureData = this.get( descriptor.textures[ 0 ] );
  44805. if ( renderTarget.multiview ) {
  44806. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  44807. } else if ( useMultisampledRTT ) {
  44808. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44809. } else {
  44810. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44811. }
  44812. // rebind depth
  44813. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44814. if ( renderTarget.autoAllocateDepthBuffer === true ) {
  44815. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  44816. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  44817. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  44818. } else {
  44819. const textureData = this.get( descriptor.depthTexture );
  44820. if ( renderTarget.multiview ) {
  44821. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  44822. } else if ( useMultisampledRTT ) {
  44823. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44824. } else {
  44825. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44826. }
  44827. }
  44828. }
  44829. }
  44830. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  44831. if ( msaaFb === undefined ) {
  44832. const invalidationArray = [];
  44833. msaaFb = gl.createFramebuffer();
  44834. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  44835. const msaaRenderbuffers = [];
  44836. const textures = descriptor.textures;
  44837. for ( let i = 0; i < textures.length; i ++ ) {
  44838. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  44839. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44840. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  44841. if ( depthBuffer ) {
  44842. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44843. invalidationArray.push( depthStyle );
  44844. }
  44845. const texture = descriptor.textures[ i ];
  44846. const textureData = this.get( texture );
  44847. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  44848. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44849. }
  44850. renderTargetContextData.msaaFrameBuffer = msaaFb;
  44851. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  44852. if ( depthRenderbuffer === undefined ) {
  44853. depthRenderbuffer = gl.createRenderbuffer();
  44854. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  44855. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  44856. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44857. invalidationArray.push( depthStyle );
  44858. }
  44859. renderTargetContextData.invalidationArray = invalidationArray;
  44860. }
  44861. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  44862. } else {
  44863. currentFrameBuffer = fb;
  44864. }
  44865. }
  44866. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  44867. }
  44868. /**
  44869. * Computes the VAO key for the given index and attributes.
  44870. *
  44871. * @private
  44872. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  44873. * @return {string} The VAO key.
  44874. */
  44875. _getVaoKey( attributes ) {
  44876. let key = '';
  44877. for ( let i = 0; i < attributes.length; i ++ ) {
  44878. const attributeData = this.get( attributes[ i ] );
  44879. key += ':' + attributeData.id;
  44880. }
  44881. return key;
  44882. }
  44883. /**
  44884. * Creates a VAO from the index and attributes.
  44885. *
  44886. * @private
  44887. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  44888. * @return {Object} The VAO data.
  44889. */
  44890. _createVao( attributes ) {
  44891. const { gl } = this;
  44892. const vaoGPU = gl.createVertexArray();
  44893. let key = '';
  44894. let staticVao = true;
  44895. gl.bindVertexArray( vaoGPU );
  44896. for ( let i = 0; i < attributes.length; i ++ ) {
  44897. const attribute = attributes[ i ];
  44898. const attributeData = this.get( attribute );
  44899. key += ':' + attributeData.id;
  44900. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  44901. gl.enableVertexAttribArray( i );
  44902. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  44903. let stride, offset;
  44904. if ( attribute.isInterleavedBufferAttribute === true ) {
  44905. stride = attribute.data.stride * attributeData.bytesPerElement;
  44906. offset = attribute.offset * attributeData.bytesPerElement;
  44907. } else {
  44908. stride = 0;
  44909. offset = 0;
  44910. }
  44911. if ( attributeData.isInteger ) {
  44912. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  44913. } else {
  44914. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  44915. }
  44916. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  44917. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  44918. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  44919. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  44920. }
  44921. }
  44922. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  44923. this.vaoCache[ key ] = vaoGPU;
  44924. return { vaoGPU, staticVao };
  44925. }
  44926. /**
  44927. * Creates a transform feedback from the given transform buffers.
  44928. *
  44929. * @private
  44930. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  44931. * @return {WebGLTransformFeedback} The transform feedback.
  44932. */
  44933. _getTransformFeedback( transformBuffers ) {
  44934. let key = '';
  44935. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  44936. key += ':' + transformBuffers[ i ].id;
  44937. }
  44938. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  44939. if ( transformFeedbackGPU !== undefined ) {
  44940. return transformFeedbackGPU;
  44941. }
  44942. const { gl } = this;
  44943. transformFeedbackGPU = gl.createTransformFeedback();
  44944. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  44945. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  44946. const attributeData = transformBuffers[ i ];
  44947. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  44948. }
  44949. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  44950. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  44951. return transformFeedbackGPU;
  44952. }
  44953. /**
  44954. * Setups the given bindings.
  44955. *
  44956. * @private
  44957. * @param {Array<BindGroup>} bindings - The bindings.
  44958. * @param {WebGLProgram} programGPU - The WebGL program.
  44959. */
  44960. _setupBindings( bindings, programGPU ) {
  44961. const gl = this.gl;
  44962. for ( const bindGroup of bindings ) {
  44963. for ( const binding of bindGroup.bindings ) {
  44964. const bindingData = this.get( binding );
  44965. const index = bindingData.index;
  44966. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44967. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  44968. gl.uniformBlockBinding( programGPU, location, index );
  44969. } else if ( binding.isSampledTexture ) {
  44970. const location = gl.getUniformLocation( programGPU, binding.name );
  44971. gl.uniform1i( location, index );
  44972. }
  44973. }
  44974. }
  44975. }
  44976. /**
  44977. * Binds the given uniforms.
  44978. *
  44979. * @private
  44980. * @param {Array<BindGroup>} bindings - The bindings.
  44981. */
  44982. _bindUniforms( bindings ) {
  44983. const { gl, state } = this;
  44984. for ( const bindGroup of bindings ) {
  44985. for ( const binding of bindGroup.bindings ) {
  44986. const bindingData = this.get( binding );
  44987. const index = bindingData.index;
  44988. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44989. // TODO USE bindBufferRange to group multiple uniform buffers
  44990. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  44991. } else if ( binding.isSampledTexture ) {
  44992. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  44993. }
  44994. }
  44995. }
  44996. }
  44997. /**
  44998. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  44999. * should be used when MSAA is enabled.
  45000. *
  45001. * @private
  45002. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  45003. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  45004. */
  45005. _useMultisampledExtension( renderTarget ) {
  45006. if ( renderTarget.multiview === true ) {
  45007. return true;
  45008. }
  45009. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget.autoAllocateDepthBuffer !== false;
  45010. }
  45011. /**
  45012. * Frees internal resources.
  45013. */
  45014. dispose() {
  45015. const extension = this.extensions.get( 'WEBGL_lose_context' );
  45016. if ( extension ) extension.loseContext();
  45017. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  45018. }
  45019. }
  45020. const GPUPrimitiveTopology = {
  45021. PointList: 'point-list',
  45022. LineList: 'line-list',
  45023. LineStrip: 'line-strip',
  45024. TriangleList: 'triangle-list',
  45025. TriangleStrip: 'triangle-strip',
  45026. };
  45027. const GPUCompareFunction = {
  45028. Never: 'never',
  45029. Less: 'less',
  45030. Equal: 'equal',
  45031. LessEqual: 'less-equal',
  45032. Greater: 'greater',
  45033. NotEqual: 'not-equal',
  45034. GreaterEqual: 'greater-equal',
  45035. Always: 'always'
  45036. };
  45037. const GPUStoreOp = {
  45038. Store: 'store'};
  45039. const GPULoadOp = {
  45040. Load: 'load',
  45041. Clear: 'clear'
  45042. };
  45043. const GPUFrontFace = {
  45044. CCW: 'ccw'};
  45045. const GPUCullMode = {
  45046. None: 'none',
  45047. Front: 'front',
  45048. Back: 'back'
  45049. };
  45050. const GPUIndexFormat = {
  45051. Uint16: 'uint16',
  45052. Uint32: 'uint32'
  45053. };
  45054. const GPUTextureFormat = {
  45055. // 8-bit formats
  45056. R8Unorm: 'r8unorm',
  45057. R8Snorm: 'r8snorm',
  45058. R8Uint: 'r8uint',
  45059. R8Sint: 'r8sint',
  45060. // 16-bit formats
  45061. R16Uint: 'r16uint',
  45062. R16Sint: 'r16sint',
  45063. R16Float: 'r16float',
  45064. RG8Unorm: 'rg8unorm',
  45065. RG8Snorm: 'rg8snorm',
  45066. RG8Uint: 'rg8uint',
  45067. RG8Sint: 'rg8sint',
  45068. // 32-bit formats
  45069. R32Uint: 'r32uint',
  45070. R32Sint: 'r32sint',
  45071. R32Float: 'r32float',
  45072. RG16Uint: 'rg16uint',
  45073. RG16Sint: 'rg16sint',
  45074. RG16Float: 'rg16float',
  45075. RGBA8Unorm: 'rgba8unorm',
  45076. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  45077. RGBA8Snorm: 'rgba8snorm',
  45078. RGBA8Uint: 'rgba8uint',
  45079. RGBA8Sint: 'rgba8sint',
  45080. BGRA8Unorm: 'bgra8unorm',
  45081. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  45082. // Packed 32-bit formats
  45083. RGB9E5UFloat: 'rgb9e5ufloat',
  45084. RGB10A2Unorm: 'rgb10a2unorm',
  45085. RG11B10UFloat: 'rgb10a2unorm',
  45086. // 64-bit formats
  45087. RG32Uint: 'rg32uint',
  45088. RG32Sint: 'rg32sint',
  45089. RG32Float: 'rg32float',
  45090. RGBA16Uint: 'rgba16uint',
  45091. RGBA16Sint: 'rgba16sint',
  45092. RGBA16Float: 'rgba16float',
  45093. // 128-bit formats
  45094. RGBA32Uint: 'rgba32uint',
  45095. RGBA32Sint: 'rgba32sint',
  45096. RGBA32Float: 'rgba32float',
  45097. Depth16Unorm: 'depth16unorm',
  45098. Depth24Plus: 'depth24plus',
  45099. Depth24PlusStencil8: 'depth24plus-stencil8',
  45100. Depth32Float: 'depth32float',
  45101. // 'depth32float-stencil8' extension
  45102. Depth32FloatStencil8: 'depth32float-stencil8',
  45103. // BC compressed formats usable if 'texture-compression-bc' is both
  45104. // supported by the device/user agent and enabled in requestDevice.
  45105. BC1RGBAUnorm: 'bc1-rgba-unorm',
  45106. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  45107. BC2RGBAUnorm: 'bc2-rgba-unorm',
  45108. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  45109. BC3RGBAUnorm: 'bc3-rgba-unorm',
  45110. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  45111. BC4RUnorm: 'bc4-r-unorm',
  45112. BC4RSnorm: 'bc4-r-snorm',
  45113. BC5RGUnorm: 'bc5-rg-unorm',
  45114. BC5RGSnorm: 'bc5-rg-snorm',
  45115. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  45116. BC6HRGBFloat: 'bc6h-rgb-float',
  45117. BC7RGBAUnorm: 'bc7-rgba-unorm',
  45118. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  45119. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  45120. // supported by the device/user agent and enabled in requestDevice.
  45121. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  45122. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  45123. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  45124. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  45125. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  45126. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  45127. EACR11Unorm: 'eac-r11unorm',
  45128. EACR11Snorm: 'eac-r11snorm',
  45129. EACRG11Unorm: 'eac-rg11unorm',
  45130. EACRG11Snorm: 'eac-rg11snorm',
  45131. // ASTC compressed formats usable if 'texture-compression-astc' is both
  45132. // supported by the device/user agent and enabled in requestDevice.
  45133. ASTC4x4Unorm: 'astc-4x4-unorm',
  45134. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  45135. ASTC5x4Unorm: 'astc-5x4-unorm',
  45136. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  45137. ASTC5x5Unorm: 'astc-5x5-unorm',
  45138. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  45139. ASTC6x5Unorm: 'astc-6x5-unorm',
  45140. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  45141. ASTC6x6Unorm: 'astc-6x6-unorm',
  45142. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  45143. ASTC8x5Unorm: 'astc-8x5-unorm',
  45144. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  45145. ASTC8x6Unorm: 'astc-8x6-unorm',
  45146. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  45147. ASTC8x8Unorm: 'astc-8x8-unorm',
  45148. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  45149. ASTC10x5Unorm: 'astc-10x5-unorm',
  45150. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  45151. ASTC10x6Unorm: 'astc-10x6-unorm',
  45152. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  45153. ASTC10x8Unorm: 'astc-10x8-unorm',
  45154. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  45155. ASTC10x10Unorm: 'astc-10x10-unorm',
  45156. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  45157. ASTC12x10Unorm: 'astc-12x10-unorm',
  45158. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  45159. ASTC12x12Unorm: 'astc-12x12-unorm',
  45160. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  45161. };
  45162. const GPUAddressMode = {
  45163. ClampToEdge: 'clamp-to-edge',
  45164. Repeat: 'repeat',
  45165. MirrorRepeat: 'mirror-repeat'
  45166. };
  45167. const GPUFilterMode = {
  45168. Linear: 'linear',
  45169. Nearest: 'nearest'
  45170. };
  45171. const GPUBlendFactor = {
  45172. Zero: 'zero',
  45173. One: 'one',
  45174. Src: 'src',
  45175. OneMinusSrc: 'one-minus-src',
  45176. SrcAlpha: 'src-alpha',
  45177. OneMinusSrcAlpha: 'one-minus-src-alpha',
  45178. Dst: 'dst',
  45179. OneMinusDstColor: 'one-minus-dst',
  45180. DstAlpha: 'dst-alpha',
  45181. OneMinusDstAlpha: 'one-minus-dst-alpha',
  45182. SrcAlphaSaturated: 'src-alpha-saturated',
  45183. Constant: 'constant',
  45184. OneMinusConstant: 'one-minus-constant'
  45185. };
  45186. const GPUBlendOperation = {
  45187. Add: 'add',
  45188. Subtract: 'subtract',
  45189. ReverseSubtract: 'reverse-subtract',
  45190. Min: 'min',
  45191. Max: 'max'
  45192. };
  45193. const GPUColorWriteFlags = {
  45194. None: 0,
  45195. All: 0xF
  45196. };
  45197. const GPUStencilOperation = {
  45198. Keep: 'keep',
  45199. Zero: 'zero',
  45200. Replace: 'replace',
  45201. Invert: 'invert',
  45202. IncrementClamp: 'increment-clamp',
  45203. DecrementClamp: 'decrement-clamp',
  45204. IncrementWrap: 'increment-wrap',
  45205. DecrementWrap: 'decrement-wrap'
  45206. };
  45207. const GPUBufferBindingType = {
  45208. Storage: 'storage',
  45209. ReadOnlyStorage: 'read-only-storage'
  45210. };
  45211. const GPUStorageTextureAccess = {
  45212. WriteOnly: 'write-only',
  45213. ReadOnly: 'read-only',
  45214. ReadWrite: 'read-write',
  45215. };
  45216. const GPUSamplerBindingType = {
  45217. NonFiltering: 'non-filtering',
  45218. Comparison: 'comparison'
  45219. };
  45220. const GPUTextureSampleType = {
  45221. Float: 'float',
  45222. UnfilterableFloat: 'unfilterable-float',
  45223. Depth: 'depth',
  45224. SInt: 'sint',
  45225. UInt: 'uint'
  45226. };
  45227. const GPUTextureDimension = {
  45228. TwoD: '2d',
  45229. ThreeD: '3d'
  45230. };
  45231. const GPUTextureViewDimension = {
  45232. TwoD: '2d',
  45233. TwoDArray: '2d-array',
  45234. Cube: 'cube',
  45235. ThreeD: '3d'
  45236. };
  45237. const GPUTextureAspect = {
  45238. All: 'all'};
  45239. const GPUInputStepMode = {
  45240. Vertex: 'vertex',
  45241. Instance: 'instance'
  45242. };
  45243. const GPUFeatureName = {
  45244. DepthClipControl: 'depth-clip-control',
  45245. Depth32FloatStencil8: 'depth32float-stencil8',
  45246. TextureCompressionBC: 'texture-compression-bc',
  45247. TextureCompressionETC2: 'texture-compression-etc2',
  45248. TextureCompressionASTC: 'texture-compression-astc',
  45249. TimestampQuery: 'timestamp-query',
  45250. IndirectFirstInstance: 'indirect-first-instance',
  45251. ShaderF16: 'shader-f16',
  45252. RG11B10UFloat: 'rg11b10ufloat-renderable',
  45253. BGRA8UNormStorage: 'bgra8unorm-storage',
  45254. Float32Filterable: 'float32-filterable',
  45255. ClipDistances: 'clip-distances',
  45256. DualSourceBlending: 'dual-source-blending',
  45257. Subgroups: 'subgroups'
  45258. };
  45259. /**
  45260. * Represents a sampler binding type.
  45261. *
  45262. * @private
  45263. * @augments Binding
  45264. */
  45265. class Sampler extends Binding {
  45266. /**
  45267. * Constructs a new sampler.
  45268. *
  45269. * @param {string} name - The samplers's name.
  45270. * @param {?Texture} texture - The texture this binding is referring to.
  45271. */
  45272. constructor( name, texture ) {
  45273. super( name );
  45274. /**
  45275. * The texture the sampler is referring to.
  45276. *
  45277. * @type {?Texture}
  45278. */
  45279. this.texture = texture;
  45280. /**
  45281. * The binding's version.
  45282. *
  45283. * @type {number}
  45284. */
  45285. this.version = texture ? texture.version : 0;
  45286. /**
  45287. * This flag can be used for type testing.
  45288. *
  45289. * @type {boolean}
  45290. * @readonly
  45291. * @default true
  45292. */
  45293. this.isSampler = true;
  45294. }
  45295. }
  45296. /**
  45297. * A special form of sampler binding type.
  45298. * It's texture value is managed by a node object.
  45299. *
  45300. * @private
  45301. * @augments Sampler
  45302. */
  45303. class NodeSampler extends Sampler {
  45304. /**
  45305. * Constructs a new node-based sampler.
  45306. *
  45307. * @param {string} name - The samplers's name.
  45308. * @param {TextureNode} textureNode - The texture node.
  45309. * @param {UniformGroupNode} groupNode - The uniform group node.
  45310. */
  45311. constructor( name, textureNode, groupNode ) {
  45312. super( name, textureNode ? textureNode.value : null );
  45313. /**
  45314. * The texture node.
  45315. *
  45316. * @type {TextureNode}
  45317. */
  45318. this.textureNode = textureNode;
  45319. /**
  45320. * The uniform group node.
  45321. *
  45322. * @type {UniformGroupNode}
  45323. */
  45324. this.groupNode = groupNode;
  45325. }
  45326. /**
  45327. * Updates the texture value of this sampler.
  45328. */
  45329. update() {
  45330. this.texture = this.textureNode.value;
  45331. }
  45332. }
  45333. /**
  45334. * Represents a storage buffer binding type.
  45335. *
  45336. * @private
  45337. * @augments Buffer
  45338. */
  45339. class StorageBuffer extends Buffer {
  45340. /**
  45341. * Constructs a new uniform buffer.
  45342. *
  45343. * @param {string} name - The buffer's name.
  45344. * @param {BufferAttribute} attribute - The buffer attribute.
  45345. */
  45346. constructor( name, attribute ) {
  45347. super( name, attribute ? attribute.array : null );
  45348. /**
  45349. * This flag can be used for type testing.
  45350. *
  45351. * @type {BufferAttribute}
  45352. */
  45353. this.attribute = attribute;
  45354. /**
  45355. * This flag can be used for type testing.
  45356. *
  45357. * @type {boolean}
  45358. * @readonly
  45359. * @default true
  45360. */
  45361. this.isStorageBuffer = true;
  45362. }
  45363. }
  45364. let _id = 0;
  45365. /**
  45366. * A special form of storage buffer binding type.
  45367. * It's buffer value is managed by a node object.
  45368. *
  45369. * @private
  45370. * @augments StorageBuffer
  45371. */
  45372. class NodeStorageBuffer extends StorageBuffer {
  45373. /**
  45374. * Constructs a new node-based storage buffer.
  45375. *
  45376. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  45377. * @param {UniformGroupNode} groupNode - The uniform group node.
  45378. */
  45379. constructor( nodeUniform, groupNode ) {
  45380. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  45381. /**
  45382. * The node uniform.
  45383. *
  45384. * @type {StorageBufferNode}
  45385. */
  45386. this.nodeUniform = nodeUniform;
  45387. /**
  45388. * The access type.
  45389. *
  45390. * @type {string}
  45391. */
  45392. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  45393. /**
  45394. * The uniform group node.
  45395. *
  45396. * @type {UniformGroupNode}
  45397. */
  45398. this.groupNode = groupNode;
  45399. }
  45400. /**
  45401. * The storage buffer.
  45402. *
  45403. * @type {BufferAttribute}
  45404. */
  45405. get buffer() {
  45406. return this.nodeUniform.value;
  45407. }
  45408. }
  45409. /**
  45410. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  45411. *
  45412. * @private
  45413. */
  45414. class WebGPUTexturePassUtils extends DataMap {
  45415. /**
  45416. * Constructs a new utility object.
  45417. *
  45418. * @param {GPUDevice} device - The WebGPU device.
  45419. */
  45420. constructor( device ) {
  45421. super();
  45422. /**
  45423. * The WebGPU device.
  45424. *
  45425. * @type {GPUDevice}
  45426. */
  45427. this.device = device;
  45428. const mipmapVertexSource = `
  45429. struct VarysStruct {
  45430. @builtin( position ) Position: vec4<f32>,
  45431. @location( 0 ) vTex : vec2<f32>
  45432. };
  45433. @vertex
  45434. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  45435. var Varys : VarysStruct;
  45436. var pos = array< vec2<f32>, 4 >(
  45437. vec2<f32>( -1.0, 1.0 ),
  45438. vec2<f32>( 1.0, 1.0 ),
  45439. vec2<f32>( -1.0, -1.0 ),
  45440. vec2<f32>( 1.0, -1.0 )
  45441. );
  45442. var tex = array< vec2<f32>, 4 >(
  45443. vec2<f32>( 0.0, 0.0 ),
  45444. vec2<f32>( 1.0, 0.0 ),
  45445. vec2<f32>( 0.0, 1.0 ),
  45446. vec2<f32>( 1.0, 1.0 )
  45447. );
  45448. Varys.vTex = tex[ vertexIndex ];
  45449. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  45450. return Varys;
  45451. }
  45452. `;
  45453. const mipmapFragmentSource = `
  45454. @group( 0 ) @binding( 0 )
  45455. var imgSampler : sampler;
  45456. @group( 0 ) @binding( 1 )
  45457. var img : texture_2d<f32>;
  45458. @fragment
  45459. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  45460. return textureSample( img, imgSampler, vTex );
  45461. }
  45462. `;
  45463. const flipYFragmentSource = `
  45464. @group( 0 ) @binding( 0 )
  45465. var imgSampler : sampler;
  45466. @group( 0 ) @binding( 1 )
  45467. var img : texture_2d<f32>;
  45468. @fragment
  45469. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  45470. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  45471. }
  45472. `;
  45473. /**
  45474. * The mipmap GPU sampler.
  45475. *
  45476. * @type {GPUSampler}
  45477. */
  45478. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  45479. /**
  45480. * The flipY GPU sampler.
  45481. *
  45482. * @type {GPUSampler}
  45483. */
  45484. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  45485. /**
  45486. * A cache for GPU render pipelines used for copy/transfer passes.
  45487. * Every texture format requires a unique pipeline.
  45488. *
  45489. * @type {Object<string,GPURenderPipeline>}
  45490. */
  45491. this.transferPipelines = {};
  45492. /**
  45493. * A cache for GPU render pipelines used for flipY passes.
  45494. * Every texture format requires a unique pipeline.
  45495. *
  45496. * @type {Object<string,GPURenderPipeline>}
  45497. */
  45498. this.flipYPipelines = {};
  45499. /**
  45500. * The mipmap vertex shader module.
  45501. *
  45502. * @type {GPUShaderModule}
  45503. */
  45504. this.mipmapVertexShaderModule = device.createShaderModule( {
  45505. label: 'mipmapVertex',
  45506. code: mipmapVertexSource
  45507. } );
  45508. /**
  45509. * The mipmap fragment shader module.
  45510. *
  45511. * @type {GPUShaderModule}
  45512. */
  45513. this.mipmapFragmentShaderModule = device.createShaderModule( {
  45514. label: 'mipmapFragment',
  45515. code: mipmapFragmentSource
  45516. } );
  45517. /**
  45518. * The flipY fragment shader module.
  45519. *
  45520. * @type {GPUShaderModule}
  45521. */
  45522. this.flipYFragmentShaderModule = device.createShaderModule( {
  45523. label: 'flipYFragment',
  45524. code: flipYFragmentSource
  45525. } );
  45526. }
  45527. /**
  45528. * Returns a render pipeline for the internal copy render pass. The pass
  45529. * requires a unique render pipeline for each texture format.
  45530. *
  45531. * @param {string} format - The GPU texture format
  45532. * @return {GPURenderPipeline} The GPU render pipeline.
  45533. */
  45534. getTransferPipeline( format ) {
  45535. let pipeline = this.transferPipelines[ format ];
  45536. if ( pipeline === undefined ) {
  45537. pipeline = this.device.createRenderPipeline( {
  45538. label: `mipmap-${ format }`,
  45539. vertex: {
  45540. module: this.mipmapVertexShaderModule,
  45541. entryPoint: 'main'
  45542. },
  45543. fragment: {
  45544. module: this.mipmapFragmentShaderModule,
  45545. entryPoint: 'main',
  45546. targets: [ { format } ]
  45547. },
  45548. primitive: {
  45549. topology: GPUPrimitiveTopology.TriangleStrip,
  45550. stripIndexFormat: GPUIndexFormat.Uint32
  45551. },
  45552. layout: 'auto'
  45553. } );
  45554. this.transferPipelines[ format ] = pipeline;
  45555. }
  45556. return pipeline;
  45557. }
  45558. /**
  45559. * Returns a render pipeline for the flipY render pass. The pass
  45560. * requires a unique render pipeline for each texture format.
  45561. *
  45562. * @param {string} format - The GPU texture format
  45563. * @return {GPURenderPipeline} The GPU render pipeline.
  45564. */
  45565. getFlipYPipeline( format ) {
  45566. let pipeline = this.flipYPipelines[ format ];
  45567. if ( pipeline === undefined ) {
  45568. pipeline = this.device.createRenderPipeline( {
  45569. label: `flipY-${ format }`,
  45570. vertex: {
  45571. module: this.mipmapVertexShaderModule,
  45572. entryPoint: 'main'
  45573. },
  45574. fragment: {
  45575. module: this.flipYFragmentShaderModule,
  45576. entryPoint: 'main',
  45577. targets: [ { format } ]
  45578. },
  45579. primitive: {
  45580. topology: GPUPrimitiveTopology.TriangleStrip,
  45581. stripIndexFormat: GPUIndexFormat.Uint32
  45582. },
  45583. layout: 'auto'
  45584. } );
  45585. this.flipYPipelines[ format ] = pipeline;
  45586. }
  45587. return pipeline;
  45588. }
  45589. /**
  45590. * Flip the contents of the given GPU texture along its vertical axis.
  45591. *
  45592. * @param {GPUTexture} textureGPU - The GPU texture object.
  45593. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45594. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  45595. */
  45596. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  45597. const format = textureGPUDescriptor.format;
  45598. const { width, height } = textureGPUDescriptor.size;
  45599. const transferPipeline = this.getTransferPipeline( format );
  45600. const flipYPipeline = this.getFlipYPipeline( format );
  45601. const tempTexture = this.device.createTexture( {
  45602. size: { width, height, depthOrArrayLayers: 1 },
  45603. format,
  45604. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  45605. } );
  45606. const srcView = textureGPU.createView( {
  45607. baseMipLevel: 0,
  45608. mipLevelCount: 1,
  45609. dimension: GPUTextureViewDimension.TwoD,
  45610. baseArrayLayer
  45611. } );
  45612. const dstView = tempTexture.createView( {
  45613. baseMipLevel: 0,
  45614. mipLevelCount: 1,
  45615. dimension: GPUTextureViewDimension.TwoD,
  45616. baseArrayLayer: 0
  45617. } );
  45618. const commandEncoder = this.device.createCommandEncoder( {} );
  45619. const pass = ( pipeline, sourceView, destinationView ) => {
  45620. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  45621. const bindGroup = this.device.createBindGroup( {
  45622. layout: bindGroupLayout,
  45623. entries: [ {
  45624. binding: 0,
  45625. resource: this.flipYSampler
  45626. }, {
  45627. binding: 1,
  45628. resource: sourceView
  45629. } ]
  45630. } );
  45631. const passEncoder = commandEncoder.beginRenderPass( {
  45632. colorAttachments: [ {
  45633. view: destinationView,
  45634. loadOp: GPULoadOp.Clear,
  45635. storeOp: GPUStoreOp.Store,
  45636. clearValue: [ 0, 0, 0, 0 ]
  45637. } ]
  45638. } );
  45639. passEncoder.setPipeline( pipeline );
  45640. passEncoder.setBindGroup( 0, bindGroup );
  45641. passEncoder.draw( 4, 1, 0, 0 );
  45642. passEncoder.end();
  45643. };
  45644. pass( transferPipeline, srcView, dstView );
  45645. pass( flipYPipeline, dstView, srcView );
  45646. this.device.queue.submit( [ commandEncoder.finish() ] );
  45647. tempTexture.destroy();
  45648. }
  45649. /**
  45650. * Generates mipmaps for the given GPU texture.
  45651. *
  45652. * @param {GPUTexture} textureGPU - The GPU texture object.
  45653. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45654. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  45655. */
  45656. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  45657. const textureData = this.get( textureGPU );
  45658. if ( textureData.useCount === undefined ) {
  45659. textureData.useCount = 0;
  45660. textureData.layers = [];
  45661. }
  45662. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  45663. const commandEncoder = this.device.createCommandEncoder( {} );
  45664. this._mipmapRunBundles( commandEncoder, passes );
  45665. this.device.queue.submit( [ commandEncoder.finish() ] );
  45666. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  45667. textureData.useCount ++;
  45668. }
  45669. /**
  45670. * Since multiple copy render passes are required to generate mipmaps, the passes
  45671. * are managed as render bundles to improve performance.
  45672. *
  45673. * @param {GPUTexture} textureGPU - The GPU texture object.
  45674. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45675. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  45676. * @return {Array<Object>} An array of render bundles.
  45677. */
  45678. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  45679. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  45680. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  45681. let srcView = textureGPU.createView( {
  45682. baseMipLevel: 0,
  45683. mipLevelCount: 1,
  45684. dimension: GPUTextureViewDimension.TwoD,
  45685. baseArrayLayer
  45686. } );
  45687. const passes = [];
  45688. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  45689. const bindGroup = this.device.createBindGroup( {
  45690. layout: bindGroupLayout,
  45691. entries: [ {
  45692. binding: 0,
  45693. resource: this.mipmapSampler
  45694. }, {
  45695. binding: 1,
  45696. resource: srcView
  45697. } ]
  45698. } );
  45699. const dstView = textureGPU.createView( {
  45700. baseMipLevel: i,
  45701. mipLevelCount: 1,
  45702. dimension: GPUTextureViewDimension.TwoD,
  45703. baseArrayLayer
  45704. } );
  45705. const passDescriptor = {
  45706. colorAttachments: [ {
  45707. view: dstView,
  45708. loadOp: GPULoadOp.Clear,
  45709. storeOp: GPUStoreOp.Store,
  45710. clearValue: [ 0, 0, 0, 0 ]
  45711. } ]
  45712. };
  45713. const passEncoder = this.device.createRenderBundleEncoder( {
  45714. colorFormats: [ textureGPUDescriptor.format ]
  45715. } );
  45716. passEncoder.setPipeline( pipeline );
  45717. passEncoder.setBindGroup( 0, bindGroup );
  45718. passEncoder.draw( 4, 1, 0, 0 );
  45719. passes.push( {
  45720. renderBundles: [ passEncoder.finish() ],
  45721. passDescriptor
  45722. } );
  45723. srcView = dstView;
  45724. }
  45725. return passes;
  45726. }
  45727. /**
  45728. * Executes the render bundles.
  45729. *
  45730. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  45731. * @param {Array<Object>} passes - An array of render bundles.
  45732. */
  45733. _mipmapRunBundles( commandEncoder, passes ) {
  45734. const levels = passes.length;
  45735. for ( let i = 0; i < levels; i ++ ) {
  45736. const pass = passes[ i ];
  45737. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  45738. passEncoder.executeBundles( pass.renderBundles );
  45739. passEncoder.end();
  45740. }
  45741. }
  45742. }
  45743. const _compareToWebGPU = {
  45744. [ NeverCompare ]: 'never',
  45745. [ LessCompare ]: 'less',
  45746. [ EqualCompare ]: 'equal',
  45747. [ LessEqualCompare ]: 'less-equal',
  45748. [ GreaterCompare ]: 'greater',
  45749. [ GreaterEqualCompare ]: 'greater-equal',
  45750. [ AlwaysCompare ]: 'always',
  45751. [ NotEqualCompare ]: 'not-equal'
  45752. };
  45753. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  45754. /**
  45755. * A WebGPU backend utility module for managing textures.
  45756. *
  45757. * @private
  45758. */
  45759. class WebGPUTextureUtils {
  45760. /**
  45761. * Constructs a new utility object.
  45762. *
  45763. * @param {WebGPUBackend} backend - The WebGPU backend.
  45764. */
  45765. constructor( backend ) {
  45766. /**
  45767. * A reference to the WebGPU backend.
  45768. *
  45769. * @type {WebGPUBackend}
  45770. */
  45771. this.backend = backend;
  45772. /**
  45773. * A reference to the pass utils.
  45774. *
  45775. * @type {?WebGPUTexturePassUtils}
  45776. * @default null
  45777. */
  45778. this._passUtils = null;
  45779. /**
  45780. * A dictionary for managing default textures. The key
  45781. * is the texture format, the value the texture object.
  45782. *
  45783. * @type {Object<string,Texture>}
  45784. */
  45785. this.defaultTexture = {};
  45786. /**
  45787. * A dictionary for managing default cube textures. The key
  45788. * is the texture format, the value the texture object.
  45789. *
  45790. * @type {Object<string,CubeTexture>}
  45791. */
  45792. this.defaultCubeTexture = {};
  45793. /**
  45794. * A default video frame.
  45795. *
  45796. * @type {?VideoFrame}
  45797. * @default null
  45798. */
  45799. this.defaultVideoFrame = null;
  45800. /**
  45801. * Represents the color attachment of the default framebuffer.
  45802. *
  45803. * @type {?GPUTexture}
  45804. * @default null
  45805. */
  45806. this.colorBuffer = null;
  45807. /**
  45808. * Represents the depth attachment of the default framebuffer.
  45809. *
  45810. * @type {DepthTexture}
  45811. */
  45812. this.depthTexture = new DepthTexture();
  45813. this.depthTexture.name = 'depthBuffer';
  45814. }
  45815. /**
  45816. * Creates a GPU sampler for the given texture.
  45817. *
  45818. * @param {Texture} texture - The texture to create the sampler for.
  45819. */
  45820. createSampler( texture ) {
  45821. const backend = this.backend;
  45822. const device = backend.device;
  45823. const textureGPU = backend.get( texture );
  45824. const samplerDescriptorGPU = {
  45825. addressModeU: this._convertAddressMode( texture.wrapS ),
  45826. addressModeV: this._convertAddressMode( texture.wrapT ),
  45827. addressModeW: this._convertAddressMode( texture.wrapR ),
  45828. magFilter: this._convertFilterMode( texture.magFilter ),
  45829. minFilter: this._convertFilterMode( texture.minFilter ),
  45830. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  45831. maxAnisotropy: 1
  45832. };
  45833. // anisotropy can only be used when all filter modes are set to linear.
  45834. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  45835. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  45836. }
  45837. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  45838. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  45839. }
  45840. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  45841. }
  45842. /**
  45843. * Creates a default texture for the given texture that can be used
  45844. * as a placeholder until the actual texture is ready for usage.
  45845. *
  45846. * @param {Texture} texture - The texture to create a default texture for.
  45847. */
  45848. createDefaultTexture( texture ) {
  45849. let textureGPU;
  45850. const format = getFormat( texture );
  45851. if ( texture.isCubeTexture ) {
  45852. textureGPU = this._getDefaultCubeTextureGPU( format );
  45853. } else if ( texture.isVideoTexture ) {
  45854. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  45855. } else {
  45856. textureGPU = this._getDefaultTextureGPU( format );
  45857. }
  45858. this.backend.get( texture ).texture = textureGPU;
  45859. }
  45860. /**
  45861. * Defines a texture on the GPU for the given texture object.
  45862. *
  45863. * @param {Texture} texture - The texture.
  45864. * @param {Object} [options={}] - Optional configuration parameter.
  45865. */
  45866. createTexture( texture, options = {} ) {
  45867. const backend = this.backend;
  45868. const textureData = backend.get( texture );
  45869. if ( textureData.initialized ) {
  45870. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  45871. }
  45872. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  45873. if ( options.levels === undefined ) options.levels = 1;
  45874. if ( options.depth === undefined ) options.depth = 1;
  45875. const { width, height, depth, levels } = options;
  45876. if ( texture.isFramebufferTexture ) {
  45877. if ( options.renderTarget ) {
  45878. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  45879. } else {
  45880. options.format = this.backend.utils.getPreferredCanvasFormat();
  45881. }
  45882. }
  45883. const dimension = this._getDimension( texture );
  45884. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  45885. textureData.format = format;
  45886. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  45887. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  45888. if ( texture.isStorageTexture === true ) {
  45889. usage |= GPUTextureUsage.STORAGE_BINDING;
  45890. }
  45891. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  45892. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  45893. }
  45894. const textureDescriptorGPU = {
  45895. label: texture.name,
  45896. size: {
  45897. width: width,
  45898. height: height,
  45899. depthOrArrayLayers: depth,
  45900. },
  45901. mipLevelCount: levels,
  45902. sampleCount: primarySamples,
  45903. dimension: dimension,
  45904. format: format,
  45905. usage: usage
  45906. };
  45907. // texture creation
  45908. if ( texture.isVideoTexture ) {
  45909. const video = texture.source.data;
  45910. const videoFrame = new VideoFrame( video );
  45911. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  45912. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  45913. videoFrame.close();
  45914. textureData.externalTexture = video;
  45915. } else {
  45916. if ( format === undefined ) {
  45917. console.warn( 'WebGPURenderer: Texture format not supported.' );
  45918. this.createDefaultTexture( texture );
  45919. return;
  45920. }
  45921. if ( texture.isCubeTexture ) {
  45922. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  45923. }
  45924. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  45925. }
  45926. if ( isMSAA ) {
  45927. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  45928. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  45929. msaaTextureDescriptorGPU.sampleCount = samples;
  45930. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  45931. }
  45932. textureData.initialized = true;
  45933. textureData.textureDescriptorGPU = textureDescriptorGPU;
  45934. }
  45935. /**
  45936. * Destroys the GPU data for the given texture object.
  45937. *
  45938. * @param {Texture} texture - The texture.
  45939. */
  45940. destroyTexture( texture ) {
  45941. const backend = this.backend;
  45942. const textureData = backend.get( texture );
  45943. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  45944. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  45945. backend.delete( texture );
  45946. }
  45947. /**
  45948. * Destroys the GPU sampler for the given texture.
  45949. *
  45950. * @param {Texture} texture - The texture to destroy the sampler for.
  45951. */
  45952. destroySampler( texture ) {
  45953. const backend = this.backend;
  45954. const textureData = backend.get( texture );
  45955. delete textureData.sampler;
  45956. }
  45957. /**
  45958. * Generates mipmaps for the given texture.
  45959. *
  45960. * @param {Texture} texture - The texture.
  45961. */
  45962. generateMipmaps( texture ) {
  45963. const textureData = this.backend.get( texture );
  45964. if ( texture.isCubeTexture ) {
  45965. for ( let i = 0; i < 6; i ++ ) {
  45966. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  45967. }
  45968. } else {
  45969. const depth = texture.image.depth || 1;
  45970. for ( let i = 0; i < depth; i ++ ) {
  45971. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  45972. }
  45973. }
  45974. }
  45975. /**
  45976. * Returns the color buffer representing the color
  45977. * attachment of the default framebuffer.
  45978. *
  45979. * @return {GPUTexture} The color buffer.
  45980. */
  45981. getColorBuffer() {
  45982. if ( this.colorBuffer ) this.colorBuffer.destroy();
  45983. const backend = this.backend;
  45984. const { width, height } = backend.getDrawingBufferSize();
  45985. this.colorBuffer = backend.device.createTexture( {
  45986. label: 'colorBuffer',
  45987. size: {
  45988. width: width,
  45989. height: height,
  45990. depthOrArrayLayers: 1
  45991. },
  45992. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  45993. format: backend.utils.getPreferredCanvasFormat(),
  45994. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  45995. } );
  45996. return this.colorBuffer;
  45997. }
  45998. /**
  45999. * Returns the depth buffer representing the depth
  46000. * attachment of the default framebuffer.
  46001. *
  46002. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  46003. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  46004. * @return {GPUTexture} The depth buffer.
  46005. */
  46006. getDepthBuffer( depth = true, stencil = false ) {
  46007. const backend = this.backend;
  46008. const { width, height } = backend.getDrawingBufferSize();
  46009. const depthTexture = this.depthTexture;
  46010. const depthTextureGPU = backend.get( depthTexture ).texture;
  46011. let format, type;
  46012. if ( stencil ) {
  46013. format = DepthStencilFormat;
  46014. type = UnsignedInt248Type;
  46015. } else if ( depth ) {
  46016. format = DepthFormat;
  46017. type = UnsignedIntType;
  46018. }
  46019. if ( depthTextureGPU !== undefined ) {
  46020. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  46021. return depthTextureGPU;
  46022. }
  46023. this.destroyTexture( depthTexture );
  46024. }
  46025. depthTexture.name = 'depthBuffer';
  46026. depthTexture.format = format;
  46027. depthTexture.type = type;
  46028. depthTexture.image.width = width;
  46029. depthTexture.image.height = height;
  46030. this.createTexture( depthTexture, { width, height } );
  46031. return backend.get( depthTexture ).texture;
  46032. }
  46033. /**
  46034. * Uploads the updated texture data to the GPU.
  46035. *
  46036. * @param {Texture} texture - The texture.
  46037. * @param {Object} [options={}] - Optional configuration parameter.
  46038. */
  46039. updateTexture( texture, options ) {
  46040. const textureData = this.backend.get( texture );
  46041. const { textureDescriptorGPU } = textureData;
  46042. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  46043. return;
  46044. // transfer texture data
  46045. if ( texture.isDataTexture ) {
  46046. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  46047. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  46048. for ( let i = 0; i < options.image.depth; i ++ ) {
  46049. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  46050. }
  46051. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  46052. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  46053. } else if ( texture.isCubeTexture ) {
  46054. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY, texture.premultiplyAlpha );
  46055. } else if ( texture.isVideoTexture ) {
  46056. const video = texture.source.data;
  46057. textureData.externalTexture = video;
  46058. } else {
  46059. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  46060. }
  46061. //
  46062. textureData.version = texture.version;
  46063. if ( texture.onUpdate ) texture.onUpdate( texture );
  46064. }
  46065. /**
  46066. * Returns texture data as a typed array.
  46067. *
  46068. * @async
  46069. * @param {Texture} texture - The texture to copy.
  46070. * @param {number} x - The x coordinate of the copy origin.
  46071. * @param {number} y - The y coordinate of the copy origin.
  46072. * @param {number} width - The width of the copy.
  46073. * @param {number} height - The height of the copy.
  46074. * @param {number} faceIndex - The face index.
  46075. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46076. */
  46077. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46078. const device = this.backend.device;
  46079. const textureData = this.backend.get( texture );
  46080. const textureGPU = textureData.texture;
  46081. const format = textureData.textureDescriptorGPU.format;
  46082. const bytesPerTexel = this._getBytesPerTexel( format );
  46083. let bytesPerRow = width * bytesPerTexel;
  46084. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  46085. const readBuffer = device.createBuffer(
  46086. {
  46087. size: width * height * bytesPerTexel,
  46088. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  46089. }
  46090. );
  46091. const encoder = device.createCommandEncoder();
  46092. encoder.copyTextureToBuffer(
  46093. {
  46094. texture: textureGPU,
  46095. origin: { x, y, z: faceIndex },
  46096. },
  46097. {
  46098. buffer: readBuffer,
  46099. bytesPerRow: bytesPerRow
  46100. },
  46101. {
  46102. width: width,
  46103. height: height
  46104. }
  46105. );
  46106. const typedArrayType = this._getTypedArrayType( format );
  46107. device.queue.submit( [ encoder.finish() ] );
  46108. await readBuffer.mapAsync( GPUMapMode.READ );
  46109. const buffer = readBuffer.getMappedRange();
  46110. return new typedArrayType( buffer );
  46111. }
  46112. /**
  46113. * Returns the default GPU texture for the given format.
  46114. *
  46115. * @private
  46116. * @param {string} format - The GPU format.
  46117. * @return {GPUTexture} The GPU texture.
  46118. */
  46119. _getDefaultTextureGPU( format ) {
  46120. let defaultTexture = this.defaultTexture[ format ];
  46121. if ( defaultTexture === undefined ) {
  46122. const texture = new Texture();
  46123. texture.minFilter = NearestFilter;
  46124. texture.magFilter = NearestFilter;
  46125. this.createTexture( texture, { width: 1, height: 1, format } );
  46126. this.defaultTexture[ format ] = defaultTexture = texture;
  46127. }
  46128. return this.backend.get( defaultTexture ).texture;
  46129. }
  46130. /**
  46131. * Returns the default GPU cube texture for the given format.
  46132. *
  46133. * @private
  46134. * @param {string} format - The GPU format.
  46135. * @return {GPUTexture} The GPU texture.
  46136. */
  46137. _getDefaultCubeTextureGPU( format ) {
  46138. let defaultCubeTexture = this.defaultTexture[ format ];
  46139. if ( defaultCubeTexture === undefined ) {
  46140. const texture = new CubeTexture();
  46141. texture.minFilter = NearestFilter;
  46142. texture.magFilter = NearestFilter;
  46143. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  46144. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  46145. }
  46146. return this.backend.get( defaultCubeTexture ).texture;
  46147. }
  46148. /**
  46149. * Returns the default video frame used as default data in context of video textures.
  46150. *
  46151. * @private
  46152. * @return {VideoFrame} The video frame.
  46153. */
  46154. _getDefaultVideoFrame() {
  46155. let defaultVideoFrame = this.defaultVideoFrame;
  46156. if ( defaultVideoFrame === null ) {
  46157. const init = {
  46158. timestamp: 0,
  46159. codedWidth: 1,
  46160. codedHeight: 1,
  46161. format: 'RGBA',
  46162. };
  46163. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  46164. }
  46165. return defaultVideoFrame;
  46166. }
  46167. /**
  46168. * Uploads cube texture image data to the GPU memory.
  46169. *
  46170. * @private
  46171. * @param {Array} images - The cube image data.
  46172. * @param {GPUTexture} textureGPU - The GPU texture.
  46173. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46174. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  46175. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  46176. */
  46177. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY, premultiplyAlpha ) {
  46178. for ( let i = 0; i < 6; i ++ ) {
  46179. const image = images[ i ];
  46180. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  46181. if ( image.isDataTexture ) {
  46182. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  46183. } else {
  46184. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY, premultiplyAlpha );
  46185. }
  46186. }
  46187. }
  46188. /**
  46189. * Uploads texture image data to the GPU memory.
  46190. *
  46191. * @private
  46192. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  46193. * @param {GPUTexture} textureGPU - The GPU texture.
  46194. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46195. * @param {number} originDepth - The origin depth.
  46196. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  46197. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  46198. */
  46199. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha ) {
  46200. const device = this.backend.device;
  46201. device.queue.copyExternalImageToTexture(
  46202. {
  46203. source: image,
  46204. flipY: flipY
  46205. }, {
  46206. texture: textureGPU,
  46207. mipLevel: 0,
  46208. origin: { x: 0, y: 0, z: originDepth },
  46209. premultipliedAlpha: premultiplyAlpha
  46210. }, {
  46211. width: image.width,
  46212. height: image.height,
  46213. depthOrArrayLayers: 1
  46214. }
  46215. );
  46216. }
  46217. /**
  46218. * Returns the pass utils singleton.
  46219. *
  46220. * @private
  46221. * @return {WebGPUTexturePassUtils} The utils instance.
  46222. */
  46223. _getPassUtils() {
  46224. let passUtils = this._passUtils;
  46225. if ( passUtils === null ) {
  46226. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  46227. }
  46228. return passUtils;
  46229. }
  46230. /**
  46231. * Generates mipmaps for the given GPU texture.
  46232. *
  46233. * @private
  46234. * @param {GPUTexture} textureGPU - The GPU texture object.
  46235. * @param {Object} textureDescriptorGPU - The texture descriptor.
  46236. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  46237. */
  46238. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  46239. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  46240. }
  46241. /**
  46242. * Flip the contents of the given GPU texture along its vertical axis.
  46243. *
  46244. * @private
  46245. * @param {GPUTexture} textureGPU - The GPU texture object.
  46246. * @param {Object} textureDescriptorGPU - The texture descriptor.
  46247. * @param {number} [originDepth=0] - The origin depth.
  46248. */
  46249. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  46250. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  46251. }
  46252. /**
  46253. * Uploads texture buffer data to the GPU memory.
  46254. *
  46255. * @private
  46256. * @param {Object} image - An object defining the image buffer data.
  46257. * @param {GPUTexture} textureGPU - The GPU texture.
  46258. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46259. * @param {number} originDepth - The origin depth.
  46260. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  46261. * @param {number} [depth=0] - TODO.
  46262. */
  46263. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  46264. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  46265. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  46266. const device = this.backend.device;
  46267. const data = image.data;
  46268. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  46269. const bytesPerRow = image.width * bytesPerTexel;
  46270. device.queue.writeTexture(
  46271. {
  46272. texture: textureGPU,
  46273. mipLevel: 0,
  46274. origin: { x: 0, y: 0, z: originDepth }
  46275. },
  46276. data,
  46277. {
  46278. offset: image.width * image.height * bytesPerTexel * depth,
  46279. bytesPerRow
  46280. },
  46281. {
  46282. width: image.width,
  46283. height: image.height,
  46284. depthOrArrayLayers: 1
  46285. } );
  46286. if ( flipY === true ) {
  46287. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  46288. }
  46289. }
  46290. /**
  46291. * Uploads compressed texture data to the GPU memory.
  46292. *
  46293. * @private
  46294. * @param {Array<Object>} mipmaps - An array with mipmap data.
  46295. * @param {GPUTexture} textureGPU - The GPU texture.
  46296. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46297. */
  46298. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  46299. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  46300. const device = this.backend.device;
  46301. const blockData = this._getBlockData( textureDescriptorGPU.format );
  46302. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  46303. for ( let i = 0; i < mipmaps.length; i ++ ) {
  46304. const mipmap = mipmaps[ i ];
  46305. const width = mipmap.width;
  46306. const height = mipmap.height;
  46307. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  46308. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  46309. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  46310. for ( let j = 0; j < depth; j ++ ) {
  46311. device.queue.writeTexture(
  46312. {
  46313. texture: textureGPU,
  46314. mipLevel: i,
  46315. origin: { x: 0, y: 0, z: j }
  46316. },
  46317. mipmap.data,
  46318. {
  46319. offset: j * bytesPerImage,
  46320. bytesPerRow,
  46321. rowsPerImage: Math.ceil( height / blockData.height )
  46322. },
  46323. {
  46324. width: Math.ceil( width / blockData.width ) * blockData.width,
  46325. height: Math.ceil( height / blockData.height ) * blockData.height,
  46326. depthOrArrayLayers: 1
  46327. }
  46328. );
  46329. }
  46330. }
  46331. }
  46332. /**
  46333. * This method is only relevant for compressed texture formats. It returns a block
  46334. * data descriptor for the given GPU compressed texture format.
  46335. *
  46336. * @private
  46337. * @param {string} format - The GPU compressed texture format.
  46338. * @return {Object} The block data descriptor.
  46339. */
  46340. _getBlockData( format ) {
  46341. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  46342. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  46343. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  46344. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  46345. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  46346. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  46347. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  46348. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  46349. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  46350. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  46351. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  46352. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  46353. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  46354. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  46355. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  46356. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  46357. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  46358. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  46359. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  46360. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  46361. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  46362. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  46363. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  46364. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  46365. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  46366. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  46367. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  46368. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  46369. }
  46370. /**
  46371. * Converts the three.js uv wrapping constants to GPU address mode constants.
  46372. *
  46373. * @private
  46374. * @param {number} value - The three.js constant defining a uv wrapping mode.
  46375. * @return {string} The GPU address mode.
  46376. */
  46377. _convertAddressMode( value ) {
  46378. let addressMode = GPUAddressMode.ClampToEdge;
  46379. if ( value === RepeatWrapping ) {
  46380. addressMode = GPUAddressMode.Repeat;
  46381. } else if ( value === MirroredRepeatWrapping ) {
  46382. addressMode = GPUAddressMode.MirrorRepeat;
  46383. }
  46384. return addressMode;
  46385. }
  46386. /**
  46387. * Converts the three.js filter constants to GPU filter constants.
  46388. *
  46389. * @private
  46390. * @param {number} value - The three.js constant defining a filter mode.
  46391. * @return {string} The GPU filter mode.
  46392. */
  46393. _convertFilterMode( value ) {
  46394. let filterMode = GPUFilterMode.Linear;
  46395. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  46396. filterMode = GPUFilterMode.Nearest;
  46397. }
  46398. return filterMode;
  46399. }
  46400. /**
  46401. * Returns the bytes-per-texel value for the given GPU texture format.
  46402. *
  46403. * @private
  46404. * @param {string} format - The GPU texture format.
  46405. * @return {number} The bytes-per-texel.
  46406. */
  46407. _getBytesPerTexel( format ) {
  46408. // 8-bit formats
  46409. if ( format === GPUTextureFormat.R8Unorm ||
  46410. format === GPUTextureFormat.R8Snorm ||
  46411. format === GPUTextureFormat.R8Uint ||
  46412. format === GPUTextureFormat.R8Sint ) return 1;
  46413. // 16-bit formats
  46414. if ( format === GPUTextureFormat.R16Uint ||
  46415. format === GPUTextureFormat.R16Sint ||
  46416. format === GPUTextureFormat.R16Float ||
  46417. format === GPUTextureFormat.RG8Unorm ||
  46418. format === GPUTextureFormat.RG8Snorm ||
  46419. format === GPUTextureFormat.RG8Uint ||
  46420. format === GPUTextureFormat.RG8Sint ) return 2;
  46421. // 32-bit formats
  46422. if ( format === GPUTextureFormat.R32Uint ||
  46423. format === GPUTextureFormat.R32Sint ||
  46424. format === GPUTextureFormat.R32Float ||
  46425. format === GPUTextureFormat.RG16Uint ||
  46426. format === GPUTextureFormat.RG16Sint ||
  46427. format === GPUTextureFormat.RG16Float ||
  46428. format === GPUTextureFormat.RGBA8Unorm ||
  46429. format === GPUTextureFormat.RGBA8UnormSRGB ||
  46430. format === GPUTextureFormat.RGBA8Snorm ||
  46431. format === GPUTextureFormat.RGBA8Uint ||
  46432. format === GPUTextureFormat.RGBA8Sint ||
  46433. format === GPUTextureFormat.BGRA8Unorm ||
  46434. format === GPUTextureFormat.BGRA8UnormSRGB ||
  46435. // Packed 32-bit formats
  46436. format === GPUTextureFormat.RGB9E5UFloat ||
  46437. format === GPUTextureFormat.RGB10A2Unorm ||
  46438. format === GPUTextureFormat.RG11B10UFloat ||
  46439. format === GPUTextureFormat.Depth32Float ||
  46440. format === GPUTextureFormat.Depth24Plus ||
  46441. format === GPUTextureFormat.Depth24PlusStencil8 ||
  46442. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  46443. // 64-bit formats
  46444. if ( format === GPUTextureFormat.RG32Uint ||
  46445. format === GPUTextureFormat.RG32Sint ||
  46446. format === GPUTextureFormat.RG32Float ||
  46447. format === GPUTextureFormat.RGBA16Uint ||
  46448. format === GPUTextureFormat.RGBA16Sint ||
  46449. format === GPUTextureFormat.RGBA16Float ) return 8;
  46450. // 128-bit formats
  46451. if ( format === GPUTextureFormat.RGBA32Uint ||
  46452. format === GPUTextureFormat.RGBA32Sint ||
  46453. format === GPUTextureFormat.RGBA32Float ) return 16;
  46454. }
  46455. /**
  46456. * Returns the corresponding typed array type for the given GPU texture format.
  46457. *
  46458. * @private
  46459. * @param {string} format - The GPU texture format.
  46460. * @return {TypedArray.constructor} The typed array type.
  46461. */
  46462. _getTypedArrayType( format ) {
  46463. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  46464. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  46465. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  46466. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  46467. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  46468. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  46469. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  46470. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  46471. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  46472. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  46473. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  46474. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  46475. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  46476. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  46477. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  46478. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  46479. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  46480. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  46481. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  46482. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  46483. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  46484. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  46485. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  46486. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  46487. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  46488. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  46489. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  46490. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  46491. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  46492. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  46493. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  46494. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  46495. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  46496. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  46497. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  46498. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  46499. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  46500. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  46501. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  46502. }
  46503. /**
  46504. * Returns the GPU dimensions for the given texture.
  46505. *
  46506. * @private
  46507. * @param {Texture} texture - The texture.
  46508. * @return {string} The GPU dimension.
  46509. */
  46510. _getDimension( texture ) {
  46511. let dimension;
  46512. if ( texture.isData3DTexture ) {
  46513. dimension = GPUTextureDimension.ThreeD;
  46514. } else {
  46515. dimension = GPUTextureDimension.TwoD;
  46516. }
  46517. return dimension;
  46518. }
  46519. }
  46520. /**
  46521. * Returns the GPU format for the given texture.
  46522. *
  46523. * @param {Texture} texture - The texture.
  46524. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  46525. * It is not necessary to apply the device for most formats.
  46526. * @return {string} The GPU format.
  46527. */
  46528. function getFormat( texture, device = null ) {
  46529. const format = texture.format;
  46530. const type = texture.type;
  46531. const colorSpace = texture.colorSpace;
  46532. const transfer = ColorManagement.getTransfer( colorSpace );
  46533. let formatGPU;
  46534. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  46535. switch ( format ) {
  46536. case RGBA_S3TC_DXT1_Format:
  46537. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  46538. break;
  46539. case RGBA_S3TC_DXT3_Format:
  46540. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  46541. break;
  46542. case RGBA_S3TC_DXT5_Format:
  46543. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  46544. break;
  46545. case RGB_ETC2_Format:
  46546. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  46547. break;
  46548. case RGBA_ETC2_EAC_Format:
  46549. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  46550. break;
  46551. case RGBA_ASTC_4x4_Format:
  46552. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  46553. break;
  46554. case RGBA_ASTC_5x4_Format:
  46555. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  46556. break;
  46557. case RGBA_ASTC_5x5_Format:
  46558. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  46559. break;
  46560. case RGBA_ASTC_6x5_Format:
  46561. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  46562. break;
  46563. case RGBA_ASTC_6x6_Format:
  46564. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  46565. break;
  46566. case RGBA_ASTC_8x5_Format:
  46567. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  46568. break;
  46569. case RGBA_ASTC_8x6_Format:
  46570. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  46571. break;
  46572. case RGBA_ASTC_8x8_Format:
  46573. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  46574. break;
  46575. case RGBA_ASTC_10x5_Format:
  46576. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  46577. break;
  46578. case RGBA_ASTC_10x6_Format:
  46579. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  46580. break;
  46581. case RGBA_ASTC_10x8_Format:
  46582. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  46583. break;
  46584. case RGBA_ASTC_10x10_Format:
  46585. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  46586. break;
  46587. case RGBA_ASTC_12x10_Format:
  46588. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  46589. break;
  46590. case RGBA_ASTC_12x12_Format:
  46591. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  46592. break;
  46593. case RGBAFormat:
  46594. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  46595. break;
  46596. default:
  46597. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  46598. }
  46599. } else {
  46600. switch ( format ) {
  46601. case RGBAFormat:
  46602. switch ( type ) {
  46603. case ByteType:
  46604. formatGPU = GPUTextureFormat.RGBA8Snorm;
  46605. break;
  46606. case ShortType:
  46607. formatGPU = GPUTextureFormat.RGBA16Sint;
  46608. break;
  46609. case UnsignedShortType:
  46610. formatGPU = GPUTextureFormat.RGBA16Uint;
  46611. break;
  46612. case UnsignedIntType:
  46613. formatGPU = GPUTextureFormat.RGBA32Uint;
  46614. break;
  46615. case IntType:
  46616. formatGPU = GPUTextureFormat.RGBA32Sint;
  46617. break;
  46618. case UnsignedByteType:
  46619. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  46620. break;
  46621. case HalfFloatType:
  46622. formatGPU = GPUTextureFormat.RGBA16Float;
  46623. break;
  46624. case FloatType:
  46625. formatGPU = GPUTextureFormat.RGBA32Float;
  46626. break;
  46627. default:
  46628. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  46629. }
  46630. break;
  46631. case RGBFormat:
  46632. switch ( type ) {
  46633. case UnsignedInt5999Type:
  46634. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  46635. break;
  46636. default:
  46637. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  46638. }
  46639. break;
  46640. case RedFormat:
  46641. switch ( type ) {
  46642. case ByteType:
  46643. formatGPU = GPUTextureFormat.R8Snorm;
  46644. break;
  46645. case ShortType:
  46646. formatGPU = GPUTextureFormat.R16Sint;
  46647. break;
  46648. case UnsignedShortType:
  46649. formatGPU = GPUTextureFormat.R16Uint;
  46650. break;
  46651. case UnsignedIntType:
  46652. formatGPU = GPUTextureFormat.R32Uint;
  46653. break;
  46654. case IntType:
  46655. formatGPU = GPUTextureFormat.R32Sint;
  46656. break;
  46657. case UnsignedByteType:
  46658. formatGPU = GPUTextureFormat.R8Unorm;
  46659. break;
  46660. case HalfFloatType:
  46661. formatGPU = GPUTextureFormat.R16Float;
  46662. break;
  46663. case FloatType:
  46664. formatGPU = GPUTextureFormat.R32Float;
  46665. break;
  46666. default:
  46667. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  46668. }
  46669. break;
  46670. case RGFormat:
  46671. switch ( type ) {
  46672. case ByteType:
  46673. formatGPU = GPUTextureFormat.RG8Snorm;
  46674. break;
  46675. case ShortType:
  46676. formatGPU = GPUTextureFormat.RG16Sint;
  46677. break;
  46678. case UnsignedShortType:
  46679. formatGPU = GPUTextureFormat.RG16Uint;
  46680. break;
  46681. case UnsignedIntType:
  46682. formatGPU = GPUTextureFormat.RG32Uint;
  46683. break;
  46684. case IntType:
  46685. formatGPU = GPUTextureFormat.RG32Sint;
  46686. break;
  46687. case UnsignedByteType:
  46688. formatGPU = GPUTextureFormat.RG8Unorm;
  46689. break;
  46690. case HalfFloatType:
  46691. formatGPU = GPUTextureFormat.RG16Float;
  46692. break;
  46693. case FloatType:
  46694. formatGPU = GPUTextureFormat.RG32Float;
  46695. break;
  46696. default:
  46697. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  46698. }
  46699. break;
  46700. case DepthFormat:
  46701. switch ( type ) {
  46702. case UnsignedShortType:
  46703. formatGPU = GPUTextureFormat.Depth16Unorm;
  46704. break;
  46705. case UnsignedIntType:
  46706. formatGPU = GPUTextureFormat.Depth24Plus;
  46707. break;
  46708. case FloatType:
  46709. formatGPU = GPUTextureFormat.Depth32Float;
  46710. break;
  46711. default:
  46712. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  46713. }
  46714. break;
  46715. case DepthStencilFormat:
  46716. switch ( type ) {
  46717. case UnsignedInt248Type:
  46718. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  46719. break;
  46720. case FloatType:
  46721. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  46722. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  46723. }
  46724. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  46725. break;
  46726. default:
  46727. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  46728. }
  46729. break;
  46730. case RedIntegerFormat:
  46731. switch ( type ) {
  46732. case IntType:
  46733. formatGPU = GPUTextureFormat.R32Sint;
  46734. break;
  46735. case UnsignedIntType:
  46736. formatGPU = GPUTextureFormat.R32Uint;
  46737. break;
  46738. default:
  46739. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  46740. }
  46741. break;
  46742. case RGIntegerFormat:
  46743. switch ( type ) {
  46744. case IntType:
  46745. formatGPU = GPUTextureFormat.RG32Sint;
  46746. break;
  46747. case UnsignedIntType:
  46748. formatGPU = GPUTextureFormat.RG32Uint;
  46749. break;
  46750. default:
  46751. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  46752. }
  46753. break;
  46754. case RGBAIntegerFormat:
  46755. switch ( type ) {
  46756. case IntType:
  46757. formatGPU = GPUTextureFormat.RGBA32Sint;
  46758. break;
  46759. case UnsignedIntType:
  46760. formatGPU = GPUTextureFormat.RGBA32Uint;
  46761. break;
  46762. default:
  46763. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  46764. }
  46765. break;
  46766. default:
  46767. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  46768. }
  46769. }
  46770. return formatGPU;
  46771. }
  46772. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  46773. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  46774. const wgslTypeLib$1 = {
  46775. 'f32': 'float',
  46776. 'i32': 'int',
  46777. 'u32': 'uint',
  46778. 'bool': 'bool',
  46779. 'vec2<f32>': 'vec2',
  46780. 'vec2<i32>': 'ivec2',
  46781. 'vec2<u32>': 'uvec2',
  46782. 'vec2<bool>': 'bvec2',
  46783. 'vec2f': 'vec2',
  46784. 'vec2i': 'ivec2',
  46785. 'vec2u': 'uvec2',
  46786. 'vec2b': 'bvec2',
  46787. 'vec3<f32>': 'vec3',
  46788. 'vec3<i32>': 'ivec3',
  46789. 'vec3<u32>': 'uvec3',
  46790. 'vec3<bool>': 'bvec3',
  46791. 'vec3f': 'vec3',
  46792. 'vec3i': 'ivec3',
  46793. 'vec3u': 'uvec3',
  46794. 'vec3b': 'bvec3',
  46795. 'vec4<f32>': 'vec4',
  46796. 'vec4<i32>': 'ivec4',
  46797. 'vec4<u32>': 'uvec4',
  46798. 'vec4<bool>': 'bvec4',
  46799. 'vec4f': 'vec4',
  46800. 'vec4i': 'ivec4',
  46801. 'vec4u': 'uvec4',
  46802. 'vec4b': 'bvec4',
  46803. 'mat2x2<f32>': 'mat2',
  46804. 'mat2x2f': 'mat2',
  46805. 'mat3x3<f32>': 'mat3',
  46806. 'mat3x3f': 'mat3',
  46807. 'mat4x4<f32>': 'mat4',
  46808. 'mat4x4f': 'mat4',
  46809. 'sampler': 'sampler',
  46810. 'texture_1d': 'texture',
  46811. 'texture_2d': 'texture',
  46812. 'texture_2d_array': 'texture',
  46813. 'texture_multisampled_2d': 'cubeTexture',
  46814. 'texture_depth_2d': 'depthTexture',
  46815. 'texture_depth_2d_array': 'depthTexture',
  46816. 'texture_depth_multisampled_2d': 'depthTexture',
  46817. 'texture_depth_cube': 'depthTexture',
  46818. 'texture_depth_cube_array': 'depthTexture',
  46819. 'texture_3d': 'texture3D',
  46820. 'texture_cube': 'cubeTexture',
  46821. 'texture_cube_array': 'cubeTexture',
  46822. 'texture_storage_1d': 'storageTexture',
  46823. 'texture_storage_2d': 'storageTexture',
  46824. 'texture_storage_2d_array': 'storageTexture',
  46825. 'texture_storage_3d': 'storageTexture'
  46826. };
  46827. const parse = ( source ) => {
  46828. source = source.trim();
  46829. const declaration = source.match( declarationRegexp );
  46830. if ( declaration !== null && declaration.length === 4 ) {
  46831. const inputsCode = declaration[ 2 ];
  46832. const propsMatches = [];
  46833. let match = null;
  46834. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  46835. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  46836. }
  46837. // Process matches to correctly pair names and types
  46838. const inputs = [];
  46839. for ( let i = 0; i < propsMatches.length; i ++ ) {
  46840. const { name, type } = propsMatches[ i ];
  46841. let resolvedType = type;
  46842. if ( resolvedType.startsWith( 'ptr' ) ) {
  46843. resolvedType = 'pointer';
  46844. } else {
  46845. if ( resolvedType.startsWith( 'texture' ) ) {
  46846. resolvedType = type.split( '<' )[ 0 ];
  46847. }
  46848. resolvedType = wgslTypeLib$1[ resolvedType ];
  46849. }
  46850. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  46851. }
  46852. const blockCode = source.substring( declaration[ 0 ].length );
  46853. const outputType = declaration[ 3 ] || 'void';
  46854. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  46855. const type = wgslTypeLib$1[ outputType ] || outputType;
  46856. return {
  46857. type,
  46858. inputs,
  46859. name,
  46860. inputsCode,
  46861. blockCode,
  46862. outputType
  46863. };
  46864. } else {
  46865. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  46866. }
  46867. };
  46868. /**
  46869. * This class represents a WSL node function.
  46870. *
  46871. * @augments NodeFunction
  46872. */
  46873. class WGSLNodeFunction extends NodeFunction {
  46874. /**
  46875. * Constructs a new WGSL node function.
  46876. *
  46877. * @param {string} source - The WGSL source.
  46878. */
  46879. constructor( source ) {
  46880. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  46881. super( type, inputs, name );
  46882. this.inputsCode = inputsCode;
  46883. this.blockCode = blockCode;
  46884. this.outputType = outputType;
  46885. }
  46886. /**
  46887. * This method returns the WGSL code of the node function.
  46888. *
  46889. * @param {string} [name=this.name] - The function's name.
  46890. * @return {string} The shader code.
  46891. */
  46892. getCode( name = this.name ) {
  46893. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  46894. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  46895. }
  46896. }
  46897. /**
  46898. * A WGSL node parser.
  46899. *
  46900. * @augments NodeParser
  46901. */
  46902. class WGSLNodeParser extends NodeParser {
  46903. /**
  46904. * The method parses the given WGSL code an returns a node function.
  46905. *
  46906. * @param {string} source - The WGSL code.
  46907. * @return {WGSLNodeFunction} A node function.
  46908. */
  46909. parseFunction( source ) {
  46910. return new WGSLNodeFunction( source );
  46911. }
  46912. }
  46913. // GPUShaderStage is not defined in browsers not supporting WebGPU
  46914. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  46915. const accessNames = {
  46916. [ NodeAccess.READ_ONLY ]: 'read',
  46917. [ NodeAccess.WRITE_ONLY ]: 'write',
  46918. [ NodeAccess.READ_WRITE ]: 'read_write'
  46919. };
  46920. const wrapNames = {
  46921. [ RepeatWrapping ]: 'repeat',
  46922. [ ClampToEdgeWrapping ]: 'clamp',
  46923. [ MirroredRepeatWrapping ]: 'mirror'
  46924. };
  46925. const gpuShaderStageLib = {
  46926. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  46927. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  46928. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  46929. };
  46930. const supports = {
  46931. instance: true,
  46932. swizzleAssign: false,
  46933. storageBuffer: true
  46934. };
  46935. const wgslFnOpLib = {
  46936. '^^': 'tsl_xor'
  46937. };
  46938. const wgslTypeLib = {
  46939. float: 'f32',
  46940. int: 'i32',
  46941. uint: 'u32',
  46942. bool: 'bool',
  46943. color: 'vec3<f32>',
  46944. vec2: 'vec2<f32>',
  46945. ivec2: 'vec2<i32>',
  46946. uvec2: 'vec2<u32>',
  46947. bvec2: 'vec2<bool>',
  46948. vec3: 'vec3<f32>',
  46949. ivec3: 'vec3<i32>',
  46950. uvec3: 'vec3<u32>',
  46951. bvec3: 'vec3<bool>',
  46952. vec4: 'vec4<f32>',
  46953. ivec4: 'vec4<i32>',
  46954. uvec4: 'vec4<u32>',
  46955. bvec4: 'vec4<bool>',
  46956. mat2: 'mat2x2<f32>',
  46957. mat3: 'mat3x3<f32>',
  46958. mat4: 'mat4x4<f32>'
  46959. };
  46960. const wgslCodeCache = {};
  46961. const wgslPolyfill = {
  46962. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  46963. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  46964. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  46965. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  46966. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  46967. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  46968. equals_bvec2: new CodeNode( 'fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }' ),
  46969. equals_bvec3: new CodeNode( 'fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }' ),
  46970. equals_bvec4: new CodeNode( 'fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }' ),
  46971. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  46972. mirrorWrapping_float: new CodeNode( 'fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }' ),
  46973. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  46974. biquadraticTexture: new CodeNode( /* wgsl */`
  46975. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  46976. let res = vec2f( iRes );
  46977. let uvScaled = coord * res;
  46978. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  46979. // https://www.shadertoy.com/view/WtyXRy
  46980. let uv = uvWrapping - 0.5;
  46981. let iuv = floor( uv );
  46982. let f = fract( uv );
  46983. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  46984. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  46985. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  46986. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  46987. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  46988. }
  46989. ` )
  46990. };
  46991. const wgslMethods = {
  46992. dFdx: 'dpdx',
  46993. dFdy: '- dpdy',
  46994. mod_float: 'tsl_mod_float',
  46995. mod_vec2: 'tsl_mod_vec2',
  46996. mod_vec3: 'tsl_mod_vec3',
  46997. mod_vec4: 'tsl_mod_vec4',
  46998. equals_bool: 'tsl_equals_bool',
  46999. equals_bvec2: 'tsl_equals_bvec2',
  47000. equals_bvec3: 'tsl_equals_bvec3',
  47001. equals_bvec4: 'tsl_equals_bvec4',
  47002. inversesqrt: 'inverseSqrt',
  47003. bitcast: 'bitcast<f32>'
  47004. };
  47005. // WebGPU issue: does not support pow() with negative base on Windows
  47006. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  47007. wgslPolyfill.pow_float = new CodeNode( 'fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }' );
  47008. wgslPolyfill.pow_vec2 = new CodeNode( 'fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }', [ wgslPolyfill.pow_float ] );
  47009. wgslPolyfill.pow_vec3 = new CodeNode( 'fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }', [ wgslPolyfill.pow_float ] );
  47010. wgslPolyfill.pow_vec4 = new CodeNode( 'fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }', [ wgslPolyfill.pow_float ] );
  47011. wgslMethods.pow_float = 'tsl_pow_float';
  47012. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  47013. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  47014. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  47015. }
  47016. //
  47017. let diagnostics = '';
  47018. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  47019. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  47020. }
  47021. /**
  47022. * A node builder targeting WGSL.
  47023. *
  47024. * This module generates WGSL shader code from node materials and also
  47025. * generates the respective bindings and vertex buffer definitions. These
  47026. * data are later used by the renderer to create render and compute pipelines
  47027. * for render objects.
  47028. *
  47029. * @augments NodeBuilder
  47030. */
  47031. class WGSLNodeBuilder extends NodeBuilder {
  47032. /**
  47033. * Constructs a new WGSL node builder renderer.
  47034. *
  47035. * @param {Object3D} object - The 3D object.
  47036. * @param {Renderer} renderer - The renderer.
  47037. */
  47038. constructor( object, renderer ) {
  47039. super( object, renderer, new WGSLNodeParser() );
  47040. /**
  47041. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  47042. * another dictionary which manages UBOs per group ('render','frame','object').
  47043. *
  47044. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  47045. */
  47046. this.uniformGroups = {};
  47047. /**
  47048. * A dictionary that holds for each shader stage a Map of builtins.
  47049. *
  47050. * @type {Object<string,Map<string,Object>>}
  47051. */
  47052. this.builtins = {};
  47053. /**
  47054. * A dictionary that holds for each shader stage a Set of directives.
  47055. *
  47056. * @type {Object<string,Set<string>>}
  47057. */
  47058. this.directives = {};
  47059. /**
  47060. * A map for managing scope arrays. Only relevant for when using
  47061. * {@link WorkgroupInfoNode} in context of compute shaders.
  47062. *
  47063. * @type {Map<string,Object>}
  47064. */
  47065. this.scopedArrays = new Map();
  47066. }
  47067. /**
  47068. * Checks if the given texture requires a manual conversion to the working color space.
  47069. *
  47070. * @param {Texture} texture - The texture to check.
  47071. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  47072. */
  47073. needsToWorkingColorSpace( texture ) {
  47074. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  47075. }
  47076. /**
  47077. * Generates the WGSL snippet for sampled textures.
  47078. *
  47079. * @private
  47080. * @param {Texture} texture - The texture.
  47081. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47082. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47083. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47084. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47085. * @return {string} The WGSL snippet.
  47086. */
  47087. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47088. if ( shaderStage === 'fragment' ) {
  47089. if ( depthSnippet ) {
  47090. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  47091. } else {
  47092. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  47093. }
  47094. } else {
  47095. return this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  47096. }
  47097. }
  47098. /**
  47099. * Generates the WGSL snippet when sampling video textures.
  47100. *
  47101. * @private
  47102. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  47103. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47104. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47105. * @return {string} The WGSL snippet.
  47106. */
  47107. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  47108. if ( shaderStage === 'fragment' ) {
  47109. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  47110. } else {
  47111. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  47112. }
  47113. }
  47114. /**
  47115. * Generates the WGSL snippet when sampling textures with explicit mip level.
  47116. *
  47117. * @private
  47118. * @param {Texture} texture - The texture.
  47119. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47120. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47121. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47122. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47123. * @return {string} The WGSL snippet.
  47124. */
  47125. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet ) {
  47126. if ( this.isUnfilterable( texture ) === false ) {
  47127. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  47128. } else if ( this.isFilteredTexture( texture ) ) {
  47129. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  47130. } else {
  47131. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  47132. }
  47133. }
  47134. /**
  47135. * Generates a wrap function used in context of textures.
  47136. *
  47137. * @param {Texture} texture - The texture to generate the function for.
  47138. * @return {string} The name of the generated function.
  47139. */
  47140. generateWrapFunction( texture ) {
  47141. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  47142. let nodeCode = wgslCodeCache[ functionName ];
  47143. if ( nodeCode === undefined ) {
  47144. const includes = [];
  47145. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  47146. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  47147. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  47148. const addWrapSnippet = ( wrap, axis ) => {
  47149. if ( wrap === RepeatWrapping ) {
  47150. includes.push( wgslPolyfill.repeatWrapping_float );
  47151. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  47152. } else if ( wrap === ClampToEdgeWrapping ) {
  47153. includes.push( wgslPolyfill.clampWrapping_float );
  47154. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  47155. } else if ( wrap === MirroredRepeatWrapping ) {
  47156. includes.push( wgslPolyfill.mirrorWrapping_float );
  47157. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  47158. } else {
  47159. code += `\t\tcoord.${ axis }`;
  47160. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  47161. }
  47162. };
  47163. addWrapSnippet( texture.wrapS, 'x' );
  47164. code += ',\n';
  47165. addWrapSnippet( texture.wrapT, 'y' );
  47166. if ( texture.isData3DTexture ) {
  47167. code += ',\n';
  47168. addWrapSnippet( texture.wrapR, 'z' );
  47169. }
  47170. code += '\n\t);\n\n}\n';
  47171. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  47172. }
  47173. nodeCode.build( this );
  47174. return functionName;
  47175. }
  47176. /**
  47177. * Generates the array declaration string.
  47178. *
  47179. * @param {string} type - The type.
  47180. * @param {?number} [count] - The count.
  47181. * @return {string} The generated value as a shader string.
  47182. */
  47183. generateArrayDeclaration( type, count ) {
  47184. return `array< ${ this.getType( type ) }, ${ count } >`;
  47185. }
  47186. /**
  47187. * Generates a WGSL variable that holds the texture dimension of the given texture.
  47188. * It also returns information about the number of layers (elements) of an arrayed
  47189. * texture as well as the cube face count of cube textures.
  47190. *
  47191. * @param {Texture} texture - The texture to generate the function for.
  47192. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  47193. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47194. * @return {string} The name of the dimension variable.
  47195. */
  47196. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  47197. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  47198. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  47199. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  47200. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  47201. let textureDimensionsParams;
  47202. let dimensionType;
  47203. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  47204. const isMultisampled = primarySamples > 1;
  47205. if ( texture.isData3DTexture ) {
  47206. dimensionType = 'vec3<u32>';
  47207. } else {
  47208. // Regular 2D textures, depth textures, etc.
  47209. dimensionType = 'vec2<u32>';
  47210. }
  47211. // Build parameters string based on texture type and multisampling
  47212. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  47213. textureDimensionsParams = textureProperty;
  47214. } else {
  47215. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  47216. }
  47217. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  47218. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  47219. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  47220. textureData.arrayLayerCount = new VarNode(
  47221. new ExpressionNode(
  47222. `textureNumLayers(${textureProperty})`,
  47223. 'u32'
  47224. )
  47225. );
  47226. }
  47227. // For cube textures, we know it's always 6 faces
  47228. if ( texture.isTextureCube ) {
  47229. textureData.cubeFaceCount = new VarNode(
  47230. new ExpressionNode( '6u', 'u32' )
  47231. );
  47232. }
  47233. }
  47234. return textureDimensionNode.build( this );
  47235. }
  47236. /**
  47237. * Generates the WGSL snippet for a manual filtered texture.
  47238. *
  47239. * @param {Texture} texture - The texture.
  47240. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47241. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47242. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47243. * @return {string} The WGSL snippet.
  47244. */
  47245. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  47246. this._include( 'biquadraticTexture' );
  47247. const wrapFunction = this.generateWrapFunction( texture );
  47248. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  47249. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  47250. }
  47251. /**
  47252. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  47253. * Since it's a lookup, no sampling or filtering is applied.
  47254. *
  47255. * @param {Texture} texture - The texture.
  47256. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47257. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47258. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47259. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47260. * @return {string} The WGSL snippet.
  47261. */
  47262. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  47263. const wrapFunction = this.generateWrapFunction( texture );
  47264. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  47265. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  47266. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  47267. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  47268. }
  47269. /**
  47270. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  47271. *
  47272. * @param {Texture} texture - The texture.
  47273. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47274. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47275. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47276. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47277. * @return {string} The WGSL snippet.
  47278. */
  47279. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  47280. let snippet;
  47281. if ( texture.isVideoTexture === true ) {
  47282. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  47283. } else if ( depthSnippet ) {
  47284. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  47285. } else {
  47286. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  47287. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  47288. snippet += '.x';
  47289. }
  47290. }
  47291. return snippet;
  47292. }
  47293. /**
  47294. * Generates the WGSL snippet that writes a single texel to a texture.
  47295. *
  47296. * @param {Texture} texture - The texture.
  47297. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47298. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47299. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47300. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  47301. * @return {string} The WGSL snippet.
  47302. */
  47303. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  47304. let snippet;
  47305. if ( depthSnippet ) {
  47306. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  47307. } else {
  47308. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  47309. }
  47310. return snippet;
  47311. }
  47312. /**
  47313. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  47314. *
  47315. * @param {Texture} texture - The texture.
  47316. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  47317. */
  47318. isSampleCompare( texture ) {
  47319. return texture.isDepthTexture === true && texture.compareFunction !== null;
  47320. }
  47321. /**
  47322. * Returns `true` if the given texture is unfilterable.
  47323. *
  47324. * @param {Texture} texture - The texture.
  47325. * @return {boolean} Whether the given texture is unfilterable or not.
  47326. */
  47327. isUnfilterable( texture ) {
  47328. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  47329. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  47330. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  47331. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  47332. }
  47333. /**
  47334. * Generates the WGSL snippet for sampling/loading the given texture.
  47335. *
  47336. * @param {Texture} texture - The texture.
  47337. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47338. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47339. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47340. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47341. * @return {string} The WGSL snippet.
  47342. */
  47343. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47344. let snippet = null;
  47345. if ( texture.isVideoTexture === true ) {
  47346. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  47347. } else if ( this.isUnfilterable( texture ) ) {
  47348. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  47349. } else {
  47350. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  47351. }
  47352. return snippet;
  47353. }
  47354. /**
  47355. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  47356. *
  47357. * @param {Texture} texture - The texture.
  47358. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47359. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47360. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  47361. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47362. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47363. * @return {string} The WGSL snippet.
  47364. */
  47365. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47366. if ( shaderStage === 'fragment' ) {
  47367. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  47368. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  47369. } else {
  47370. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  47371. }
  47372. }
  47373. /**
  47374. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  47375. * against a reference value.
  47376. *
  47377. * @param {Texture} texture - The texture.
  47378. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47379. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47380. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  47381. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47382. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47383. * @return {string} The WGSL snippet.
  47384. */
  47385. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47386. if ( shaderStage === 'fragment' ) {
  47387. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  47388. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  47389. }
  47390. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  47391. } else {
  47392. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  47393. }
  47394. }
  47395. /**
  47396. * Generates the WGSL snippet when sampling textures with explicit mip level.
  47397. *
  47398. * @param {Texture} texture - The texture.
  47399. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47400. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47401. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47402. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47403. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47404. * @return {string} The WGSL snippet.
  47405. */
  47406. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47407. let snippet = null;
  47408. if ( texture.isVideoTexture === true ) {
  47409. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  47410. } else {
  47411. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  47412. }
  47413. return snippet;
  47414. }
  47415. /**
  47416. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  47417. *
  47418. * @param {Texture} texture - The texture.
  47419. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47420. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47421. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  47422. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47423. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47424. * @return {string} The WGSL snippet.
  47425. */
  47426. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47427. if ( shaderStage === 'fragment' ) {
  47428. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  47429. } else {
  47430. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  47431. }
  47432. }
  47433. /**
  47434. * Returns a WGSL snippet that represents the property name of the given node.
  47435. *
  47436. * @param {Node} node - The node.
  47437. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47438. * @return {string} The property name.
  47439. */
  47440. getPropertyName( node, shaderStage = this.shaderStage ) {
  47441. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  47442. if ( shaderStage === 'vertex' ) {
  47443. return `varyings.${ node.name }`;
  47444. }
  47445. } else if ( node.isNodeUniform === true ) {
  47446. const name = node.name;
  47447. const type = node.type;
  47448. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  47449. return name;
  47450. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  47451. if ( this.isCustomStruct( node ) ) {
  47452. return name;
  47453. }
  47454. return name + '.value';
  47455. } else {
  47456. return node.groupNode.name + '.' + name;
  47457. }
  47458. }
  47459. return super.getPropertyName( node );
  47460. }
  47461. /**
  47462. * Returns the output struct name.
  47463. *
  47464. * @return {string} The name of the output struct.
  47465. */
  47466. getOutputStructName() {
  47467. return 'output';
  47468. }
  47469. /**
  47470. * Returns the native shader operator name for a given generic name.
  47471. *
  47472. * @param {string} op - The operator name to resolve.
  47473. * @return {?string} The resolved operator name.
  47474. */
  47475. getFunctionOperator( op ) {
  47476. const fnOp = wgslFnOpLib[ op ];
  47477. if ( fnOp !== undefined ) {
  47478. this._include( fnOp );
  47479. return fnOp;
  47480. }
  47481. return null;
  47482. }
  47483. /**
  47484. * Returns the node access for the given node and shader stage.
  47485. *
  47486. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  47487. * @param {string} shaderStage - The shader stage.
  47488. * @return {string} The node access.
  47489. */
  47490. getNodeAccess( node, shaderStage ) {
  47491. if ( shaderStage !== 'compute' )
  47492. return NodeAccess.READ_ONLY;
  47493. return node.access;
  47494. }
  47495. /**
  47496. * Returns A WGSL snippet representing the storage access.
  47497. *
  47498. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  47499. * @param {string} shaderStage - The shader stage.
  47500. * @return {string} The WGSL snippet representing the storage access.
  47501. */
  47502. getStorageAccess( node, shaderStage ) {
  47503. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  47504. }
  47505. /**
  47506. * This method is one of the more important ones since it's responsible
  47507. * for generating a matching binding instance for the given uniform node.
  47508. *
  47509. * These bindings are later used in the renderer to create bind groups
  47510. * and layouts.
  47511. *
  47512. * @param {UniformNode} node - The uniform node.
  47513. * @param {string} type - The node data type.
  47514. * @param {string} shaderStage - The shader stage.
  47515. * @param {?string} [name=null] - An optional uniform name.
  47516. * @return {NodeUniform} The node uniform object.
  47517. */
  47518. getUniformFromNode( node, type, shaderStage, name = null ) {
  47519. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  47520. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  47521. if ( nodeData.uniformGPU === undefined ) {
  47522. let uniformGPU;
  47523. const group = node.groupNode;
  47524. const groupName = group.name;
  47525. const bindings = this.getBindGroupArray( groupName, shaderStage );
  47526. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  47527. let texture = null;
  47528. const access = this.getNodeAccess( node, shaderStage );
  47529. if ( type === 'texture' || type === 'storageTexture' ) {
  47530. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  47531. } else if ( type === 'cubeTexture' ) {
  47532. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  47533. } else if ( type === 'texture3D' ) {
  47534. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  47535. }
  47536. texture.store = node.isStorageTextureNode === true;
  47537. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47538. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  47539. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  47540. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47541. bindings.push( sampler, texture );
  47542. uniformGPU = [ sampler, texture ];
  47543. } else {
  47544. bindings.push( texture );
  47545. uniformGPU = [ texture ];
  47546. }
  47547. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  47548. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  47549. const buffer = new bufferClass( node, group );
  47550. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47551. bindings.push( buffer );
  47552. uniformGPU = buffer;
  47553. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  47554. } else {
  47555. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  47556. let uniformsGroup = uniformsStage[ groupName ];
  47557. if ( uniformsGroup === undefined ) {
  47558. uniformsGroup = new NodeUniformsGroup( groupName, group );
  47559. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47560. uniformsStage[ groupName ] = uniformsGroup;
  47561. bindings.push( uniformsGroup );
  47562. }
  47563. uniformGPU = this.getNodeUniform( uniformNode, type );
  47564. uniformsGroup.addUniform( uniformGPU );
  47565. }
  47566. nodeData.uniformGPU = uniformGPU;
  47567. }
  47568. return uniformNode;
  47569. }
  47570. /**
  47571. * This method should be used whenever builtins are required in nodes.
  47572. * The internal builtins data structure will make sure builtins are
  47573. * defined in the WGSL source.
  47574. *
  47575. * @param {string} name - The builtin name.
  47576. * @param {string} property - The property name.
  47577. * @param {string} type - The node data type.
  47578. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47579. * @return {string} The property name.
  47580. */
  47581. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  47582. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  47583. if ( map.has( name ) === false ) {
  47584. map.set( name, {
  47585. name,
  47586. property,
  47587. type
  47588. } );
  47589. }
  47590. return property;
  47591. }
  47592. /**
  47593. * Returns `true` if the given builtin is defined in the given shader stage.
  47594. *
  47595. * @param {string} name - The builtin name.
  47596. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47597. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  47598. */
  47599. hasBuiltin( name, shaderStage = this.shaderStage ) {
  47600. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  47601. }
  47602. /**
  47603. * Returns the vertex index builtin.
  47604. *
  47605. * @return {string} The vertex index.
  47606. */
  47607. getVertexIndex() {
  47608. if ( this.shaderStage === 'vertex' ) {
  47609. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  47610. }
  47611. return 'vertexIndex';
  47612. }
  47613. /**
  47614. * Builds the given shader node.
  47615. *
  47616. * @param {ShaderNodeInternal} shaderNode - The shader node.
  47617. * @return {string} The WGSL function code.
  47618. */
  47619. buildFunctionCode( shaderNode ) {
  47620. const layout = shaderNode.layout;
  47621. const flowData = this.flowShaderNode( shaderNode );
  47622. const parameters = [];
  47623. for ( const input of layout.inputs ) {
  47624. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  47625. }
  47626. //
  47627. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  47628. ${ flowData.vars }
  47629. ${ flowData.code }
  47630. `;
  47631. if ( flowData.result ) {
  47632. code += `\treturn ${ flowData.result };\n`;
  47633. }
  47634. code += '\n}\n';
  47635. //
  47636. return code;
  47637. }
  47638. /**
  47639. * Returns the instance index builtin.
  47640. *
  47641. * @return {string} The instance index.
  47642. */
  47643. getInstanceIndex() {
  47644. if ( this.shaderStage === 'vertex' ) {
  47645. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  47646. }
  47647. return 'instanceIndex';
  47648. }
  47649. /**
  47650. * Returns the invocation local index builtin.
  47651. *
  47652. * @return {string} The invocation local index.
  47653. */
  47654. getInvocationLocalIndex() {
  47655. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  47656. }
  47657. /**
  47658. * Returns the subgroup size builtin.
  47659. *
  47660. * @return {string} The subgroup size.
  47661. */
  47662. getSubgroupSize() {
  47663. this.enableSubGroups();
  47664. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  47665. }
  47666. /**
  47667. * Returns the invocation subgroup index builtin.
  47668. *
  47669. * @return {string} The invocation subgroup index.
  47670. */
  47671. getInvocationSubgroupIndex() {
  47672. this.enableSubGroups();
  47673. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  47674. }
  47675. /**
  47676. * Returns the subgroup index builtin.
  47677. *
  47678. * @return {string} The subgroup index.
  47679. */
  47680. getSubgroupIndex() {
  47681. this.enableSubGroups();
  47682. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  47683. }
  47684. /**
  47685. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  47686. *
  47687. * @return {null} Null.
  47688. */
  47689. getDrawIndex() {
  47690. return null;
  47691. }
  47692. /**
  47693. * Returns the front facing builtin.
  47694. *
  47695. * @return {string} The front facing builtin.
  47696. */
  47697. getFrontFacing() {
  47698. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  47699. }
  47700. /**
  47701. * Returns the frag coord builtin.
  47702. *
  47703. * @return {string} The frag coord builtin.
  47704. */
  47705. getFragCoord() {
  47706. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  47707. }
  47708. /**
  47709. * Returns the frag depth builtin.
  47710. *
  47711. * @return {string} The frag depth builtin.
  47712. */
  47713. getFragDepth() {
  47714. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  47715. }
  47716. /**
  47717. * Returns the clip distances builtin.
  47718. *
  47719. * @return {string} The clip distances builtin.
  47720. */
  47721. getClipDistance() {
  47722. return 'varyings.hw_clip_distances';
  47723. }
  47724. /**
  47725. * Whether to flip texture data along its vertical axis or not.
  47726. *
  47727. * @return {boolean} Returns always `false` in context of WGSL.
  47728. */
  47729. isFlipY() {
  47730. return false;
  47731. }
  47732. /**
  47733. * Enables the given directive for the given shader stage.
  47734. *
  47735. * @param {string} name - The directive name.
  47736. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  47737. */
  47738. enableDirective( name, shaderStage = this.shaderStage ) {
  47739. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  47740. stage.add( name );
  47741. }
  47742. /**
  47743. * Returns the directives of the given shader stage as a WGSL string.
  47744. *
  47745. * @param {string} shaderStage - The shader stage.
  47746. * @return {string} A WGSL snippet that enables the directives of the given stage.
  47747. */
  47748. getDirectives( shaderStage ) {
  47749. const snippets = [];
  47750. const directives = this.directives[ shaderStage ];
  47751. if ( directives !== undefined ) {
  47752. for ( const directive of directives ) {
  47753. snippets.push( `enable ${directive};` );
  47754. }
  47755. }
  47756. return snippets.join( '\n' );
  47757. }
  47758. /**
  47759. * Enables the 'subgroups' directive.
  47760. */
  47761. enableSubGroups() {
  47762. this.enableDirective( 'subgroups' );
  47763. }
  47764. /**
  47765. * Enables the 'subgroups-f16' directive.
  47766. */
  47767. enableSubgroupsF16() {
  47768. this.enableDirective( 'subgroups-f16' );
  47769. }
  47770. /**
  47771. * Enables the 'clip_distances' directive.
  47772. */
  47773. enableClipDistances() {
  47774. this.enableDirective( 'clip_distances' );
  47775. }
  47776. /**
  47777. * Enables the 'f16' directive.
  47778. */
  47779. enableShaderF16() {
  47780. this.enableDirective( 'f16' );
  47781. }
  47782. /**
  47783. * Enables the 'dual_source_blending' directive.
  47784. */
  47785. enableDualSourceBlending() {
  47786. this.enableDirective( 'dual_source_blending' );
  47787. }
  47788. /**
  47789. * Enables hardware clipping.
  47790. *
  47791. * @param {string} planeCount - The clipping plane count.
  47792. */
  47793. enableHardwareClipping( planeCount ) {
  47794. this.enableClipDistances();
  47795. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  47796. }
  47797. /**
  47798. * Returns the builtins of the given shader stage as a WGSL string.
  47799. *
  47800. * @param {string} shaderStage - The shader stage.
  47801. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  47802. */
  47803. getBuiltins( shaderStage ) {
  47804. const snippets = [];
  47805. const builtins = this.builtins[ shaderStage ];
  47806. if ( builtins !== undefined ) {
  47807. for ( const { name, property, type } of builtins.values() ) {
  47808. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  47809. }
  47810. }
  47811. return snippets.join( ',\n\t' );
  47812. }
  47813. /**
  47814. * This method should be used when a new scoped buffer is used in context of
  47815. * compute shaders. It adds the array to the internal data structure which is
  47816. * later used to generate the respective WGSL.
  47817. *
  47818. * @param {string} name - The array name.
  47819. * @param {string} scope - The scope.
  47820. * @param {string} bufferType - The buffer type.
  47821. * @param {string} bufferCount - The buffer count.
  47822. * @return {string} The array name.
  47823. */
  47824. getScopedArray( name, scope, bufferType, bufferCount ) {
  47825. if ( this.scopedArrays.has( name ) === false ) {
  47826. this.scopedArrays.set( name, {
  47827. name,
  47828. scope,
  47829. bufferType,
  47830. bufferCount
  47831. } );
  47832. }
  47833. return name;
  47834. }
  47835. /**
  47836. * Returns the scoped arrays of the given shader stage as a WGSL string.
  47837. *
  47838. * @param {string} shaderStage - The shader stage.
  47839. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  47840. * Returns `undefined` when used in the vertex or fragment stage.
  47841. */
  47842. getScopedArrays( shaderStage ) {
  47843. if ( shaderStage !== 'compute' ) {
  47844. return;
  47845. }
  47846. const snippets = [];
  47847. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  47848. const type = this.getType( bufferType );
  47849. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  47850. }
  47851. return snippets.join( '\n' );
  47852. }
  47853. /**
  47854. * Returns the shader attributes of the given shader stage as a WGSL string.
  47855. *
  47856. * @param {string} shaderStage - The shader stage.
  47857. * @return {string} The WGSL snippet that defines the shader attributes.
  47858. */
  47859. getAttributes( shaderStage ) {
  47860. const snippets = [];
  47861. if ( shaderStage === 'compute' ) {
  47862. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  47863. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  47864. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  47865. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  47866. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  47867. this.enableDirective( 'subgroups', shaderStage );
  47868. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  47869. }
  47870. }
  47871. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  47872. const builtins = this.getBuiltins( 'attribute' );
  47873. if ( builtins ) snippets.push( builtins );
  47874. const attributes = this.getAttributesArray();
  47875. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  47876. const attribute = attributes[ index ];
  47877. const name = attribute.name;
  47878. const type = this.getType( attribute.type );
  47879. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  47880. }
  47881. }
  47882. return snippets.join( ',\n\t' );
  47883. }
  47884. /**
  47885. * Returns the members of the given struct type node as a WGSL string.
  47886. *
  47887. * @param {StructTypeNode} struct - The struct type node.
  47888. * @return {string} The WGSL snippet that defines the struct members.
  47889. */
  47890. getStructMembers( struct ) {
  47891. const snippets = [];
  47892. for ( const member of struct.members ) {
  47893. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  47894. let type = this.getType( member.type );
  47895. if ( member.atomic ) {
  47896. type = 'atomic< ' + type + ' >';
  47897. }
  47898. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  47899. }
  47900. if ( struct.output ) {
  47901. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  47902. }
  47903. return snippets.join( ',\n' );
  47904. }
  47905. /**
  47906. * Returns the structs of the given shader stage as a WGSL string.
  47907. *
  47908. * @param {string} shaderStage - The shader stage.
  47909. * @return {string} The WGSL snippet that defines the structs.
  47910. */
  47911. getStructs( shaderStage ) {
  47912. let result = '';
  47913. const structs = this.structs[ shaderStage ];
  47914. if ( structs.length > 0 ) {
  47915. const snippets = [];
  47916. for ( const struct of structs ) {
  47917. let snippet = `struct ${ struct.name } {\n`;
  47918. snippet += this.getStructMembers( struct );
  47919. snippet += '\n};';
  47920. snippets.push( snippet );
  47921. }
  47922. result = '\n' + snippets.join( '\n\n' ) + '\n';
  47923. }
  47924. return result;
  47925. }
  47926. /**
  47927. * Returns a WGSL string representing a variable.
  47928. *
  47929. * @param {string} type - The variable's type.
  47930. * @param {string} name - The variable's name.
  47931. * @param {?number} [count=null] - The array length.
  47932. * @return {string} The WGSL snippet that defines a variable.
  47933. */
  47934. getVar( type, name, count = null ) {
  47935. let snippet = `var ${ name } : `;
  47936. if ( count !== null ) {
  47937. snippet += this.generateArrayDeclaration( type, count );
  47938. } else {
  47939. snippet += this.getType( type );
  47940. }
  47941. return snippet;
  47942. }
  47943. /**
  47944. * Returns the variables of the given shader stage as a WGSL string.
  47945. *
  47946. * @param {string} shaderStage - The shader stage.
  47947. * @return {string} The WGSL snippet that defines the variables.
  47948. */
  47949. getVars( shaderStage ) {
  47950. const snippets = [];
  47951. const vars = this.vars[ shaderStage ];
  47952. if ( vars !== undefined ) {
  47953. for ( const variable of vars ) {
  47954. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  47955. }
  47956. }
  47957. return `\n${ snippets.join( '\n' ) }\n`;
  47958. }
  47959. /**
  47960. * Returns the varyings of the given shader stage as a WGSL string.
  47961. *
  47962. * @param {string} shaderStage - The shader stage.
  47963. * @return {string} The WGSL snippet that defines the varyings.
  47964. */
  47965. getVaryings( shaderStage ) {
  47966. const snippets = [];
  47967. if ( shaderStage === 'vertex' ) {
  47968. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  47969. }
  47970. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  47971. const varyings = this.varyings;
  47972. const vars = this.vars[ shaderStage ];
  47973. for ( let index = 0; index < varyings.length; index ++ ) {
  47974. const varying = varyings[ index ];
  47975. if ( varying.needsInterpolation ) {
  47976. let attributesSnippet = `@location( ${index} )`;
  47977. if ( varying.interpolationType ) {
  47978. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  47979. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  47980. // Otherwise, optimize interpolation when sensible
  47981. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  47982. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  47983. }
  47984. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  47985. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  47986. vars.push( varying );
  47987. }
  47988. }
  47989. }
  47990. const builtins = this.getBuiltins( shaderStage );
  47991. if ( builtins ) snippets.push( builtins );
  47992. const code = snippets.join( ',\n\t' );
  47993. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  47994. }
  47995. isCustomStruct( nodeUniform ) {
  47996. const attribute = nodeUniform.value;
  47997. const bufferNode = nodeUniform.node;
  47998. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  47999. const isStructArray =
  48000. ( bufferNode.value && bufferNode.value.array ) &&
  48001. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  48002. return isAttributeStructType && ! isStructArray;
  48003. }
  48004. /**
  48005. * Returns the uniforms of the given shader stage as a WGSL string.
  48006. *
  48007. * @param {string} shaderStage - The shader stage.
  48008. * @return {string} The WGSL snippet that defines the uniforms.
  48009. */
  48010. getUniforms( shaderStage ) {
  48011. const uniforms = this.uniforms[ shaderStage ];
  48012. const bindingSnippets = [];
  48013. const bufferSnippets = [];
  48014. const structSnippets = [];
  48015. const uniformGroups = {};
  48016. for ( const uniform of uniforms ) {
  48017. const groupName = uniform.groupNode.name;
  48018. const uniformIndexes = this.bindingsIndexes[ groupName ];
  48019. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  48020. const texture = uniform.node.value;
  48021. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  48022. if ( this.isSampleCompare( texture ) ) {
  48023. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  48024. } else {
  48025. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  48026. }
  48027. }
  48028. let textureType;
  48029. let multisampled = '';
  48030. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  48031. if ( primarySamples > 1 ) {
  48032. multisampled = '_multisampled';
  48033. }
  48034. if ( texture.isCubeTexture === true ) {
  48035. textureType = 'texture_cube<f32>';
  48036. } else if ( texture.isDepthTexture === true ) {
  48037. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  48038. textureType = `texture${ multisampled }_2d<f32>`;
  48039. } else {
  48040. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  48041. }
  48042. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  48043. textureType = 'texture_2d_array<f32>';
  48044. } else if ( texture.isVideoTexture === true ) {
  48045. textureType = 'texture_external';
  48046. } else if ( texture.isData3DTexture === true ) {
  48047. textureType = 'texture_3d<f32>';
  48048. } else if ( uniform.node.isStorageTextureNode === true ) {
  48049. const format = getFormat( texture );
  48050. const access = this.getStorageAccess( uniform.node, shaderStage );
  48051. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  48052. } else {
  48053. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  48054. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  48055. }
  48056. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  48057. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  48058. const bufferNode = uniform.node;
  48059. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  48060. const bufferCount = bufferNode.bufferCount;
  48061. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  48062. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  48063. if ( this.isCustomStruct( uniform ) ) {
  48064. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  48065. } else {
  48066. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  48067. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  48068. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  48069. }
  48070. } else {
  48071. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  48072. const groupName = uniform.groupNode.name;
  48073. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  48074. index: uniformIndexes.binding ++,
  48075. id: uniformIndexes.group,
  48076. snippets: []
  48077. } );
  48078. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  48079. }
  48080. }
  48081. for ( const name in uniformGroups ) {
  48082. const group = uniformGroups[ name ];
  48083. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  48084. }
  48085. let code = bindingSnippets.join( '\n' );
  48086. code += bufferSnippets.join( '\n' );
  48087. code += structSnippets.join( '\n' );
  48088. return code;
  48089. }
  48090. /**
  48091. * Controls the code build of the shader stages.
  48092. */
  48093. buildCode() {
  48094. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  48095. this.sortBindingGroups();
  48096. for ( const shaderStage in shadersData ) {
  48097. this.shaderStage = shaderStage;
  48098. const stageData = shadersData[ shaderStage ];
  48099. stageData.uniforms = this.getUniforms( shaderStage );
  48100. stageData.attributes = this.getAttributes( shaderStage );
  48101. stageData.varyings = this.getVaryings( shaderStage );
  48102. stageData.structs = this.getStructs( shaderStage );
  48103. stageData.vars = this.getVars( shaderStage );
  48104. stageData.codes = this.getCodes( shaderStage );
  48105. stageData.directives = this.getDirectives( shaderStage );
  48106. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  48107. //
  48108. let flow = '// code\n\n';
  48109. flow += this.flowCode[ shaderStage ];
  48110. const flowNodes = this.flowNodes[ shaderStage ];
  48111. const mainNode = flowNodes[ flowNodes.length - 1 ];
  48112. const outputNode = mainNode.outputNode;
  48113. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  48114. for ( const node of flowNodes ) {
  48115. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  48116. const slotName = node.name;
  48117. if ( slotName ) {
  48118. if ( flow.length > 0 ) flow += '\n';
  48119. flow += `\t// flow -> ${ slotName }\n`;
  48120. }
  48121. flow += `${ flowSlotData.code }\n\t`;
  48122. if ( node === mainNode && shaderStage !== 'compute' ) {
  48123. flow += '// result\n\n\t';
  48124. if ( shaderStage === 'vertex' ) {
  48125. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  48126. } else if ( shaderStage === 'fragment' ) {
  48127. if ( isOutputStruct ) {
  48128. stageData.returnType = outputNode.getNodeType( this );
  48129. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  48130. flow += `return ${ flowSlotData.result };`;
  48131. } else {
  48132. let structSnippet = '\t@location(0) color: vec4<f32>';
  48133. const builtins = this.getBuiltins( 'output' );
  48134. if ( builtins ) structSnippet += ',\n\t' + builtins;
  48135. stageData.returnType = 'OutputStruct';
  48136. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  48137. stageData.structs += '\nvar<private> output : OutputStruct;';
  48138. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  48139. }
  48140. }
  48141. }
  48142. }
  48143. stageData.flow = flow;
  48144. }
  48145. this.shaderStage = null;
  48146. if ( this.material !== null ) {
  48147. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  48148. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  48149. } else {
  48150. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  48151. }
  48152. }
  48153. /**
  48154. * Returns the native shader method name for a given generic name.
  48155. *
  48156. * @param {string} method - The method name to resolve.
  48157. * @param {?string} [output=null] - An optional output.
  48158. * @return {string} The resolved WGSL method name.
  48159. */
  48160. getMethod( method, output = null ) {
  48161. let wgslMethod;
  48162. if ( output !== null ) {
  48163. wgslMethod = this._getWGSLMethod( method + '_' + output );
  48164. }
  48165. if ( wgslMethod === undefined ) {
  48166. wgslMethod = this._getWGSLMethod( method );
  48167. }
  48168. return wgslMethod || method;
  48169. }
  48170. /**
  48171. * Returns the WGSL type of the given node data type.
  48172. *
  48173. * @param {string} type - The node data type.
  48174. * @return {string} The WGSL type.
  48175. */
  48176. getType( type ) {
  48177. return wgslTypeLib[ type ] || type;
  48178. }
  48179. /**
  48180. * Whether the requested feature is available or not.
  48181. *
  48182. * @param {string} name - The requested feature.
  48183. * @return {boolean} Whether the requested feature is supported or not.
  48184. */
  48185. isAvailable( name ) {
  48186. let result = supports[ name ];
  48187. if ( result === undefined ) {
  48188. if ( name === 'float32Filterable' ) {
  48189. result = this.renderer.hasFeature( 'float32-filterable' );
  48190. } else if ( name === 'clipDistance' ) {
  48191. result = this.renderer.hasFeature( 'clip-distances' );
  48192. }
  48193. supports[ name ] = result;
  48194. }
  48195. return result;
  48196. }
  48197. /**
  48198. * Returns the native shader method name for a given generic name.
  48199. *
  48200. * @private
  48201. * @param {string} method - The method name to resolve.
  48202. * @return {string} The resolved WGSL method name.
  48203. */
  48204. _getWGSLMethod( method ) {
  48205. if ( wgslPolyfill[ method ] !== undefined ) {
  48206. this._include( method );
  48207. }
  48208. return wgslMethods[ method ];
  48209. }
  48210. /**
  48211. * Includes the given method name into the current
  48212. * function node.
  48213. *
  48214. * @private
  48215. * @param {string} name - The method name to include.
  48216. * @return {CodeNode} The respective code node.
  48217. */
  48218. _include( name ) {
  48219. const codeNode = wgslPolyfill[ name ];
  48220. codeNode.build( this );
  48221. if ( this.currentFunctionNode !== null ) {
  48222. this.currentFunctionNode.includes.push( codeNode );
  48223. }
  48224. return codeNode;
  48225. }
  48226. /**
  48227. * Returns a WGSL vertex shader based on the given shader data.
  48228. *
  48229. * @private
  48230. * @param {Object} shaderData - The shader data.
  48231. * @return {string} The vertex shader.
  48232. */
  48233. _getWGSLVertexCode( shaderData ) {
  48234. return `${ this.getSignature() }
  48235. // directives
  48236. ${shaderData.directives}
  48237. // structs
  48238. ${shaderData.structs}
  48239. // uniforms
  48240. ${shaderData.uniforms}
  48241. // varyings
  48242. ${shaderData.varyings}
  48243. var<private> varyings : VaryingsStruct;
  48244. // codes
  48245. ${shaderData.codes}
  48246. @vertex
  48247. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  48248. // vars
  48249. ${shaderData.vars}
  48250. // flow
  48251. ${shaderData.flow}
  48252. return varyings;
  48253. }
  48254. `;
  48255. }
  48256. /**
  48257. * Returns a WGSL fragment shader based on the given shader data.
  48258. *
  48259. * @private
  48260. * @param {Object} shaderData - The shader data.
  48261. * @return {string} The vertex shader.
  48262. */
  48263. _getWGSLFragmentCode( shaderData ) {
  48264. return `${ this.getSignature() }
  48265. // global
  48266. ${ diagnostics }
  48267. // structs
  48268. ${shaderData.structs}
  48269. // uniforms
  48270. ${shaderData.uniforms}
  48271. // codes
  48272. ${shaderData.codes}
  48273. @fragment
  48274. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  48275. // vars
  48276. ${shaderData.vars}
  48277. // flow
  48278. ${shaderData.flow}
  48279. }
  48280. `;
  48281. }
  48282. /**
  48283. * Returns a WGSL compute shader based on the given shader data.
  48284. *
  48285. * @private
  48286. * @param {Object} shaderData - The shader data.
  48287. * @param {string} workgroupSize - The workgroup size.
  48288. * @return {string} The vertex shader.
  48289. */
  48290. _getWGSLComputeCode( shaderData, workgroupSize ) {
  48291. return `${ this.getSignature() }
  48292. // directives
  48293. ${shaderData.directives}
  48294. // system
  48295. var<private> instanceIndex : u32;
  48296. // locals
  48297. ${shaderData.scopedArrays}
  48298. // structs
  48299. ${shaderData.structs}
  48300. // uniforms
  48301. ${shaderData.uniforms}
  48302. // codes
  48303. ${shaderData.codes}
  48304. @compute @workgroup_size( ${workgroupSize} )
  48305. fn main( ${shaderData.attributes} ) {
  48306. // system
  48307. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  48308. // vars
  48309. ${shaderData.vars}
  48310. // flow
  48311. ${shaderData.flow}
  48312. }
  48313. `;
  48314. }
  48315. /**
  48316. * Returns a WGSL struct based on the given name and variables.
  48317. *
  48318. * @private
  48319. * @param {string} name - The struct name.
  48320. * @param {string} vars - The struct variables.
  48321. * @return {string} The WGSL snippet representing a struct.
  48322. */
  48323. _getWGSLStruct( name, vars ) {
  48324. return `
  48325. struct ${name} {
  48326. ${vars}
  48327. };`;
  48328. }
  48329. /**
  48330. * Returns a WGSL struct binding.
  48331. *
  48332. * @private
  48333. * @param {string} name - The struct name.
  48334. * @param {string} vars - The struct variables.
  48335. * @param {string} access - The access.
  48336. * @param {number} [binding=0] - The binding index.
  48337. * @param {number} [group=0] - The group index.
  48338. * @return {string} The WGSL snippet representing a struct binding.
  48339. */
  48340. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  48341. const structName = name + 'Struct';
  48342. const structSnippet = this._getWGSLStruct( structName, vars );
  48343. return `${structSnippet}
  48344. @binding( ${ binding } ) @group( ${ group } )
  48345. var<${access}> ${ name } : ${ structName };`;
  48346. }
  48347. }
  48348. /**
  48349. * A WebGPU backend utility module with common helpers.
  48350. *
  48351. * @private
  48352. */
  48353. class WebGPUUtils {
  48354. /**
  48355. * Constructs a new utility object.
  48356. *
  48357. * @param {WebGPUBackend} backend - The WebGPU backend.
  48358. */
  48359. constructor( backend ) {
  48360. /**
  48361. * A reference to the WebGPU backend.
  48362. *
  48363. * @type {WebGPUBackend}
  48364. */
  48365. this.backend = backend;
  48366. }
  48367. /**
  48368. * Returns the depth/stencil GPU format for the given render context.
  48369. *
  48370. * @param {RenderContext} renderContext - The render context.
  48371. * @return {string} The depth/stencil GPU texture format.
  48372. */
  48373. getCurrentDepthStencilFormat( renderContext ) {
  48374. let format;
  48375. if ( renderContext.depthTexture !== null ) {
  48376. format = this.getTextureFormatGPU( renderContext.depthTexture );
  48377. } else if ( renderContext.depth && renderContext.stencil ) {
  48378. format = GPUTextureFormat.Depth24PlusStencil8;
  48379. } else if ( renderContext.depth ) {
  48380. format = GPUTextureFormat.Depth24Plus;
  48381. }
  48382. return format;
  48383. }
  48384. /**
  48385. * Returns the GPU format for the given texture.
  48386. *
  48387. * @param {Texture} texture - The texture.
  48388. * @return {string} The GPU texture format.
  48389. */
  48390. getTextureFormatGPU( texture ) {
  48391. return this.backend.get( texture ).format;
  48392. }
  48393. /**
  48394. * Returns an object that defines the multi-sampling state of the given texture.
  48395. *
  48396. * @param {Texture} texture - The texture.
  48397. * @return {Object} The multi-sampling state.
  48398. */
  48399. getTextureSampleData( texture ) {
  48400. let samples;
  48401. if ( texture.isFramebufferTexture ) {
  48402. samples = 1;
  48403. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  48404. const renderer = this.backend.renderer;
  48405. const renderTarget = renderer.getRenderTarget();
  48406. samples = renderTarget ? renderTarget.samples : renderer.samples;
  48407. } else if ( texture.renderTarget ) {
  48408. samples = texture.renderTarget.samples;
  48409. }
  48410. samples = samples || 1;
  48411. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  48412. const primarySamples = isMSAA ? 1 : samples;
  48413. return { samples, primarySamples, isMSAA };
  48414. }
  48415. /**
  48416. * Returns the default color attachment's GPU format of the current render context.
  48417. *
  48418. * @param {RenderContext} renderContext - The render context.
  48419. * @return {string} The GPU texture format of the default color attachment.
  48420. */
  48421. getCurrentColorFormat( renderContext ) {
  48422. let format;
  48423. if ( renderContext.textures !== null ) {
  48424. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  48425. } else {
  48426. format = this.getPreferredCanvasFormat(); // default context format
  48427. }
  48428. return format;
  48429. }
  48430. /**
  48431. * Returns the output color space of the current render context.
  48432. *
  48433. * @param {RenderContext} renderContext - The render context.
  48434. * @return {string} The output color space.
  48435. */
  48436. getCurrentColorSpace( renderContext ) {
  48437. if ( renderContext.textures !== null ) {
  48438. return renderContext.textures[ 0 ].colorSpace;
  48439. }
  48440. return this.backend.renderer.outputColorSpace;
  48441. }
  48442. /**
  48443. * Returns GPU primitive topology for the given object and material.
  48444. *
  48445. * @param {Object3D} object - The 3D object.
  48446. * @param {Material} material - The material.
  48447. * @return {string} The GPU primitive topology.
  48448. */
  48449. getPrimitiveTopology( object, material ) {
  48450. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  48451. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  48452. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  48453. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  48454. }
  48455. /**
  48456. * Returns a modified sample count from the given sample count value.
  48457. *
  48458. * That is required since WebGPU does not support arbitrary sample counts.
  48459. *
  48460. * @param {number} sampleCount - The input sample count.
  48461. * @return {number} The (potentially updated) output sample count.
  48462. */
  48463. getSampleCount( sampleCount ) {
  48464. let count = 1;
  48465. if ( sampleCount > 1 ) {
  48466. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  48467. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  48468. if ( count === 2 ) {
  48469. count = 4;
  48470. }
  48471. }
  48472. return count;
  48473. }
  48474. /**
  48475. * Returns the sample count of the given render context.
  48476. *
  48477. * @param {RenderContext} renderContext - The render context.
  48478. * @return {number} The sample count.
  48479. */
  48480. getSampleCountRenderContext( renderContext ) {
  48481. if ( renderContext.textures !== null ) {
  48482. return this.getSampleCount( renderContext.sampleCount );
  48483. }
  48484. return this.getSampleCount( this.backend.renderer.samples );
  48485. }
  48486. /**
  48487. * Returns the preferred canvas format.
  48488. *
  48489. * There is a separate method for this so it's possible to
  48490. * honor edge cases for specific devices.
  48491. *
  48492. * @return {string} The GPU texture format of the canvas.
  48493. */
  48494. getPreferredCanvasFormat() {
  48495. const outputType = this.backend.parameters.outputType;
  48496. if ( outputType === undefined ) {
  48497. return navigator.gpu.getPreferredCanvasFormat();
  48498. } else if ( outputType === UnsignedByteType ) {
  48499. return GPUTextureFormat.BGRA8Unorm;
  48500. } else if ( outputType === HalfFloatType ) {
  48501. return GPUTextureFormat.RGBA16Float;
  48502. } else {
  48503. throw new Error( 'Unsupported outputType' );
  48504. }
  48505. }
  48506. }
  48507. const typedArraysToVertexFormatPrefix = new Map( [
  48508. [ Int8Array, [ 'sint8', 'snorm8' ]],
  48509. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  48510. [ Int16Array, [ 'sint16', 'snorm16' ]],
  48511. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  48512. [ Int32Array, [ 'sint32', 'snorm32' ]],
  48513. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  48514. [ Float32Array, [ 'float32', ]],
  48515. ] );
  48516. const typedAttributeToVertexFormatPrefix = new Map( [
  48517. [ Float16BufferAttribute, [ 'float16', ]],
  48518. ] );
  48519. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  48520. [ Int32Array, 'sint32' ],
  48521. [ Int16Array, 'sint32' ], // patch for INT16
  48522. [ Uint32Array, 'uint32' ],
  48523. [ Uint16Array, 'uint32' ], // patch for UINT16
  48524. [ Float32Array, 'float32' ]
  48525. ] );
  48526. /**
  48527. * A WebGPU backend utility module for managing shader attributes.
  48528. *
  48529. * @private
  48530. */
  48531. class WebGPUAttributeUtils {
  48532. /**
  48533. * Constructs a new utility object.
  48534. *
  48535. * @param {WebGPUBackend} backend - The WebGPU backend.
  48536. */
  48537. constructor( backend ) {
  48538. /**
  48539. * A reference to the WebGPU backend.
  48540. *
  48541. * @type {WebGPUBackend}
  48542. */
  48543. this.backend = backend;
  48544. }
  48545. /**
  48546. * Creates the GPU buffer for the given buffer attribute.
  48547. *
  48548. * @param {BufferAttribute} attribute - The buffer attribute.
  48549. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  48550. */
  48551. createAttribute( attribute, usage ) {
  48552. const bufferAttribute = this._getBufferAttribute( attribute );
  48553. const backend = this.backend;
  48554. const bufferData = backend.get( bufferAttribute );
  48555. let buffer = bufferData.buffer;
  48556. if ( buffer === undefined ) {
  48557. const device = backend.device;
  48558. let array = bufferAttribute.array;
  48559. // patch for INT16 and UINT16
  48560. if ( attribute.normalized === false ) {
  48561. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  48562. array = new Int32Array( array );
  48563. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  48564. array = new Uint32Array( array );
  48565. if ( usage & GPUBufferUsage.INDEX ) {
  48566. for ( let i = 0; i < array.length; i ++ ) {
  48567. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  48568. }
  48569. }
  48570. }
  48571. }
  48572. bufferAttribute.array = array;
  48573. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  48574. array = new array.constructor( bufferAttribute.count * 4 );
  48575. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  48576. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  48577. }
  48578. // Update BufferAttribute
  48579. bufferAttribute.itemSize = 4;
  48580. bufferAttribute.array = array;
  48581. bufferData._force3to4BytesAlignment = true;
  48582. }
  48583. // ensure 4 byte alignment
  48584. const byteLength = array.byteLength;
  48585. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  48586. buffer = device.createBuffer( {
  48587. label: bufferAttribute.name,
  48588. size: size,
  48589. usage: usage,
  48590. mappedAtCreation: true
  48591. } );
  48592. new array.constructor( buffer.getMappedRange() ).set( array );
  48593. buffer.unmap();
  48594. bufferData.buffer = buffer;
  48595. }
  48596. }
  48597. /**
  48598. * Updates the GPU buffer of the given buffer attribute.
  48599. *
  48600. * @param {BufferAttribute} attribute - The buffer attribute.
  48601. */
  48602. updateAttribute( attribute ) {
  48603. const bufferAttribute = this._getBufferAttribute( attribute );
  48604. const backend = this.backend;
  48605. const device = backend.device;
  48606. const bufferData = backend.get( bufferAttribute );
  48607. const buffer = backend.get( bufferAttribute ).buffer;
  48608. let array = bufferAttribute.array;
  48609. // if storage buffer ensure 4 byte alignment
  48610. if ( bufferData._force3to4BytesAlignment === true ) {
  48611. array = new array.constructor( bufferAttribute.count * 4 );
  48612. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  48613. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  48614. }
  48615. bufferAttribute.array = array;
  48616. }
  48617. const isTypedArray = this._isTypedArray( array );
  48618. const updateRanges = bufferAttribute.updateRanges;
  48619. if ( updateRanges.length === 0 ) {
  48620. // Not using update ranges
  48621. device.queue.writeBuffer(
  48622. buffer,
  48623. 0,
  48624. array,
  48625. 0
  48626. );
  48627. } else {
  48628. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  48629. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  48630. const range = updateRanges[ i ];
  48631. let dataOffset, size;
  48632. if ( bufferData._force3to4BytesAlignment === true ) {
  48633. const vertexStart = Math.floor( range.start / 3 );
  48634. const vertexCount = Math.ceil( range.count / 3 );
  48635. dataOffset = vertexStart * 4 * byteOffsetFactor;
  48636. size = vertexCount * 4 * byteOffsetFactor;
  48637. } else {
  48638. dataOffset = range.start * byteOffsetFactor;
  48639. size = range.count * byteOffsetFactor;
  48640. }
  48641. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  48642. device.queue.writeBuffer(
  48643. buffer,
  48644. bufferOffset,
  48645. array,
  48646. dataOffset,
  48647. size
  48648. );
  48649. }
  48650. bufferAttribute.clearUpdateRanges();
  48651. }
  48652. }
  48653. /**
  48654. * This method creates the vertex buffer layout data which are
  48655. * require when creating a render pipeline for the given render object.
  48656. *
  48657. * @param {RenderObject} renderObject - The render object.
  48658. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  48659. */
  48660. createShaderVertexBuffers( renderObject ) {
  48661. const attributes = renderObject.getAttributes();
  48662. const vertexBuffers = new Map();
  48663. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  48664. const geometryAttribute = attributes[ slot ];
  48665. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  48666. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  48667. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  48668. if ( vertexBufferLayout === undefined ) {
  48669. let arrayStride, stepMode;
  48670. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  48671. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  48672. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  48673. } else {
  48674. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  48675. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  48676. }
  48677. // patch for INT16 and UINT16
  48678. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  48679. arrayStride = 4;
  48680. }
  48681. vertexBufferLayout = {
  48682. arrayStride,
  48683. attributes: [],
  48684. stepMode
  48685. };
  48686. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  48687. }
  48688. const format = this._getVertexFormat( geometryAttribute );
  48689. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  48690. vertexBufferLayout.attributes.push( {
  48691. shaderLocation: slot,
  48692. offset,
  48693. format
  48694. } );
  48695. }
  48696. return Array.from( vertexBuffers.values() );
  48697. }
  48698. /**
  48699. * Destroys the GPU buffer of the given buffer attribute.
  48700. *
  48701. * @param {BufferAttribute} attribute - The buffer attribute.
  48702. */
  48703. destroyAttribute( attribute ) {
  48704. const backend = this.backend;
  48705. const data = backend.get( this._getBufferAttribute( attribute ) );
  48706. data.buffer.destroy();
  48707. backend.delete( attribute );
  48708. }
  48709. /**
  48710. * This method performs a readback operation by moving buffer data from
  48711. * a storage buffer attribute from the GPU to the CPU.
  48712. *
  48713. * @async
  48714. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48715. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48716. */
  48717. async getArrayBufferAsync( attribute ) {
  48718. const backend = this.backend;
  48719. const device = backend.device;
  48720. const data = backend.get( this._getBufferAttribute( attribute ) );
  48721. const bufferGPU = data.buffer;
  48722. const size = bufferGPU.size;
  48723. const readBufferGPU = device.createBuffer( {
  48724. label: `${ attribute.name }_readback`,
  48725. size,
  48726. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  48727. } );
  48728. const cmdEncoder = device.createCommandEncoder( {
  48729. label: `readback_encoder_${ attribute.name }`
  48730. } );
  48731. cmdEncoder.copyBufferToBuffer(
  48732. bufferGPU,
  48733. 0,
  48734. readBufferGPU,
  48735. 0,
  48736. size
  48737. );
  48738. const gpuCommands = cmdEncoder.finish();
  48739. device.queue.submit( [ gpuCommands ] );
  48740. await readBufferGPU.mapAsync( GPUMapMode.READ );
  48741. const arrayBuffer = readBufferGPU.getMappedRange();
  48742. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  48743. readBufferGPU.unmap();
  48744. return dstBuffer.buffer;
  48745. }
  48746. /**
  48747. * Returns the vertex format of the given buffer attribute.
  48748. *
  48749. * @private
  48750. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  48751. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  48752. */
  48753. _getVertexFormat( geometryAttribute ) {
  48754. const { itemSize, normalized } = geometryAttribute;
  48755. const ArrayType = geometryAttribute.array.constructor;
  48756. const AttributeType = geometryAttribute.constructor;
  48757. let format;
  48758. if ( itemSize === 1 ) {
  48759. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  48760. } else {
  48761. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  48762. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  48763. if ( prefix ) {
  48764. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  48765. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  48766. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  48767. if ( paddedItemSize % 1 ) {
  48768. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  48769. }
  48770. format = `${prefix}x${paddedItemSize}`;
  48771. }
  48772. }
  48773. if ( ! format ) {
  48774. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  48775. }
  48776. return format;
  48777. }
  48778. /**
  48779. * Returns `true` if the given array is a typed array.
  48780. *
  48781. * @private
  48782. * @param {any} array - The array.
  48783. * @return {boolean} Whether the given array is a typed array or not.
  48784. */
  48785. _isTypedArray( array ) {
  48786. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  48787. }
  48788. /**
  48789. * Utility method for handling interleaved buffer attributes correctly.
  48790. * To process them, their `InterleavedBuffer` is returned.
  48791. *
  48792. * @private
  48793. * @param {BufferAttribute} attribute - The attribute.
  48794. * @return {BufferAttribute|InterleavedBuffer}
  48795. */
  48796. _getBufferAttribute( attribute ) {
  48797. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  48798. return attribute;
  48799. }
  48800. }
  48801. /**
  48802. * A WebGPU backend utility module for managing bindings.
  48803. *
  48804. * When reading the documentation it's helpful to keep in mind that
  48805. * all class definitions starting with 'GPU*' are modules from the
  48806. * WebGPU API. So for example `BindGroup` is a class from the engine
  48807. * whereas `GPUBindGroup` is a class from WebGPU.
  48808. *
  48809. * @private
  48810. */
  48811. class WebGPUBindingUtils {
  48812. /**
  48813. * Constructs a new utility object.
  48814. *
  48815. * @param {WebGPUBackend} backend - The WebGPU backend.
  48816. */
  48817. constructor( backend ) {
  48818. /**
  48819. * A reference to the WebGPU backend.
  48820. *
  48821. * @type {WebGPUBackend}
  48822. */
  48823. this.backend = backend;
  48824. /**
  48825. * A cache for managing bind group layouts.
  48826. *
  48827. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  48828. */
  48829. this.bindGroupLayoutCache = new WeakMap();
  48830. }
  48831. /**
  48832. * Creates a GPU bind group layout for the given bind group.
  48833. *
  48834. * @param {BindGroup} bindGroup - The bind group.
  48835. * @return {GPUBindGroupLayout} The GPU bind group layout.
  48836. */
  48837. createBindingsLayout( bindGroup ) {
  48838. const backend = this.backend;
  48839. const device = backend.device;
  48840. const entries = [];
  48841. let index = 0;
  48842. for ( const binding of bindGroup.bindings ) {
  48843. const bindingGPU = {
  48844. binding: index ++,
  48845. visibility: binding.visibility
  48846. };
  48847. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  48848. const buffer = {}; // GPUBufferBindingLayout
  48849. if ( binding.isStorageBuffer ) {
  48850. if ( binding.visibility & 4 ) {
  48851. // compute
  48852. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  48853. buffer.type = GPUBufferBindingType.Storage;
  48854. } else {
  48855. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  48856. }
  48857. } else {
  48858. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  48859. }
  48860. }
  48861. bindingGPU.buffer = buffer;
  48862. } else if ( binding.isSampler ) {
  48863. const sampler = {}; // GPUSamplerBindingLayout
  48864. if ( binding.texture.isDepthTexture ) {
  48865. if ( binding.texture.compareFunction !== null ) {
  48866. sampler.type = GPUSamplerBindingType.Comparison;
  48867. } else if ( backend.compatibilityMode ) {
  48868. sampler.type = GPUSamplerBindingType.NonFiltering;
  48869. }
  48870. }
  48871. bindingGPU.sampler = sampler;
  48872. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  48873. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  48874. } else if ( binding.isSampledTexture && binding.store ) {
  48875. const storageTexture = {}; // GPUStorageTextureBindingLayout
  48876. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  48877. const access = binding.access;
  48878. if ( access === NodeAccess.READ_WRITE ) {
  48879. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  48880. } else if ( access === NodeAccess.WRITE_ONLY ) {
  48881. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  48882. } else {
  48883. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  48884. }
  48885. bindingGPU.storageTexture = storageTexture;
  48886. } else if ( binding.isSampledTexture ) {
  48887. const texture = {}; // GPUTextureBindingLayout
  48888. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  48889. if ( primarySamples > 1 ) {
  48890. texture.multisampled = true;
  48891. if ( ! binding.texture.isDepthTexture ) {
  48892. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  48893. }
  48894. }
  48895. if ( binding.texture.isDepthTexture ) {
  48896. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  48897. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  48898. } else {
  48899. texture.sampleType = GPUTextureSampleType.Depth;
  48900. }
  48901. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  48902. const type = binding.texture.type;
  48903. if ( type === IntType ) {
  48904. texture.sampleType = GPUTextureSampleType.SInt;
  48905. } else if ( type === UnsignedIntType ) {
  48906. texture.sampleType = GPUTextureSampleType.UInt;
  48907. } else if ( type === FloatType ) {
  48908. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  48909. texture.sampleType = GPUTextureSampleType.Float;
  48910. } else {
  48911. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  48912. }
  48913. }
  48914. }
  48915. if ( binding.isSampledCubeTexture ) {
  48916. texture.viewDimension = GPUTextureViewDimension.Cube;
  48917. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  48918. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  48919. } else if ( binding.isSampledTexture3D ) {
  48920. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  48921. }
  48922. bindingGPU.texture = texture;
  48923. } else {
  48924. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  48925. }
  48926. entries.push( bindingGPU );
  48927. }
  48928. return device.createBindGroupLayout( { entries } );
  48929. }
  48930. /**
  48931. * Creates bindings from the given bind group definition.
  48932. *
  48933. * @param {BindGroup} bindGroup - The bind group.
  48934. * @param {Array<BindGroup>} bindings - Array of bind groups.
  48935. * @param {number} cacheIndex - The cache index.
  48936. * @param {number} version - The version.
  48937. */
  48938. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  48939. const { backend, bindGroupLayoutCache } = this;
  48940. const bindingsData = backend.get( bindGroup );
  48941. // setup (static) binding layout and (dynamic) binding group
  48942. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  48943. if ( bindLayoutGPU === undefined ) {
  48944. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  48945. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  48946. }
  48947. let bindGroupGPU;
  48948. if ( cacheIndex > 0 ) {
  48949. if ( bindingsData.groups === undefined ) {
  48950. bindingsData.groups = [];
  48951. bindingsData.versions = [];
  48952. }
  48953. if ( bindingsData.versions[ cacheIndex ] === version ) {
  48954. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  48955. }
  48956. }
  48957. if ( bindGroupGPU === undefined ) {
  48958. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  48959. if ( cacheIndex > 0 ) {
  48960. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  48961. bindingsData.versions[ cacheIndex ] = version;
  48962. }
  48963. }
  48964. bindingsData.group = bindGroupGPU;
  48965. bindingsData.layout = bindLayoutGPU;
  48966. }
  48967. /**
  48968. * Updates a buffer binding.
  48969. *
  48970. * @param {Buffer} binding - The buffer binding to update.
  48971. */
  48972. updateBinding( binding ) {
  48973. const backend = this.backend;
  48974. const device = backend.device;
  48975. const buffer = binding.buffer;
  48976. const bufferGPU = backend.get( binding ).buffer;
  48977. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  48978. }
  48979. /**
  48980. * Creates a GPU bind group for the camera index.
  48981. *
  48982. * @param {Uint32Array} data - The index data.
  48983. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  48984. * @return {GPUBindGroup} The GPU bind group.
  48985. */
  48986. createBindGroupIndex( data, layout ) {
  48987. const backend = this.backend;
  48988. const device = backend.device;
  48989. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  48990. const index = data[ 0 ];
  48991. const buffer = device.createBuffer( {
  48992. label: 'bindingCameraIndex_' + index,
  48993. size: 16, // uint(4) * 4
  48994. usage: usage
  48995. } );
  48996. device.queue.writeBuffer( buffer, 0, data, 0 );
  48997. const entries = [ { binding: 0, resource: { buffer } } ];
  48998. return device.createBindGroup( {
  48999. label: 'bindGroupCameraIndex_' + index,
  49000. layout,
  49001. entries
  49002. } );
  49003. }
  49004. /**
  49005. * Creates a GPU bind group for the given bind group and GPU layout.
  49006. *
  49007. * @param {BindGroup} bindGroup - The bind group.
  49008. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  49009. * @return {GPUBindGroup} The GPU bind group.
  49010. */
  49011. createBindGroup( bindGroup, layoutGPU ) {
  49012. const backend = this.backend;
  49013. const device = backend.device;
  49014. let bindingPoint = 0;
  49015. const entriesGPU = [];
  49016. for ( const binding of bindGroup.bindings ) {
  49017. if ( binding.isUniformBuffer ) {
  49018. const bindingData = backend.get( binding );
  49019. if ( bindingData.buffer === undefined ) {
  49020. const byteLength = binding.byteLength;
  49021. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  49022. const bufferGPU = device.createBuffer( {
  49023. label: 'bindingBuffer_' + binding.name,
  49024. size: byteLength,
  49025. usage: usage
  49026. } );
  49027. bindingData.buffer = bufferGPU;
  49028. }
  49029. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  49030. } else if ( binding.isStorageBuffer ) {
  49031. const bindingData = backend.get( binding );
  49032. if ( bindingData.buffer === undefined ) {
  49033. const attribute = binding.attribute;
  49034. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  49035. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  49036. bindingData.buffer = backend.get( attribute ).buffer;
  49037. }
  49038. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  49039. } else if ( binding.isSampler ) {
  49040. const textureGPU = backend.get( binding.texture );
  49041. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  49042. } else if ( binding.isSampledTexture ) {
  49043. const textureData = backend.get( binding.texture );
  49044. let resourceGPU;
  49045. if ( textureData.externalTexture !== undefined ) {
  49046. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  49047. } else {
  49048. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  49049. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  49050. resourceGPU = textureData[ propertyName ];
  49051. if ( resourceGPU === undefined ) {
  49052. const aspectGPU = GPUTextureAspect.All;
  49053. let dimensionViewGPU;
  49054. if ( binding.isSampledCubeTexture ) {
  49055. dimensionViewGPU = GPUTextureViewDimension.Cube;
  49056. } else if ( binding.isSampledTexture3D ) {
  49057. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  49058. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  49059. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  49060. } else {
  49061. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  49062. }
  49063. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  49064. }
  49065. }
  49066. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  49067. }
  49068. bindingPoint ++;
  49069. }
  49070. return device.createBindGroup( {
  49071. label: 'bindGroup_' + bindGroup.name,
  49072. layout: layoutGPU,
  49073. entries: entriesGPU
  49074. } );
  49075. }
  49076. }
  49077. /**
  49078. * A WebGPU backend utility module for managing pipelines.
  49079. *
  49080. * @private
  49081. */
  49082. class WebGPUPipelineUtils {
  49083. /**
  49084. * Constructs a new utility object.
  49085. *
  49086. * @param {WebGPUBackend} backend - The WebGPU backend.
  49087. */
  49088. constructor( backend ) {
  49089. /**
  49090. * A reference to the WebGPU backend.
  49091. *
  49092. * @type {WebGPUBackend}
  49093. */
  49094. this.backend = backend;
  49095. /**
  49096. * A Weak Map that tracks the active pipeline for render or compute passes.
  49097. *
  49098. * @private
  49099. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  49100. */
  49101. this._activePipelines = new WeakMap();
  49102. }
  49103. /**
  49104. * Sets the given pipeline for the given pass. The method makes sure to only set the
  49105. * pipeline when necessary.
  49106. *
  49107. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  49108. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  49109. */
  49110. setPipeline( pass, pipeline ) {
  49111. const currentPipeline = this._activePipelines.get( pass );
  49112. if ( currentPipeline !== pipeline ) {
  49113. pass.setPipeline( pipeline );
  49114. this._activePipelines.set( pass, pipeline );
  49115. }
  49116. }
  49117. /**
  49118. * Returns the sample count derived from the given render context.
  49119. *
  49120. * @private
  49121. * @param {RenderContext} renderContext - The render context.
  49122. * @return {number} The sample count.
  49123. */
  49124. _getSampleCount( renderContext ) {
  49125. return this.backend.utils.getSampleCountRenderContext( renderContext );
  49126. }
  49127. /**
  49128. * Creates a render pipeline for the given render object.
  49129. *
  49130. * @param {RenderObject} renderObject - The render object.
  49131. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  49132. */
  49133. createRenderPipeline( renderObject, promises ) {
  49134. const { object, material, geometry, pipeline } = renderObject;
  49135. const { vertexProgram, fragmentProgram } = pipeline;
  49136. const backend = this.backend;
  49137. const device = backend.device;
  49138. const utils = backend.utils;
  49139. const pipelineData = backend.get( pipeline );
  49140. // bind group layouts
  49141. const bindGroupLayouts = [];
  49142. for ( const bindGroup of renderObject.getBindings() ) {
  49143. const bindingsData = backend.get( bindGroup );
  49144. bindGroupLayouts.push( bindingsData.layout );
  49145. }
  49146. // vertex buffers
  49147. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  49148. // blending
  49149. let blending;
  49150. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  49151. blending = this._getBlending( material );
  49152. }
  49153. // stencil
  49154. let stencilFront = {};
  49155. if ( material.stencilWrite === true ) {
  49156. stencilFront = {
  49157. compare: this._getStencilCompare( material ),
  49158. failOp: this._getStencilOperation( material.stencilFail ),
  49159. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  49160. passOp: this._getStencilOperation( material.stencilZPass )
  49161. };
  49162. }
  49163. const colorWriteMask = this._getColorWriteMask( material );
  49164. const targets = [];
  49165. if ( renderObject.context.textures !== null ) {
  49166. const textures = renderObject.context.textures;
  49167. for ( let i = 0; i < textures.length; i ++ ) {
  49168. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  49169. targets.push( {
  49170. format: colorFormat,
  49171. blend: blending,
  49172. writeMask: colorWriteMask
  49173. } );
  49174. }
  49175. } else {
  49176. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  49177. targets.push( {
  49178. format: colorFormat,
  49179. blend: blending,
  49180. writeMask: colorWriteMask
  49181. } );
  49182. }
  49183. const vertexModule = backend.get( vertexProgram ).module;
  49184. const fragmentModule = backend.get( fragmentProgram ).module;
  49185. const primitiveState = this._getPrimitiveState( object, geometry, material );
  49186. const depthCompare = this._getDepthCompare( material );
  49187. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  49188. const sampleCount = this._getSampleCount( renderObject.context );
  49189. const pipelineDescriptor = {
  49190. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  49191. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  49192. fragment: Object.assign( {}, fragmentModule, { targets } ),
  49193. primitive: primitiveState,
  49194. multisample: {
  49195. count: sampleCount,
  49196. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  49197. },
  49198. layout: device.createPipelineLayout( {
  49199. bindGroupLayouts
  49200. } )
  49201. };
  49202. const depthStencil = {};
  49203. const renderDepth = renderObject.context.depth;
  49204. const renderStencil = renderObject.context.stencil;
  49205. if ( renderDepth === true || renderStencil === true ) {
  49206. if ( renderDepth === true ) {
  49207. depthStencil.format = depthStencilFormat;
  49208. depthStencil.depthWriteEnabled = material.depthWrite;
  49209. depthStencil.depthCompare = depthCompare;
  49210. }
  49211. if ( renderStencil === true ) {
  49212. depthStencil.stencilFront = stencilFront;
  49213. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  49214. depthStencil.stencilReadMask = material.stencilFuncMask;
  49215. depthStencil.stencilWriteMask = material.stencilWriteMask;
  49216. }
  49217. if ( material.polygonOffset === true ) {
  49218. depthStencil.depthBias = material.polygonOffsetUnits;
  49219. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  49220. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  49221. }
  49222. pipelineDescriptor.depthStencil = depthStencil;
  49223. }
  49224. if ( promises === null ) {
  49225. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  49226. } else {
  49227. const p = new Promise( ( resolve /*, reject*/ ) => {
  49228. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  49229. pipelineData.pipeline = pipeline;
  49230. resolve();
  49231. } );
  49232. } );
  49233. promises.push( p );
  49234. }
  49235. }
  49236. /**
  49237. * Creates GPU render bundle encoder for the given render context.
  49238. *
  49239. * @param {RenderContext} renderContext - The render context.
  49240. * @param {?string} [label='renderBundleEncoder'] - The label.
  49241. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  49242. */
  49243. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  49244. const backend = this.backend;
  49245. const { utils, device } = backend;
  49246. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  49247. const colorFormat = utils.getCurrentColorFormat( renderContext );
  49248. const sampleCount = this._getSampleCount( renderContext );
  49249. const descriptor = {
  49250. label: label,
  49251. colorFormats: [ colorFormat ],
  49252. depthStencilFormat,
  49253. sampleCount
  49254. };
  49255. return device.createRenderBundleEncoder( descriptor );
  49256. }
  49257. /**
  49258. * Creates a compute pipeline for the given compute node.
  49259. *
  49260. * @param {ComputePipeline} pipeline - The compute pipeline.
  49261. * @param {Array<BindGroup>} bindings - The bindings.
  49262. */
  49263. createComputePipeline( pipeline, bindings ) {
  49264. const backend = this.backend;
  49265. const device = backend.device;
  49266. const computeProgram = backend.get( pipeline.computeProgram ).module;
  49267. const pipelineGPU = backend.get( pipeline );
  49268. // bind group layouts
  49269. const bindGroupLayouts = [];
  49270. for ( const bindingsGroup of bindings ) {
  49271. const bindingsData = backend.get( bindingsGroup );
  49272. bindGroupLayouts.push( bindingsData.layout );
  49273. }
  49274. pipelineGPU.pipeline = device.createComputePipeline( {
  49275. compute: computeProgram,
  49276. layout: device.createPipelineLayout( {
  49277. bindGroupLayouts
  49278. } )
  49279. } );
  49280. }
  49281. /**
  49282. * Returns the blending state as a descriptor object required
  49283. * for the pipeline creation.
  49284. *
  49285. * @private
  49286. * @param {Material} material - The material.
  49287. * @return {Object} The blending state.
  49288. */
  49289. _getBlending( material ) {
  49290. let color, alpha;
  49291. const blending = material.blending;
  49292. const blendSrc = material.blendSrc;
  49293. const blendDst = material.blendDst;
  49294. const blendEquation = material.blendEquation;
  49295. if ( blending === CustomBlending ) {
  49296. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  49297. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  49298. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  49299. color = {
  49300. srcFactor: this._getBlendFactor( blendSrc ),
  49301. dstFactor: this._getBlendFactor( blendDst ),
  49302. operation: this._getBlendOperation( blendEquation )
  49303. };
  49304. alpha = {
  49305. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  49306. dstFactor: this._getBlendFactor( blendDstAlpha ),
  49307. operation: this._getBlendOperation( blendEquationAlpha )
  49308. };
  49309. } else {
  49310. const premultipliedAlpha = material.premultipliedAlpha;
  49311. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  49312. color = {
  49313. srcFactor: srcRGB,
  49314. dstFactor: dstRGB,
  49315. operation: GPUBlendOperation.Add
  49316. };
  49317. alpha = {
  49318. srcFactor: srcAlpha,
  49319. dstFactor: dstAlpha,
  49320. operation: GPUBlendOperation.Add
  49321. };
  49322. };
  49323. if ( premultipliedAlpha ) {
  49324. switch ( blending ) {
  49325. case NormalBlending:
  49326. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  49327. break;
  49328. case AdditiveBlending:
  49329. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  49330. break;
  49331. case SubtractiveBlending:
  49332. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  49333. break;
  49334. case MultiplyBlending:
  49335. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  49336. break;
  49337. }
  49338. } else {
  49339. switch ( blending ) {
  49340. case NormalBlending:
  49341. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  49342. break;
  49343. case AdditiveBlending:
  49344. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  49345. break;
  49346. case SubtractiveBlending:
  49347. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  49348. break;
  49349. case MultiplyBlending:
  49350. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  49351. break;
  49352. }
  49353. }
  49354. }
  49355. if ( color !== undefined && alpha !== undefined ) {
  49356. return { color, alpha };
  49357. } else {
  49358. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  49359. }
  49360. }
  49361. /**
  49362. * Returns the GPU blend factor which is required for the pipeline creation.
  49363. *
  49364. * @private
  49365. * @param {number} blend - The blend factor as a three.js constant.
  49366. * @return {string} The GPU blend factor.
  49367. */
  49368. _getBlendFactor( blend ) {
  49369. let blendFactor;
  49370. switch ( blend ) {
  49371. case ZeroFactor:
  49372. blendFactor = GPUBlendFactor.Zero;
  49373. break;
  49374. case OneFactor:
  49375. blendFactor = GPUBlendFactor.One;
  49376. break;
  49377. case SrcColorFactor:
  49378. blendFactor = GPUBlendFactor.Src;
  49379. break;
  49380. case OneMinusSrcColorFactor:
  49381. blendFactor = GPUBlendFactor.OneMinusSrc;
  49382. break;
  49383. case SrcAlphaFactor:
  49384. blendFactor = GPUBlendFactor.SrcAlpha;
  49385. break;
  49386. case OneMinusSrcAlphaFactor:
  49387. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  49388. break;
  49389. case DstColorFactor:
  49390. blendFactor = GPUBlendFactor.Dst;
  49391. break;
  49392. case OneMinusDstColorFactor:
  49393. blendFactor = GPUBlendFactor.OneMinusDstColor;
  49394. break;
  49395. case DstAlphaFactor:
  49396. blendFactor = GPUBlendFactor.DstAlpha;
  49397. break;
  49398. case OneMinusDstAlphaFactor:
  49399. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  49400. break;
  49401. case SrcAlphaSaturateFactor:
  49402. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  49403. break;
  49404. case BlendColorFactor:
  49405. blendFactor = GPUBlendFactor.Constant;
  49406. break;
  49407. case OneMinusBlendColorFactor:
  49408. blendFactor = GPUBlendFactor.OneMinusConstant;
  49409. break;
  49410. default:
  49411. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  49412. }
  49413. return blendFactor;
  49414. }
  49415. /**
  49416. * Returns the GPU stencil compare function which is required for the pipeline creation.
  49417. *
  49418. * @private
  49419. * @param {Material} material - The material.
  49420. * @return {string} The GPU stencil compare function.
  49421. */
  49422. _getStencilCompare( material ) {
  49423. let stencilCompare;
  49424. const stencilFunc = material.stencilFunc;
  49425. switch ( stencilFunc ) {
  49426. case NeverStencilFunc:
  49427. stencilCompare = GPUCompareFunction.Never;
  49428. break;
  49429. case AlwaysStencilFunc:
  49430. stencilCompare = GPUCompareFunction.Always;
  49431. break;
  49432. case LessStencilFunc:
  49433. stencilCompare = GPUCompareFunction.Less;
  49434. break;
  49435. case LessEqualStencilFunc:
  49436. stencilCompare = GPUCompareFunction.LessEqual;
  49437. break;
  49438. case EqualStencilFunc:
  49439. stencilCompare = GPUCompareFunction.Equal;
  49440. break;
  49441. case GreaterEqualStencilFunc:
  49442. stencilCompare = GPUCompareFunction.GreaterEqual;
  49443. break;
  49444. case GreaterStencilFunc:
  49445. stencilCompare = GPUCompareFunction.Greater;
  49446. break;
  49447. case NotEqualStencilFunc:
  49448. stencilCompare = GPUCompareFunction.NotEqual;
  49449. break;
  49450. default:
  49451. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  49452. }
  49453. return stencilCompare;
  49454. }
  49455. /**
  49456. * Returns the GPU stencil operation which is required for the pipeline creation.
  49457. *
  49458. * @private
  49459. * @param {number} op - A three.js constant defining the stencil operation.
  49460. * @return {string} The GPU stencil operation.
  49461. */
  49462. _getStencilOperation( op ) {
  49463. let stencilOperation;
  49464. switch ( op ) {
  49465. case KeepStencilOp:
  49466. stencilOperation = GPUStencilOperation.Keep;
  49467. break;
  49468. case ZeroStencilOp:
  49469. stencilOperation = GPUStencilOperation.Zero;
  49470. break;
  49471. case ReplaceStencilOp:
  49472. stencilOperation = GPUStencilOperation.Replace;
  49473. break;
  49474. case InvertStencilOp:
  49475. stencilOperation = GPUStencilOperation.Invert;
  49476. break;
  49477. case IncrementStencilOp:
  49478. stencilOperation = GPUStencilOperation.IncrementClamp;
  49479. break;
  49480. case DecrementStencilOp:
  49481. stencilOperation = GPUStencilOperation.DecrementClamp;
  49482. break;
  49483. case IncrementWrapStencilOp:
  49484. stencilOperation = GPUStencilOperation.IncrementWrap;
  49485. break;
  49486. case DecrementWrapStencilOp:
  49487. stencilOperation = GPUStencilOperation.DecrementWrap;
  49488. break;
  49489. default:
  49490. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  49491. }
  49492. return stencilOperation;
  49493. }
  49494. /**
  49495. * Returns the GPU blend operation which is required for the pipeline creation.
  49496. *
  49497. * @private
  49498. * @param {number} blendEquation - A three.js constant defining the blend equation.
  49499. * @return {string} The GPU blend operation.
  49500. */
  49501. _getBlendOperation( blendEquation ) {
  49502. let blendOperation;
  49503. switch ( blendEquation ) {
  49504. case AddEquation:
  49505. blendOperation = GPUBlendOperation.Add;
  49506. break;
  49507. case SubtractEquation:
  49508. blendOperation = GPUBlendOperation.Subtract;
  49509. break;
  49510. case ReverseSubtractEquation:
  49511. blendOperation = GPUBlendOperation.ReverseSubtract;
  49512. break;
  49513. case MinEquation:
  49514. blendOperation = GPUBlendOperation.Min;
  49515. break;
  49516. case MaxEquation:
  49517. blendOperation = GPUBlendOperation.Max;
  49518. break;
  49519. default:
  49520. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  49521. }
  49522. return blendOperation;
  49523. }
  49524. /**
  49525. * Returns the primitive state as a descriptor object required
  49526. * for the pipeline creation.
  49527. *
  49528. * @private
  49529. * @param {Object3D} object - The 3D object.
  49530. * @param {BufferGeometry} geometry - The geometry.
  49531. * @param {Material} material - The material.
  49532. * @return {Object} The primitive state.
  49533. */
  49534. _getPrimitiveState( object, geometry, material ) {
  49535. const descriptor = {};
  49536. const utils = this.backend.utils;
  49537. descriptor.topology = utils.getPrimitiveTopology( object, material );
  49538. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  49539. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  49540. }
  49541. switch ( material.side ) {
  49542. case FrontSide:
  49543. descriptor.frontFace = GPUFrontFace.CCW;
  49544. descriptor.cullMode = GPUCullMode.Back;
  49545. break;
  49546. case BackSide:
  49547. descriptor.frontFace = GPUFrontFace.CCW;
  49548. descriptor.cullMode = GPUCullMode.Front;
  49549. break;
  49550. case DoubleSide:
  49551. descriptor.frontFace = GPUFrontFace.CCW;
  49552. descriptor.cullMode = GPUCullMode.None;
  49553. break;
  49554. default:
  49555. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  49556. break;
  49557. }
  49558. return descriptor;
  49559. }
  49560. /**
  49561. * Returns the GPU color write mask which is required for the pipeline creation.
  49562. *
  49563. * @private
  49564. * @param {Material} material - The material.
  49565. * @return {string} The GPU color write mask.
  49566. */
  49567. _getColorWriteMask( material ) {
  49568. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  49569. }
  49570. /**
  49571. * Returns the GPU depth compare function which is required for the pipeline creation.
  49572. *
  49573. * @private
  49574. * @param {Material} material - The material.
  49575. * @return {string} The GPU depth compare function.
  49576. */
  49577. _getDepthCompare( material ) {
  49578. let depthCompare;
  49579. if ( material.depthTest === false ) {
  49580. depthCompare = GPUCompareFunction.Always;
  49581. } else {
  49582. const depthFunc = material.depthFunc;
  49583. switch ( depthFunc ) {
  49584. case NeverDepth:
  49585. depthCompare = GPUCompareFunction.Never;
  49586. break;
  49587. case AlwaysDepth:
  49588. depthCompare = GPUCompareFunction.Always;
  49589. break;
  49590. case LessDepth:
  49591. depthCompare = GPUCompareFunction.Less;
  49592. break;
  49593. case LessEqualDepth:
  49594. depthCompare = GPUCompareFunction.LessEqual;
  49595. break;
  49596. case EqualDepth:
  49597. depthCompare = GPUCompareFunction.Equal;
  49598. break;
  49599. case GreaterEqualDepth:
  49600. depthCompare = GPUCompareFunction.GreaterEqual;
  49601. break;
  49602. case GreaterDepth:
  49603. depthCompare = GPUCompareFunction.Greater;
  49604. break;
  49605. case NotEqualDepth:
  49606. depthCompare = GPUCompareFunction.NotEqual;
  49607. break;
  49608. default:
  49609. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  49610. }
  49611. }
  49612. return depthCompare;
  49613. }
  49614. }
  49615. /**
  49616. * Manages a pool of WebGPU timestamp queries for performance measurement.
  49617. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  49618. *
  49619. * @augments TimestampQueryPool
  49620. */
  49621. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  49622. /**
  49623. * Creates a new WebGPU timestamp query pool.
  49624. *
  49625. * @param {GPUDevice} device - The WebGPU device to create queries on.
  49626. * @param {string} type - The type identifier for this query pool.
  49627. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  49628. */
  49629. constructor( device, type, maxQueries = 2048 ) {
  49630. super( maxQueries );
  49631. this.device = device;
  49632. this.type = type;
  49633. this.querySet = this.device.createQuerySet( {
  49634. type: 'timestamp',
  49635. count: this.maxQueries,
  49636. label: `queryset_global_timestamp_${type}`
  49637. } );
  49638. const bufferSize = this.maxQueries * 8;
  49639. this.resolveBuffer = this.device.createBuffer( {
  49640. label: `buffer_timestamp_resolve_${type}`,
  49641. size: bufferSize,
  49642. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  49643. } );
  49644. this.resultBuffer = this.device.createBuffer( {
  49645. label: `buffer_timestamp_result_${type}`,
  49646. size: bufferSize,
  49647. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  49648. } );
  49649. }
  49650. /**
  49651. * Allocates a pair of queries for a given render context.
  49652. *
  49653. * @param {Object} renderContext - The render context to allocate queries for.
  49654. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  49655. */
  49656. allocateQueriesForContext( renderContext ) {
  49657. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  49658. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  49659. warnOnce( `WebGPUTimestampQueryPool [${ this.type }]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${ this.type.toUpperCase() } ).` );
  49660. return null;
  49661. }
  49662. const baseOffset = this.currentQueryIndex;
  49663. this.currentQueryIndex += 2;
  49664. this.queryOffsets.set( renderContext.id, baseOffset );
  49665. return baseOffset;
  49666. }
  49667. /**
  49668. * Asynchronously resolves all pending queries and returns the total duration.
  49669. * If there's already a pending resolve operation, returns that promise instead.
  49670. *
  49671. * @async
  49672. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  49673. */
  49674. async resolveQueriesAsync() {
  49675. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  49676. return this.lastValue;
  49677. }
  49678. if ( this.pendingResolve ) {
  49679. return this.pendingResolve;
  49680. }
  49681. this.pendingResolve = this._resolveQueries();
  49682. try {
  49683. const result = await this.pendingResolve;
  49684. return result;
  49685. } finally {
  49686. this.pendingResolve = null;
  49687. }
  49688. }
  49689. /**
  49690. * Internal method to resolve queries and calculate total duration.
  49691. *
  49692. * @async
  49693. * @private
  49694. * @returns {Promise<number>} The total duration in milliseconds.
  49695. */
  49696. async _resolveQueries() {
  49697. if ( this.isDisposed ) {
  49698. return this.lastValue;
  49699. }
  49700. try {
  49701. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  49702. return this.lastValue;
  49703. }
  49704. const currentOffsets = new Map( this.queryOffsets );
  49705. const queryCount = this.currentQueryIndex;
  49706. const bytesUsed = queryCount * 8;
  49707. // Reset state before GPU work
  49708. this.currentQueryIndex = 0;
  49709. this.queryOffsets.clear();
  49710. const commandEncoder = this.device.createCommandEncoder();
  49711. commandEncoder.resolveQuerySet(
  49712. this.querySet,
  49713. 0,
  49714. queryCount,
  49715. this.resolveBuffer,
  49716. 0
  49717. );
  49718. commandEncoder.copyBufferToBuffer(
  49719. this.resolveBuffer,
  49720. 0,
  49721. this.resultBuffer,
  49722. 0,
  49723. bytesUsed
  49724. );
  49725. const commandBuffer = commandEncoder.finish();
  49726. this.device.queue.submit( [ commandBuffer ] );
  49727. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  49728. return this.lastValue;
  49729. }
  49730. // Create and track the mapping operation
  49731. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  49732. if ( this.isDisposed ) {
  49733. if ( this.resultBuffer.mapState === 'mapped' ) {
  49734. this.resultBuffer.unmap();
  49735. }
  49736. return this.lastValue;
  49737. }
  49738. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  49739. let totalDuration = 0;
  49740. for ( const [ , baseOffset ] of currentOffsets ) {
  49741. const startTime = times[ baseOffset ];
  49742. const endTime = times[ baseOffset + 1 ];
  49743. const duration = Number( endTime - startTime ) / 1e6;
  49744. totalDuration += duration;
  49745. }
  49746. this.resultBuffer.unmap();
  49747. this.lastValue = totalDuration;
  49748. return totalDuration;
  49749. } catch ( error ) {
  49750. console.error( 'Error resolving queries:', error );
  49751. if ( this.resultBuffer.mapState === 'mapped' ) {
  49752. this.resultBuffer.unmap();
  49753. }
  49754. return this.lastValue;
  49755. }
  49756. }
  49757. /**
  49758. * Dispose of the query pool.
  49759. *
  49760. * @async
  49761. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  49762. */
  49763. async dispose() {
  49764. if ( this.isDisposed ) {
  49765. return;
  49766. }
  49767. this.isDisposed = true;
  49768. // Wait for pending resolve operation
  49769. if ( this.pendingResolve ) {
  49770. try {
  49771. await this.pendingResolve;
  49772. } catch ( error ) {
  49773. console.error( 'Error waiting for pending resolve:', error );
  49774. }
  49775. }
  49776. // Ensure buffer is unmapped before destroying
  49777. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  49778. try {
  49779. this.resultBuffer.unmap();
  49780. } catch ( error ) {
  49781. console.error( 'Error unmapping buffer:', error );
  49782. }
  49783. }
  49784. // Destroy resources
  49785. if ( this.querySet ) {
  49786. this.querySet.destroy();
  49787. this.querySet = null;
  49788. }
  49789. if ( this.resolveBuffer ) {
  49790. this.resolveBuffer.destroy();
  49791. this.resolveBuffer = null;
  49792. }
  49793. if ( this.resultBuffer ) {
  49794. this.resultBuffer.destroy();
  49795. this.resultBuffer = null;
  49796. }
  49797. this.queryOffsets.clear();
  49798. this.pendingResolve = null;
  49799. }
  49800. }
  49801. /*// debugger tools
  49802. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  49803. //*/
  49804. /**
  49805. * A backend implementation targeting WebGPU.
  49806. *
  49807. * @private
  49808. * @augments Backend
  49809. */
  49810. class WebGPUBackend extends Backend {
  49811. /**
  49812. * WebGPUBackend options.
  49813. *
  49814. * @typedef {Object} WebGPUBackend~Options
  49815. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  49816. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  49817. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  49818. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  49819. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  49820. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  49821. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  49822. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  49823. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  49824. * @property {string} [powerPreference=undefined] - The power preference.
  49825. * @property {Object} [requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  49826. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  49827. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  49828. */
  49829. /**
  49830. * Constructs a new WebGPU backend.
  49831. *
  49832. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  49833. */
  49834. constructor( parameters = {} ) {
  49835. super( parameters );
  49836. /**
  49837. * This flag can be used for type testing.
  49838. *
  49839. * @type {boolean}
  49840. * @readonly
  49841. * @default true
  49842. */
  49843. this.isWebGPUBackend = true;
  49844. // some parameters require default values other than "undefined"
  49845. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  49846. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  49847. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  49848. /**
  49849. * Indicates whether the backend is in compatibility mode or not.
  49850. * @type {boolean}
  49851. * @default false
  49852. */
  49853. this.compatibilityMode = this.parameters.compatibilityMode;
  49854. /**
  49855. * A reference to the device.
  49856. *
  49857. * @type {?GPUDevice}
  49858. * @default null
  49859. */
  49860. this.device = null;
  49861. /**
  49862. * A reference to the context.
  49863. *
  49864. * @type {?GPUCanvasContext}
  49865. * @default null
  49866. */
  49867. this.context = null;
  49868. /**
  49869. * A reference to the color attachment of the default framebuffer.
  49870. *
  49871. * @type {?GPUTexture}
  49872. * @default null
  49873. */
  49874. this.colorBuffer = null;
  49875. /**
  49876. * A reference to the default render pass descriptor.
  49877. *
  49878. * @type {?Object}
  49879. * @default null
  49880. */
  49881. this.defaultRenderPassdescriptor = null;
  49882. /**
  49883. * A reference to a backend module holding common utility functions.
  49884. *
  49885. * @type {WebGPUUtils}
  49886. */
  49887. this.utils = new WebGPUUtils( this );
  49888. /**
  49889. * A reference to a backend module holding shader attribute-related
  49890. * utility functions.
  49891. *
  49892. * @type {WebGPUAttributeUtils}
  49893. */
  49894. this.attributeUtils = new WebGPUAttributeUtils( this );
  49895. /**
  49896. * A reference to a backend module holding shader binding-related
  49897. * utility functions.
  49898. *
  49899. * @type {WebGPUBindingUtils}
  49900. */
  49901. this.bindingUtils = new WebGPUBindingUtils( this );
  49902. /**
  49903. * A reference to a backend module holding shader pipeline-related
  49904. * utility functions.
  49905. *
  49906. * @type {WebGPUPipelineUtils}
  49907. */
  49908. this.pipelineUtils = new WebGPUPipelineUtils( this );
  49909. /**
  49910. * A reference to a backend module holding shader texture-related
  49911. * utility functions.
  49912. *
  49913. * @type {WebGPUTextureUtils}
  49914. */
  49915. this.textureUtils = new WebGPUTextureUtils( this );
  49916. /**
  49917. * A map that manages the resolve buffers for occlusion queries.
  49918. *
  49919. * @type {Map<number,GPUBuffer>}
  49920. */
  49921. this.occludedResolveCache = new Map();
  49922. }
  49923. /**
  49924. * Initializes the backend so it is ready for usage.
  49925. *
  49926. * @async
  49927. * @param {Renderer} renderer - The renderer.
  49928. * @return {Promise} A Promise that resolves when the backend has been initialized.
  49929. */
  49930. async init( renderer ) {
  49931. await super.init( renderer );
  49932. //
  49933. const parameters = this.parameters;
  49934. // create the device if it is not passed with parameters
  49935. let device;
  49936. if ( parameters.device === undefined ) {
  49937. const adapterOptions = {
  49938. powerPreference: parameters.powerPreference,
  49939. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  49940. };
  49941. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  49942. if ( adapter === null ) {
  49943. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  49944. }
  49945. // feature support
  49946. const features = Object.values( GPUFeatureName );
  49947. const supportedFeatures = [];
  49948. for ( const name of features ) {
  49949. if ( adapter.features.has( name ) ) {
  49950. supportedFeatures.push( name );
  49951. }
  49952. }
  49953. const deviceDescriptor = {
  49954. requiredFeatures: supportedFeatures,
  49955. requiredLimits: parameters.requiredLimits
  49956. };
  49957. device = await adapter.requestDevice( deviceDescriptor );
  49958. } else {
  49959. device = parameters.device;
  49960. }
  49961. device.lost.then( ( info ) => {
  49962. const deviceLossInfo = {
  49963. api: 'WebGPU',
  49964. message: info.message || 'Unknown reason',
  49965. reason: info.reason || null,
  49966. originalEvent: info
  49967. };
  49968. renderer.onDeviceLost( deviceLossInfo );
  49969. } );
  49970. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  49971. this.device = device;
  49972. this.context = context;
  49973. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  49974. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  49975. this.context.configure( {
  49976. device: this.device,
  49977. format: this.utils.getPreferredCanvasFormat(),
  49978. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  49979. alphaMode: alphaMode
  49980. } );
  49981. this.updateSize();
  49982. }
  49983. /**
  49984. * The coordinate system of the backend.
  49985. *
  49986. * @type {number}
  49987. * @readonly
  49988. */
  49989. get coordinateSystem() {
  49990. return WebGPUCoordinateSystem;
  49991. }
  49992. /**
  49993. * This method performs a readback operation by moving buffer data from
  49994. * a storage buffer attribute from the GPU to the CPU.
  49995. *
  49996. * @async
  49997. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  49998. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  49999. */
  50000. async getArrayBufferAsync( attribute ) {
  50001. return await this.attributeUtils.getArrayBufferAsync( attribute );
  50002. }
  50003. /**
  50004. * Returns the backend's rendering context.
  50005. *
  50006. * @return {GPUCanvasContext} The rendering context.
  50007. */
  50008. getContext() {
  50009. return this.context;
  50010. }
  50011. /**
  50012. * Returns the default render pass descriptor.
  50013. *
  50014. * In WebGPU, the default framebuffer must be configured
  50015. * like custom framebuffers so the backend needs a render
  50016. * pass descriptor even when rendering directly to screen.
  50017. *
  50018. * @private
  50019. * @return {Object} The render pass descriptor.
  50020. */
  50021. _getDefaultRenderPassDescriptor() {
  50022. let descriptor = this.defaultRenderPassdescriptor;
  50023. if ( descriptor === null ) {
  50024. const renderer = this.renderer;
  50025. descriptor = {
  50026. colorAttachments: [ {
  50027. view: null
  50028. } ],
  50029. };
  50030. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  50031. descriptor.depthStencilAttachment = {
  50032. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  50033. };
  50034. }
  50035. const colorAttachment = descriptor.colorAttachments[ 0 ];
  50036. if ( this.renderer.samples > 0 ) {
  50037. colorAttachment.view = this.colorBuffer.createView();
  50038. } else {
  50039. colorAttachment.resolveTarget = undefined;
  50040. }
  50041. this.defaultRenderPassdescriptor = descriptor;
  50042. }
  50043. const colorAttachment = descriptor.colorAttachments[ 0 ];
  50044. if ( this.renderer.samples > 0 ) {
  50045. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  50046. } else {
  50047. colorAttachment.view = this.context.getCurrentTexture().createView();
  50048. }
  50049. return descriptor;
  50050. }
  50051. /**
  50052. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  50053. *
  50054. * @param {RenderContext} renderContext - The render context.
  50055. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  50056. *
  50057. * @private
  50058. */
  50059. _isRenderCameraDepthArray( renderContext ) {
  50060. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  50061. }
  50062. /**
  50063. * Returns the render pass descriptor for the given render context.
  50064. *
  50065. * @private
  50066. * @param {RenderContext} renderContext - The render context.
  50067. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  50068. * @return {Object} The render pass descriptor.
  50069. */
  50070. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  50071. const renderTarget = renderContext.renderTarget;
  50072. const renderTargetData = this.get( renderTarget );
  50073. let descriptors = renderTargetData.descriptors;
  50074. if ( descriptors === undefined ||
  50075. renderTargetData.width !== renderTarget.width ||
  50076. renderTargetData.height !== renderTarget.height ||
  50077. renderTargetData.dimensions !== renderTarget.dimensions ||
  50078. renderTargetData.activeMipmapLevel !== renderContext.activeMipmapLevel ||
  50079. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  50080. renderTargetData.samples !== renderTarget.samples
  50081. ) {
  50082. descriptors = {};
  50083. renderTargetData.descriptors = descriptors;
  50084. // dispose
  50085. const onDispose = () => {
  50086. renderTarget.removeEventListener( 'dispose', onDispose );
  50087. this.delete( renderTarget );
  50088. };
  50089. if ( renderTarget.hasEventListener( 'dispose', onDispose ) === false ) {
  50090. renderTarget.addEventListener( 'dispose', onDispose );
  50091. }
  50092. }
  50093. const cacheKey = renderContext.getCacheKey();
  50094. let descriptorBase = descriptors[ cacheKey ];
  50095. if ( descriptorBase === undefined ) {
  50096. const textures = renderContext.textures;
  50097. const textureViews = [];
  50098. let sliceIndex;
  50099. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  50100. for ( let i = 0; i < textures.length; i ++ ) {
  50101. const textureData = this.get( textures[ i ] );
  50102. const viewDescriptor = {
  50103. label: `colorAttachment_${ i }`,
  50104. baseMipLevel: renderContext.activeMipmapLevel,
  50105. mipLevelCount: 1,
  50106. baseArrayLayer: renderContext.activeCubeFace,
  50107. arrayLayerCount: 1,
  50108. dimension: GPUTextureViewDimension.TwoD
  50109. };
  50110. if ( renderTarget.isRenderTarget3D ) {
  50111. sliceIndex = renderContext.activeCubeFace;
  50112. viewDescriptor.baseArrayLayer = 0;
  50113. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  50114. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  50115. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  50116. if ( isRenderCameraDepthArray === true ) {
  50117. const cameras = renderContext.camera.cameras;
  50118. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  50119. const layerViewDescriptor = {
  50120. ...viewDescriptor,
  50121. baseArrayLayer: layer,
  50122. arrayLayerCount: 1,
  50123. dimension: GPUTextureViewDimension.TwoD
  50124. };
  50125. const textureView = textureData.texture.createView( layerViewDescriptor );
  50126. textureViews.push( {
  50127. view: textureView,
  50128. resolveTarget: undefined,
  50129. depthSlice: undefined
  50130. } );
  50131. }
  50132. } else {
  50133. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  50134. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  50135. }
  50136. }
  50137. if ( isRenderCameraDepthArray !== true ) {
  50138. const textureView = textureData.texture.createView( viewDescriptor );
  50139. let view, resolveTarget;
  50140. if ( textureData.msaaTexture !== undefined ) {
  50141. view = textureData.msaaTexture.createView();
  50142. resolveTarget = textureView;
  50143. } else {
  50144. view = textureView;
  50145. resolveTarget = undefined;
  50146. }
  50147. textureViews.push( {
  50148. view,
  50149. resolveTarget,
  50150. depthSlice: sliceIndex
  50151. } );
  50152. }
  50153. }
  50154. descriptorBase = { textureViews };
  50155. if ( renderContext.depth ) {
  50156. const depthTextureData = this.get( renderContext.depthTexture );
  50157. const options = {};
  50158. if ( renderContext.depthTexture.isArrayTexture ) {
  50159. options.dimension = GPUTextureViewDimension.TwoD;
  50160. options.arrayLayerCount = 1;
  50161. options.baseArrayLayer = renderContext.activeCubeFace;
  50162. }
  50163. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  50164. }
  50165. descriptors[ cacheKey ] = descriptorBase;
  50166. renderTargetData.width = renderTarget.width;
  50167. renderTargetData.height = renderTarget.height;
  50168. renderTargetData.samples = renderTarget.samples;
  50169. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  50170. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  50171. renderTargetData.dimensions = renderTarget.dimensions;
  50172. }
  50173. const descriptor = {
  50174. colorAttachments: []
  50175. };
  50176. // Apply dynamic properties to cached views
  50177. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  50178. const viewInfo = descriptorBase.textureViews[ i ];
  50179. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  50180. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  50181. clearValue = colorAttachmentsConfig.clearValue;
  50182. }
  50183. descriptor.colorAttachments.push( {
  50184. view: viewInfo.view,
  50185. depthSlice: viewInfo.depthSlice,
  50186. resolveTarget: viewInfo.resolveTarget,
  50187. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  50188. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  50189. clearValue: clearValue
  50190. } );
  50191. }
  50192. if ( descriptorBase.depthStencilView ) {
  50193. descriptor.depthStencilAttachment = {
  50194. view: descriptorBase.depthStencilView
  50195. };
  50196. }
  50197. return descriptor;
  50198. }
  50199. /**
  50200. * This method is executed at the beginning of a render call and prepares
  50201. * the WebGPU state for upcoming render calls
  50202. *
  50203. * @param {RenderContext} renderContext - The render context.
  50204. */
  50205. beginRender( renderContext ) {
  50206. const renderContextData = this.get( renderContext );
  50207. const device = this.device;
  50208. const occlusionQueryCount = renderContext.occlusionQueryCount;
  50209. let occlusionQuerySet;
  50210. if ( occlusionQueryCount > 0 ) {
  50211. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  50212. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  50213. // Get a reference to the array of objects with queries. The renderContextData property
  50214. // can be changed by another render pass before the buffer.mapAsyc() completes.
  50215. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  50216. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  50217. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  50218. //
  50219. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  50220. renderContextData.occlusionQuerySet = occlusionQuerySet;
  50221. renderContextData.occlusionQueryIndex = 0;
  50222. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  50223. renderContextData.lastOcclusionObject = null;
  50224. }
  50225. let descriptor;
  50226. if ( renderContext.textures === null ) {
  50227. descriptor = this._getDefaultRenderPassDescriptor();
  50228. } else {
  50229. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  50230. }
  50231. this.initTimestampQuery( renderContext, descriptor );
  50232. descriptor.occlusionQuerySet = occlusionQuerySet;
  50233. const depthStencilAttachment = descriptor.depthStencilAttachment;
  50234. if ( renderContext.textures !== null ) {
  50235. const colorAttachments = descriptor.colorAttachments;
  50236. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  50237. const colorAttachment = colorAttachments[ i ];
  50238. if ( renderContext.clearColor ) {
  50239. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  50240. colorAttachment.loadOp = GPULoadOp.Clear;
  50241. } else {
  50242. colorAttachment.loadOp = GPULoadOp.Load;
  50243. }
  50244. colorAttachment.storeOp = GPUStoreOp.Store;
  50245. }
  50246. } else {
  50247. const colorAttachment = descriptor.colorAttachments[ 0 ];
  50248. if ( renderContext.clearColor ) {
  50249. colorAttachment.clearValue = renderContext.clearColorValue;
  50250. colorAttachment.loadOp = GPULoadOp.Clear;
  50251. } else {
  50252. colorAttachment.loadOp = GPULoadOp.Load;
  50253. }
  50254. colorAttachment.storeOp = GPUStoreOp.Store;
  50255. }
  50256. //
  50257. if ( renderContext.depth ) {
  50258. if ( renderContext.clearDepth ) {
  50259. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  50260. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  50261. } else {
  50262. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  50263. }
  50264. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50265. }
  50266. if ( renderContext.stencil ) {
  50267. if ( renderContext.clearStencil ) {
  50268. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  50269. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  50270. } else {
  50271. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  50272. }
  50273. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50274. }
  50275. //
  50276. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  50277. // shadow arrays - prepare bundle encoders for each camera in an array camera
  50278. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  50279. const cameras = renderContext.camera.cameras;
  50280. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  50281. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  50282. } else {
  50283. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  50284. }
  50285. // Create bundle encoders for each layer
  50286. renderContextData.bundleEncoders = [];
  50287. renderContextData.bundleSets = [];
  50288. // Create separate bundle encoders for each camera in the array
  50289. for ( let i = 0; i < cameras.length; i ++ ) {
  50290. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  50291. renderContext,
  50292. 'renderBundleArrayCamera_' + i
  50293. );
  50294. // Initialize state tracking for this bundle
  50295. const bundleSets = {
  50296. attributes: {},
  50297. bindingGroups: [],
  50298. pipeline: null,
  50299. index: null
  50300. };
  50301. renderContextData.bundleEncoders.push( bundleEncoder );
  50302. renderContextData.bundleSets.push( bundleSets );
  50303. }
  50304. // We'll complete the bundles in finishRender
  50305. renderContextData.currentPass = null;
  50306. } else {
  50307. const currentPass = encoder.beginRenderPass( descriptor );
  50308. renderContextData.currentPass = currentPass;
  50309. if ( renderContext.viewport ) {
  50310. this.updateViewport( renderContext );
  50311. }
  50312. if ( renderContext.scissor ) {
  50313. const { x, y, width, height } = renderContext.scissorValue;
  50314. currentPass.setScissorRect( x, y, width, height );
  50315. }
  50316. }
  50317. //
  50318. renderContextData.descriptor = descriptor;
  50319. renderContextData.encoder = encoder;
  50320. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  50321. renderContextData.renderBundles = [];
  50322. }
  50323. /**
  50324. * This method creates layer descriptors for each camera in an array camera
  50325. * to prepare for rendering to a depth array texture.
  50326. *
  50327. * @param {RenderContext} renderContext - The render context.
  50328. * @param {Object} renderContextData - The render context data.
  50329. * @param {Object} descriptor - The render pass descriptor.
  50330. * @param {ArrayCamera} cameras - The array camera.
  50331. *
  50332. * @private
  50333. */
  50334. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  50335. const depthStencilAttachment = descriptor.depthStencilAttachment;
  50336. renderContextData.layerDescriptors = [];
  50337. const depthTextureData = this.get( renderContext.depthTexture );
  50338. if ( ! depthTextureData.viewCache ) {
  50339. depthTextureData.viewCache = [];
  50340. }
  50341. for ( let i = 0; i < cameras.length; i ++ ) {
  50342. const layerDescriptor = {
  50343. ...descriptor,
  50344. colorAttachments: [ {
  50345. ...descriptor.colorAttachments[ 0 ],
  50346. view: descriptor.colorAttachments[ i ].view
  50347. } ]
  50348. };
  50349. if ( descriptor.depthStencilAttachment ) {
  50350. const layerIndex = i;
  50351. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  50352. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  50353. dimension: GPUTextureViewDimension.TwoD,
  50354. baseArrayLayer: i,
  50355. arrayLayerCount: 1
  50356. } );
  50357. }
  50358. layerDescriptor.depthStencilAttachment = {
  50359. view: depthTextureData.viewCache[ layerIndex ],
  50360. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  50361. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  50362. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  50363. };
  50364. if ( renderContext.stencil ) {
  50365. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  50366. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  50367. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  50368. }
  50369. } else {
  50370. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  50371. }
  50372. renderContextData.layerDescriptors.push( layerDescriptor );
  50373. }
  50374. }
  50375. /**
  50376. * This method updates the layer descriptors for each camera in an array camera
  50377. * to prepare for rendering to a depth array texture.
  50378. *
  50379. * @param {RenderContext} renderContext - The render context.
  50380. * @param {Object} renderContextData - The render context data.
  50381. * @param {ArrayCamera} cameras - The array camera.
  50382. *
  50383. */
  50384. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  50385. for ( let i = 0; i < cameras.length; i ++ ) {
  50386. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  50387. if ( layerDescriptor.depthStencilAttachment ) {
  50388. const depthAttachment = layerDescriptor.depthStencilAttachment;
  50389. if ( renderContext.depth ) {
  50390. if ( renderContext.clearDepth ) {
  50391. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  50392. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  50393. } else {
  50394. depthAttachment.depthLoadOp = GPULoadOp.Load;
  50395. }
  50396. }
  50397. if ( renderContext.stencil ) {
  50398. if ( renderContext.clearStencil ) {
  50399. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  50400. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  50401. } else {
  50402. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  50403. }
  50404. }
  50405. }
  50406. }
  50407. }
  50408. /**
  50409. * This method is executed at the end of a render call and finalizes work
  50410. * after draw calls.
  50411. *
  50412. * @param {RenderContext} renderContext - The render context.
  50413. */
  50414. finishRender( renderContext ) {
  50415. const renderContextData = this.get( renderContext );
  50416. const occlusionQueryCount = renderContext.occlusionQueryCount;
  50417. if ( renderContextData.renderBundles.length > 0 ) {
  50418. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  50419. }
  50420. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  50421. renderContextData.currentPass.endOcclusionQuery();
  50422. }
  50423. // shadow arrays - Execute bundles for each layer
  50424. const encoder = renderContextData.encoder;
  50425. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  50426. const bundles = [];
  50427. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  50428. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  50429. bundles.push( bundleEncoder.finish() );
  50430. }
  50431. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  50432. if ( i < bundles.length ) {
  50433. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  50434. const renderPass = encoder.beginRenderPass( layerDescriptor );
  50435. if ( renderContext.viewport ) {
  50436. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  50437. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  50438. }
  50439. if ( renderContext.scissor ) {
  50440. const { x, y, width, height } = renderContext.scissorValue;
  50441. renderPass.setScissorRect( x, y, width, height );
  50442. }
  50443. renderPass.executeBundles( [ bundles[ i ] ] );
  50444. renderPass.end();
  50445. }
  50446. }
  50447. } else if ( renderContextData.currentPass ) {
  50448. renderContextData.currentPass.end();
  50449. }
  50450. if ( occlusionQueryCount > 0 ) {
  50451. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  50452. //
  50453. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  50454. if ( queryResolveBuffer === undefined ) {
  50455. queryResolveBuffer = this.device.createBuffer(
  50456. {
  50457. size: bufferSize,
  50458. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  50459. }
  50460. );
  50461. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  50462. }
  50463. //
  50464. const readBuffer = this.device.createBuffer(
  50465. {
  50466. size: bufferSize,
  50467. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50468. }
  50469. );
  50470. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  50471. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  50472. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  50473. renderContextData.occlusionQueryBuffer = readBuffer;
  50474. //
  50475. this.resolveOccludedAsync( renderContext );
  50476. }
  50477. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  50478. //
  50479. if ( renderContext.textures !== null ) {
  50480. const textures = renderContext.textures;
  50481. for ( let i = 0; i < textures.length; i ++ ) {
  50482. const texture = textures[ i ];
  50483. if ( texture.generateMipmaps === true ) {
  50484. this.textureUtils.generateMipmaps( texture );
  50485. }
  50486. }
  50487. }
  50488. }
  50489. /**
  50490. * Returns `true` if the given 3D object is fully occluded by other
  50491. * 3D objects in the scene.
  50492. *
  50493. * @param {RenderContext} renderContext - The render context.
  50494. * @param {Object3D} object - The 3D object to test.
  50495. * @return {boolean} Whether the 3D object is fully occluded or not.
  50496. */
  50497. isOccluded( renderContext, object ) {
  50498. const renderContextData = this.get( renderContext );
  50499. return renderContextData.occluded && renderContextData.occluded.has( object );
  50500. }
  50501. /**
  50502. * This method processes the result of occlusion queries and writes it
  50503. * into render context data.
  50504. *
  50505. * @async
  50506. * @param {RenderContext} renderContext - The render context.
  50507. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  50508. */
  50509. async resolveOccludedAsync( renderContext ) {
  50510. const renderContextData = this.get( renderContext );
  50511. // handle occlusion query results
  50512. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  50513. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  50514. const occluded = new WeakSet();
  50515. renderContextData.currentOcclusionQueryObjects = null;
  50516. renderContextData.currentOcclusionQueryBuffer = null;
  50517. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  50518. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  50519. const results = new BigUint64Array( buffer );
  50520. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  50521. if ( results[ i ] === BigInt( 0 ) ) {
  50522. occluded.add( currentOcclusionQueryObjects[ i ] );
  50523. }
  50524. }
  50525. currentOcclusionQueryBuffer.destroy();
  50526. renderContextData.occluded = occluded;
  50527. }
  50528. }
  50529. /**
  50530. * Updates the viewport with the values from the given render context.
  50531. *
  50532. * @param {RenderContext} renderContext - The render context.
  50533. */
  50534. updateViewport( renderContext ) {
  50535. const { currentPass } = this.get( renderContext );
  50536. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  50537. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  50538. }
  50539. /**
  50540. * Returns the clear color and alpha into a single
  50541. * color object.
  50542. *
  50543. * @return {Color4} The clear color.
  50544. */
  50545. getClearColor() {
  50546. const clearColor = super.getClearColor();
  50547. // only premultiply alpha when alphaMode is "premultiplied"
  50548. if ( this.renderer.alpha === true ) {
  50549. clearColor.r *= clearColor.a;
  50550. clearColor.g *= clearColor.a;
  50551. clearColor.b *= clearColor.a;
  50552. }
  50553. return clearColor;
  50554. }
  50555. /**
  50556. * Performs a clear operation.
  50557. *
  50558. * @param {boolean} color - Whether the color buffer should be cleared or not.
  50559. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  50560. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  50561. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  50562. */
  50563. clear( color, depth, stencil, renderTargetContext = null ) {
  50564. const device = this.device;
  50565. const renderer = this.renderer;
  50566. let colorAttachments = [];
  50567. let depthStencilAttachment;
  50568. let clearValue;
  50569. let supportsDepth;
  50570. let supportsStencil;
  50571. if ( color ) {
  50572. const clearColor = this.getClearColor();
  50573. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  50574. }
  50575. if ( renderTargetContext === null ) {
  50576. supportsDepth = renderer.depth;
  50577. supportsStencil = renderer.stencil;
  50578. const descriptor = this._getDefaultRenderPassDescriptor();
  50579. if ( color ) {
  50580. colorAttachments = descriptor.colorAttachments;
  50581. const colorAttachment = colorAttachments[ 0 ];
  50582. colorAttachment.clearValue = clearValue;
  50583. colorAttachment.loadOp = GPULoadOp.Clear;
  50584. colorAttachment.storeOp = GPUStoreOp.Store;
  50585. }
  50586. if ( supportsDepth || supportsStencil ) {
  50587. depthStencilAttachment = descriptor.depthStencilAttachment;
  50588. }
  50589. } else {
  50590. supportsDepth = renderTargetContext.depth;
  50591. supportsStencil = renderTargetContext.stencil;
  50592. const clearConfig = {
  50593. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  50594. clearValue: color ? clearValue : undefined
  50595. };
  50596. if ( supportsDepth ) {
  50597. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  50598. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  50599. clearConfig.depthStoreOp = GPUStoreOp.Store;
  50600. }
  50601. if ( supportsStencil ) {
  50602. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  50603. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  50604. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  50605. }
  50606. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  50607. colorAttachments = descriptor.colorAttachments;
  50608. depthStencilAttachment = descriptor.depthStencilAttachment;
  50609. }
  50610. if ( supportsDepth && depthStencilAttachment && depthStencilAttachment.depthLoadOp === undefined ) {
  50611. if ( depth ) {
  50612. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  50613. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  50614. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50615. } else {
  50616. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  50617. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50618. }
  50619. }
  50620. //
  50621. if ( supportsStencil && depthStencilAttachment && depthStencilAttachment.stencilLoadOp === undefined ) {
  50622. if ( stencil ) {
  50623. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  50624. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  50625. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50626. } else {
  50627. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  50628. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50629. }
  50630. }
  50631. //
  50632. const encoder = device.createCommandEncoder( { label: 'clear' } );
  50633. const currentPass = encoder.beginRenderPass( {
  50634. colorAttachments,
  50635. depthStencilAttachment
  50636. } );
  50637. currentPass.end();
  50638. device.queue.submit( [ encoder.finish() ] );
  50639. }
  50640. // compute
  50641. /**
  50642. * This method is executed at the beginning of a compute call and
  50643. * prepares the state for upcoming compute tasks.
  50644. *
  50645. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  50646. */
  50647. beginCompute( computeGroup ) {
  50648. const groupGPU = this.get( computeGroup );
  50649. const descriptor = {
  50650. label: 'computeGroup_' + computeGroup.id
  50651. };
  50652. this.initTimestampQuery( computeGroup, descriptor );
  50653. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  50654. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  50655. }
  50656. /**
  50657. * Executes a compute command for the given compute node.
  50658. *
  50659. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  50660. * @param {Node} computeNode - The compute node.
  50661. * @param {Array<BindGroup>} bindings - The bindings.
  50662. * @param {ComputePipeline} pipeline - The compute pipeline.
  50663. */
  50664. compute( computeGroup, computeNode, bindings, pipeline ) {
  50665. const { passEncoderGPU } = this.get( computeGroup );
  50666. // pipeline
  50667. const pipelineGPU = this.get( pipeline ).pipeline;
  50668. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  50669. // bind groups
  50670. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  50671. const bindGroup = bindings[ i ];
  50672. const bindingsData = this.get( bindGroup );
  50673. passEncoderGPU.setBindGroup( i, bindingsData.group );
  50674. }
  50675. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  50676. const computeNodeData = this.get( computeNode );
  50677. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  50678. const { dispatchSize } = computeNodeData;
  50679. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  50680. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  50681. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  50682. } else {
  50683. dispatchSize.x = computeNode.dispatchCount;
  50684. }
  50685. passEncoderGPU.dispatchWorkgroups(
  50686. dispatchSize.x,
  50687. dispatchSize.y,
  50688. dispatchSize.z
  50689. );
  50690. }
  50691. /**
  50692. * This method is executed at the end of a compute call and
  50693. * finalizes work after compute tasks.
  50694. *
  50695. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  50696. */
  50697. finishCompute( computeGroup ) {
  50698. const groupData = this.get( computeGroup );
  50699. groupData.passEncoderGPU.end();
  50700. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  50701. }
  50702. /**
  50703. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  50704. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  50705. *
  50706. * @async
  50707. * @return {Promise} A Promise that resolves when synchronization has been finished.
  50708. */
  50709. async waitForGPU() {
  50710. await this.device.queue.onSubmittedWorkDone();
  50711. }
  50712. // render object
  50713. /**
  50714. * Executes a draw command for the given render object.
  50715. *
  50716. * @param {RenderObject} renderObject - The render object to draw.
  50717. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  50718. */
  50719. draw( renderObject, info ) {
  50720. const { object, material, context, pipeline } = renderObject;
  50721. const bindings = renderObject.getBindings();
  50722. const renderContextData = this.get( context );
  50723. const pipelineGPU = this.get( pipeline ).pipeline;
  50724. const index = renderObject.getIndex();
  50725. const hasIndex = ( index !== null );
  50726. const drawParams = renderObject.getDrawParameters();
  50727. if ( drawParams === null ) return;
  50728. // pipeline
  50729. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  50730. // pipeline
  50731. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  50732. currentSets.pipeline = pipelineGPU;
  50733. // bind groups
  50734. const currentBindingGroups = currentSets.bindingGroups;
  50735. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  50736. const bindGroup = bindings[ i ];
  50737. const bindingsData = this.get( bindGroup );
  50738. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  50739. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  50740. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  50741. }
  50742. }
  50743. // attributes
  50744. // index
  50745. if ( hasIndex === true ) {
  50746. if ( currentSets.index !== index ) {
  50747. const buffer = this.get( index ).buffer;
  50748. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  50749. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  50750. currentSets.index = index;
  50751. }
  50752. }
  50753. // vertex buffers
  50754. const vertexBuffers = renderObject.getVertexBuffers();
  50755. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  50756. const vertexBuffer = vertexBuffers[ i ];
  50757. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  50758. const buffer = this.get( vertexBuffer ).buffer;
  50759. passEncoderGPU.setVertexBuffer( i, buffer );
  50760. currentSets.attributes[ i ] = vertexBuffer;
  50761. }
  50762. }
  50763. // stencil
  50764. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  50765. passEncoderGPU.setStencilReference( material.stencilRef );
  50766. renderContextData.currentStencilRef = material.stencilRef;
  50767. }
  50768. };
  50769. // Define draw function
  50770. const draw = ( passEncoderGPU, currentSets ) => {
  50771. setPipelineAndBindings( passEncoderGPU, currentSets );
  50772. if ( object.isBatchedMesh === true ) {
  50773. const starts = object._multiDrawStarts;
  50774. const counts = object._multiDrawCounts;
  50775. const drawCount = object._multiDrawCount;
  50776. const drawInstances = object._multiDrawInstances;
  50777. if ( drawInstances !== null ) {
  50778. // @deprecated, r174
  50779. warnOnce( 'THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  50780. }
  50781. for ( let i = 0; i < drawCount; i ++ ) {
  50782. const count = drawInstances ? drawInstances[ i ] : 1;
  50783. const firstInstance = count > 1 ? 0 : i;
  50784. if ( hasIndex === true ) {
  50785. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  50786. } else {
  50787. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  50788. }
  50789. info.update( object, counts[ i ], count );
  50790. }
  50791. } else if ( hasIndex === true ) {
  50792. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  50793. const indirect = renderObject.getIndirect();
  50794. if ( indirect !== null ) {
  50795. const buffer = this.get( indirect ).buffer;
  50796. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  50797. } else {
  50798. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  50799. }
  50800. info.update( object, indexCount, instanceCount );
  50801. } else {
  50802. const { vertexCount, instanceCount, firstVertex } = drawParams;
  50803. const indirect = renderObject.getIndirect();
  50804. if ( indirect !== null ) {
  50805. const buffer = this.get( indirect ).buffer;
  50806. passEncoderGPU.drawIndirect( buffer, 0 );
  50807. } else {
  50808. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  50809. }
  50810. info.update( object, vertexCount, instanceCount );
  50811. }
  50812. };
  50813. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  50814. const cameraData = this.get( renderObject.camera );
  50815. const cameras = renderObject.camera.cameras;
  50816. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  50817. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  50818. const bindingsData = this.get( cameraIndex );
  50819. const indexesGPU = [];
  50820. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  50821. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50822. data[ 0 ] = i;
  50823. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  50824. indexesGPU.push( bindGroupIndex );
  50825. }
  50826. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  50827. }
  50828. const pixelRatio = this.renderer.getPixelRatio();
  50829. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50830. const subCamera = cameras[ i ];
  50831. if ( object.layers.test( subCamera.layers ) ) {
  50832. const vp = subCamera.viewport;
  50833. let pass = renderContextData.currentPass;
  50834. let sets = renderContextData.currentSets;
  50835. if ( renderContextData.bundleEncoders ) {
  50836. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  50837. const bundleSets = renderContextData.bundleSets[ i ];
  50838. pass = bundleEncoder;
  50839. sets = bundleSets;
  50840. }
  50841. if ( vp ) {
  50842. pass.setViewport(
  50843. Math.floor( vp.x * pixelRatio ),
  50844. Math.floor( vp.y * pixelRatio ),
  50845. Math.floor( vp.width * pixelRatio ),
  50846. Math.floor( vp.height * pixelRatio ),
  50847. context.viewportValue.minDepth,
  50848. context.viewportValue.maxDepth
  50849. );
  50850. }
  50851. // Set camera index binding for this layer
  50852. if ( cameraIndex && cameraData.indexesGPU ) {
  50853. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  50854. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  50855. }
  50856. draw( pass, sets );
  50857. }
  50858. }
  50859. } else {
  50860. // Regular single camera rendering
  50861. if ( renderContextData.currentPass ) {
  50862. // Handle occlusion queries
  50863. if ( renderContextData.occlusionQuerySet !== undefined ) {
  50864. const lastObject = renderContextData.lastOcclusionObject;
  50865. if ( lastObject !== object ) {
  50866. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  50867. renderContextData.currentPass.endOcclusionQuery();
  50868. renderContextData.occlusionQueryIndex ++;
  50869. }
  50870. if ( object.occlusionTest === true ) {
  50871. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  50872. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  50873. }
  50874. renderContextData.lastOcclusionObject = object;
  50875. }
  50876. }
  50877. draw( renderContextData.currentPass, renderContextData.currentSets );
  50878. }
  50879. }
  50880. }
  50881. // cache key
  50882. /**
  50883. * Returns `true` if the render pipeline requires an update.
  50884. *
  50885. * @param {RenderObject} renderObject - The render object.
  50886. * @return {boolean} Whether the render pipeline requires an update or not.
  50887. */
  50888. needsRenderUpdate( renderObject ) {
  50889. const data = this.get( renderObject );
  50890. const { object, material } = renderObject;
  50891. const utils = this.utils;
  50892. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  50893. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  50894. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  50895. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  50896. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  50897. let needsUpdate = false;
  50898. if ( data.material !== material || data.materialVersion !== material.version ||
  50899. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  50900. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  50901. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  50902. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  50903. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  50904. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  50905. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  50906. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  50907. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  50908. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  50909. data.primitiveTopology !== primitiveTopology ||
  50910. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  50911. ) {
  50912. data.material = material; data.materialVersion = material.version;
  50913. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  50914. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  50915. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  50916. data.colorWrite = material.colorWrite;
  50917. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  50918. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  50919. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  50920. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  50921. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  50922. data.sampleCount = sampleCount;
  50923. data.colorSpace = colorSpace;
  50924. data.colorFormat = colorFormat;
  50925. data.depthStencilFormat = depthStencilFormat;
  50926. data.primitiveTopology = primitiveTopology;
  50927. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  50928. needsUpdate = true;
  50929. }
  50930. return needsUpdate;
  50931. }
  50932. /**
  50933. * Returns a cache key that is used to identify render pipelines.
  50934. *
  50935. * @param {RenderObject} renderObject - The render object.
  50936. * @return {string} The cache key.
  50937. */
  50938. getRenderCacheKey( renderObject ) {
  50939. const { object, material } = renderObject;
  50940. const utils = this.utils;
  50941. const renderContext = renderObject.context;
  50942. return [
  50943. material.transparent, material.blending, material.premultipliedAlpha,
  50944. material.blendSrc, material.blendDst, material.blendEquation,
  50945. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  50946. material.colorWrite,
  50947. material.depthWrite, material.depthTest, material.depthFunc,
  50948. material.stencilWrite, material.stencilFunc,
  50949. material.stencilFail, material.stencilZFail, material.stencilZPass,
  50950. material.stencilFuncMask, material.stencilWriteMask,
  50951. material.side,
  50952. utils.getSampleCountRenderContext( renderContext ),
  50953. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  50954. utils.getPrimitiveTopology( object, material ),
  50955. renderObject.getGeometryCacheKey(),
  50956. renderObject.clippingContextCacheKey
  50957. ].join();
  50958. }
  50959. // textures
  50960. /**
  50961. * Creates a GPU sampler for the given texture.
  50962. *
  50963. * @param {Texture} texture - The texture to create the sampler for.
  50964. */
  50965. createSampler( texture ) {
  50966. this.textureUtils.createSampler( texture );
  50967. }
  50968. /**
  50969. * Destroys the GPU sampler for the given texture.
  50970. *
  50971. * @param {Texture} texture - The texture to destroy the sampler for.
  50972. */
  50973. destroySampler( texture ) {
  50974. this.textureUtils.destroySampler( texture );
  50975. }
  50976. /**
  50977. * Creates a default texture for the given texture that can be used
  50978. * as a placeholder until the actual texture is ready for usage.
  50979. *
  50980. * @param {Texture} texture - The texture to create a default texture for.
  50981. */
  50982. createDefaultTexture( texture ) {
  50983. this.textureUtils.createDefaultTexture( texture );
  50984. }
  50985. /**
  50986. * Defines a texture on the GPU for the given texture object.
  50987. *
  50988. * @param {Texture} texture - The texture.
  50989. * @param {Object} [options={}] - Optional configuration parameter.
  50990. */
  50991. createTexture( texture, options ) {
  50992. this.textureUtils.createTexture( texture, options );
  50993. }
  50994. /**
  50995. * Uploads the updated texture data to the GPU.
  50996. *
  50997. * @param {Texture} texture - The texture.
  50998. * @param {Object} [options={}] - Optional configuration parameter.
  50999. */
  51000. updateTexture( texture, options ) {
  51001. this.textureUtils.updateTexture( texture, options );
  51002. }
  51003. /**
  51004. * Generates mipmaps for the given texture.
  51005. *
  51006. * @param {Texture} texture - The texture.
  51007. */
  51008. generateMipmaps( texture ) {
  51009. this.textureUtils.generateMipmaps( texture );
  51010. }
  51011. /**
  51012. * Destroys the GPU data for the given texture object.
  51013. *
  51014. * @param {Texture} texture - The texture.
  51015. */
  51016. destroyTexture( texture ) {
  51017. this.textureUtils.destroyTexture( texture );
  51018. }
  51019. /**
  51020. * Returns texture data as a typed array.
  51021. *
  51022. * @async
  51023. * @param {Texture} texture - The texture to copy.
  51024. * @param {number} x - The x coordinate of the copy origin.
  51025. * @param {number} y - The y coordinate of the copy origin.
  51026. * @param {number} width - The width of the copy.
  51027. * @param {number} height - The height of the copy.
  51028. * @param {number} faceIndex - The face index.
  51029. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  51030. */
  51031. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  51032. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  51033. }
  51034. /**
  51035. * Inits a time stamp query for the given render context.
  51036. *
  51037. * @param {RenderContext} renderContext - The render context.
  51038. * @param {Object} descriptor - The query descriptor.
  51039. */
  51040. initTimestampQuery( renderContext, descriptor ) {
  51041. if ( ! this.trackTimestamp ) return;
  51042. const type = renderContext.isComputeNode ? 'compute' : 'render';
  51043. if ( ! this.timestampQueryPool[ type ] ) {
  51044. // TODO: Variable maxQueries?
  51045. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  51046. }
  51047. const timestampQueryPool = this.timestampQueryPool[ type ];
  51048. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  51049. descriptor.timestampWrites = {
  51050. querySet: timestampQueryPool.querySet,
  51051. beginningOfPassWriteIndex: baseOffset,
  51052. endOfPassWriteIndex: baseOffset + 1,
  51053. };
  51054. }
  51055. // node builder
  51056. /**
  51057. * Returns a node builder for the given render object.
  51058. *
  51059. * @param {RenderObject} object - The render object.
  51060. * @param {Renderer} renderer - The renderer.
  51061. * @return {WGSLNodeBuilder} The node builder.
  51062. */
  51063. createNodeBuilder( object, renderer ) {
  51064. return new WGSLNodeBuilder( object, renderer );
  51065. }
  51066. // program
  51067. /**
  51068. * Creates a shader program from the given programmable stage.
  51069. *
  51070. * @param {ProgrammableStage} program - The programmable stage.
  51071. */
  51072. createProgram( program ) {
  51073. const programGPU = this.get( program );
  51074. programGPU.module = {
  51075. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  51076. entryPoint: 'main'
  51077. };
  51078. }
  51079. /**
  51080. * Destroys the shader program of the given programmable stage.
  51081. *
  51082. * @param {ProgrammableStage} program - The programmable stage.
  51083. */
  51084. destroyProgram( program ) {
  51085. this.delete( program );
  51086. }
  51087. // pipelines
  51088. /**
  51089. * Creates a render pipeline for the given render object.
  51090. *
  51091. * @param {RenderObject} renderObject - The render object.
  51092. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  51093. */
  51094. createRenderPipeline( renderObject, promises ) {
  51095. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  51096. }
  51097. /**
  51098. * Creates a compute pipeline for the given compute node.
  51099. *
  51100. * @param {ComputePipeline} computePipeline - The compute pipeline.
  51101. * @param {Array<BindGroup>} bindings - The bindings.
  51102. */
  51103. createComputePipeline( computePipeline, bindings ) {
  51104. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  51105. }
  51106. /**
  51107. * Prepares the state for encoding render bundles.
  51108. *
  51109. * @param {RenderContext} renderContext - The render context.
  51110. */
  51111. beginBundle( renderContext ) {
  51112. const renderContextData = this.get( renderContext );
  51113. renderContextData._currentPass = renderContextData.currentPass;
  51114. renderContextData._currentSets = renderContextData.currentSets;
  51115. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  51116. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  51117. }
  51118. /**
  51119. * After processing render bundles this method finalizes related work.
  51120. *
  51121. * @param {RenderContext} renderContext - The render context.
  51122. * @param {RenderBundle} bundle - The render bundle.
  51123. */
  51124. finishBundle( renderContext, bundle ) {
  51125. const renderContextData = this.get( renderContext );
  51126. const bundleEncoder = renderContextData.currentPass;
  51127. const bundleGPU = bundleEncoder.finish();
  51128. this.get( bundle ).bundleGPU = bundleGPU;
  51129. // restore render pass state
  51130. renderContextData.currentSets = renderContextData._currentSets;
  51131. renderContextData.currentPass = renderContextData._currentPass;
  51132. }
  51133. /**
  51134. * Adds a render bundle to the render context data.
  51135. *
  51136. * @param {RenderContext} renderContext - The render context.
  51137. * @param {RenderBundle} bundle - The render bundle to add.
  51138. */
  51139. addBundle( renderContext, bundle ) {
  51140. const renderContextData = this.get( renderContext );
  51141. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  51142. }
  51143. // bindings
  51144. /**
  51145. * Creates bindings from the given bind group definition.
  51146. *
  51147. * @param {BindGroup} bindGroup - The bind group.
  51148. * @param {Array<BindGroup>} bindings - Array of bind groups.
  51149. * @param {number} cacheIndex - The cache index.
  51150. * @param {number} version - The version.
  51151. */
  51152. createBindings( bindGroup, bindings, cacheIndex, version ) {
  51153. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  51154. }
  51155. /**
  51156. * Updates the given bind group definition.
  51157. *
  51158. * @param {BindGroup} bindGroup - The bind group.
  51159. * @param {Array<BindGroup>} bindings - Array of bind groups.
  51160. * @param {number} cacheIndex - The cache index.
  51161. * @param {number} version - The version.
  51162. */
  51163. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  51164. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  51165. }
  51166. /**
  51167. * Updates a buffer binding.
  51168. *
  51169. * @param {Buffer} binding - The buffer binding to update.
  51170. */
  51171. updateBinding( binding ) {
  51172. this.bindingUtils.updateBinding( binding );
  51173. }
  51174. // attributes
  51175. /**
  51176. * Creates the buffer of an indexed shader attribute.
  51177. *
  51178. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  51179. */
  51180. createIndexAttribute( attribute ) {
  51181. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51182. }
  51183. /**
  51184. * Creates the GPU buffer of a shader attribute.
  51185. *
  51186. * @param {BufferAttribute} attribute - The buffer attribute.
  51187. */
  51188. createAttribute( attribute ) {
  51189. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51190. }
  51191. /**
  51192. * Creates the GPU buffer of a storage attribute.
  51193. *
  51194. * @param {BufferAttribute} attribute - The buffer attribute.
  51195. */
  51196. createStorageAttribute( attribute ) {
  51197. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51198. }
  51199. /**
  51200. * Creates the GPU buffer of an indirect storage attribute.
  51201. *
  51202. * @param {BufferAttribute} attribute - The buffer attribute.
  51203. */
  51204. createIndirectStorageAttribute( attribute ) {
  51205. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51206. }
  51207. /**
  51208. * Updates the GPU buffer of a shader attribute.
  51209. *
  51210. * @param {BufferAttribute} attribute - The buffer attribute to update.
  51211. */
  51212. updateAttribute( attribute ) {
  51213. this.attributeUtils.updateAttribute( attribute );
  51214. }
  51215. /**
  51216. * Destroys the GPU buffer of a shader attribute.
  51217. *
  51218. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  51219. */
  51220. destroyAttribute( attribute ) {
  51221. this.attributeUtils.destroyAttribute( attribute );
  51222. }
  51223. // canvas
  51224. /**
  51225. * Triggers an update of the default render pass descriptor.
  51226. */
  51227. updateSize() {
  51228. this.colorBuffer = this.textureUtils.getColorBuffer();
  51229. this.defaultRenderPassdescriptor = null;
  51230. }
  51231. // utils public
  51232. /**
  51233. * Returns the maximum anisotropy texture filtering value.
  51234. *
  51235. * @return {number} The maximum anisotropy texture filtering value.
  51236. */
  51237. getMaxAnisotropy() {
  51238. return 16;
  51239. }
  51240. /**
  51241. * Checks if the given feature is supported by the backend.
  51242. *
  51243. * @param {string} name - The feature's name.
  51244. * @return {boolean} Whether the feature is supported or not.
  51245. */
  51246. hasFeature( name ) {
  51247. return this.device.features.has( name );
  51248. }
  51249. /**
  51250. * Copies data of the given source texture to the given destination texture.
  51251. *
  51252. * @param {Texture} srcTexture - The source texture.
  51253. * @param {Texture} dstTexture - The destination texture.
  51254. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  51255. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  51256. * @param {number} [srcLevel=0] - The mipmap level to copy.
  51257. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  51258. */
  51259. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  51260. let dstX = 0;
  51261. let dstY = 0;
  51262. let dstZ = 0;
  51263. let srcX = 0;
  51264. let srcY = 0;
  51265. let srcZ = 0;
  51266. let srcWidth = srcTexture.image.width;
  51267. let srcHeight = srcTexture.image.height;
  51268. let srcDepth = 1;
  51269. if ( srcRegion !== null ) {
  51270. if ( srcRegion.isBox3 === true ) {
  51271. srcX = srcRegion.min.x;
  51272. srcY = srcRegion.min.y;
  51273. srcZ = srcRegion.min.z;
  51274. srcWidth = srcRegion.max.x - srcRegion.min.x;
  51275. srcHeight = srcRegion.max.y - srcRegion.min.y;
  51276. srcDepth = srcRegion.max.z - srcRegion.min.z;
  51277. } else {
  51278. // Assume it's a Box2
  51279. srcX = srcRegion.min.x;
  51280. srcY = srcRegion.min.y;
  51281. srcWidth = srcRegion.max.x - srcRegion.min.x;
  51282. srcHeight = srcRegion.max.y - srcRegion.min.y;
  51283. srcDepth = 1;
  51284. }
  51285. }
  51286. if ( dstPosition !== null ) {
  51287. dstX = dstPosition.x;
  51288. dstY = dstPosition.y;
  51289. dstZ = dstPosition.z || 0;
  51290. }
  51291. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  51292. const sourceGPU = this.get( srcTexture ).texture;
  51293. const destinationGPU = this.get( dstTexture ).texture;
  51294. encoder.copyTextureToTexture(
  51295. {
  51296. texture: sourceGPU,
  51297. mipLevel: srcLevel,
  51298. origin: { x: srcX, y: srcY, z: srcZ }
  51299. },
  51300. {
  51301. texture: destinationGPU,
  51302. mipLevel: dstLevel,
  51303. origin: { x: dstX, y: dstY, z: dstZ }
  51304. },
  51305. [
  51306. srcWidth,
  51307. srcHeight,
  51308. srcDepth
  51309. ]
  51310. );
  51311. this.device.queue.submit( [ encoder.finish() ] );
  51312. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  51313. this.textureUtils.generateMipmaps( dstTexture );
  51314. }
  51315. }
  51316. /**
  51317. * Copies the current bound framebuffer to the given texture.
  51318. *
  51319. * @param {Texture} texture - The destination texture.
  51320. * @param {RenderContext} renderContext - The render context.
  51321. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  51322. */
  51323. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  51324. const renderContextData = this.get( renderContext );
  51325. let sourceGPU = null;
  51326. if ( renderContext.renderTarget ) {
  51327. if ( texture.isDepthTexture ) {
  51328. sourceGPU = this.get( renderContext.depthTexture ).texture;
  51329. } else {
  51330. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  51331. }
  51332. } else {
  51333. if ( texture.isDepthTexture ) {
  51334. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  51335. } else {
  51336. sourceGPU = this.context.getCurrentTexture();
  51337. }
  51338. }
  51339. const destinationGPU = this.get( texture ).texture;
  51340. if ( sourceGPU.format !== destinationGPU.format ) {
  51341. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  51342. return;
  51343. }
  51344. let encoder;
  51345. if ( renderContextData.currentPass ) {
  51346. renderContextData.currentPass.end();
  51347. encoder = renderContextData.encoder;
  51348. } else {
  51349. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  51350. }
  51351. encoder.copyTextureToTexture(
  51352. {
  51353. texture: sourceGPU,
  51354. origin: [ rectangle.x, rectangle.y, 0 ],
  51355. },
  51356. {
  51357. texture: destinationGPU
  51358. },
  51359. [
  51360. rectangle.z,
  51361. rectangle.w
  51362. ]
  51363. );
  51364. if ( renderContextData.currentPass ) {
  51365. const { descriptor } = renderContextData;
  51366. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  51367. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  51368. }
  51369. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  51370. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  51371. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  51372. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  51373. if ( renderContext.viewport ) {
  51374. this.updateViewport( renderContext );
  51375. }
  51376. if ( renderContext.scissor ) {
  51377. const { x, y, width, height } = renderContext.scissorValue;
  51378. renderContextData.currentPass.setScissorRect( x, y, width, height );
  51379. }
  51380. } else {
  51381. this.device.queue.submit( [ encoder.finish() ] );
  51382. }
  51383. if ( texture.generateMipmaps ) {
  51384. this.textureUtils.generateMipmaps( texture );
  51385. }
  51386. }
  51387. }
  51388. /**
  51389. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  51390. *
  51391. * @augments SpotLight
  51392. */
  51393. class IESSpotLight extends SpotLight {
  51394. /**
  51395. * Constructs a new IES spot light.
  51396. *
  51397. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  51398. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  51399. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  51400. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  51401. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  51402. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  51403. */
  51404. constructor( color, intensity, distance, angle, penumbra, decay ) {
  51405. super( color, intensity, distance, angle, penumbra, decay );
  51406. /**
  51407. * TODO
  51408. *
  51409. * @type {?Texture}
  51410. * @default null
  51411. */
  51412. this.iesMap = null;
  51413. }
  51414. copy( source, recursive ) {
  51415. super.copy( source, recursive );
  51416. this.iesMap = source.iesMap;
  51417. return this;
  51418. }
  51419. }
  51420. /**
  51421. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  51422. *
  51423. * @augments SpotLight
  51424. */
  51425. class ProjectorLight extends SpotLight {
  51426. /**
  51427. * Constructs a new projector light.
  51428. *
  51429. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  51430. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  51431. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  51432. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  51433. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  51434. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  51435. */
  51436. constructor( color, intensity, distance, angle, penumbra, decay ) {
  51437. super( color, intensity, distance, angle, penumbra, decay );
  51438. /**
  51439. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  51440. *
  51441. * @type {number}
  51442. * @default null
  51443. */
  51444. this.aspect = null;
  51445. }
  51446. copy( source, recursive ) {
  51447. super.copy( source, recursive );
  51448. this.aspect = source.aspect;
  51449. return this;
  51450. }
  51451. }
  51452. /**
  51453. * This version of a node library represents a basic version
  51454. * just focusing on lights and tone mapping techniques.
  51455. *
  51456. * @private
  51457. * @augments NodeLibrary
  51458. */
  51459. class BasicNodeLibrary extends NodeLibrary {
  51460. /**
  51461. * Constructs a new basic node library.
  51462. */
  51463. constructor() {
  51464. super();
  51465. this.addLight( PointLightNode, PointLight );
  51466. this.addLight( DirectionalLightNode, DirectionalLight );
  51467. this.addLight( RectAreaLightNode, RectAreaLight );
  51468. this.addLight( SpotLightNode, SpotLight );
  51469. this.addLight( AmbientLightNode, AmbientLight );
  51470. this.addLight( HemisphereLightNode, HemisphereLight );
  51471. this.addLight( LightProbeNode, LightProbe );
  51472. this.addLight( IESSpotLightNode, IESSpotLight );
  51473. this.addLight( ProjectorLightNode, ProjectorLight );
  51474. this.addToneMapping( linearToneMapping, LinearToneMapping );
  51475. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  51476. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  51477. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  51478. this.addToneMapping( agxToneMapping, AgXToneMapping );
  51479. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  51480. }
  51481. }
  51482. /**
  51483. * This alternative version of {@link WebGPURenderer} only supports node materials.
  51484. * So classes like `MeshBasicMaterial` are not compatible.
  51485. *
  51486. * @private
  51487. * @augments Renderer
  51488. */
  51489. class WebGPURenderer extends Renderer {
  51490. /**
  51491. * Constructs a new WebGPU renderer.
  51492. *
  51493. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  51494. */
  51495. constructor( parameters = {} ) {
  51496. let BackendClass;
  51497. if ( parameters.forceWebGL ) {
  51498. BackendClass = WebGLBackend;
  51499. } else {
  51500. BackendClass = WebGPUBackend;
  51501. parameters.getFallback = () => {
  51502. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  51503. return new WebGLBackend( parameters );
  51504. };
  51505. }
  51506. const backend = new BackendClass( parameters );
  51507. super( backend, parameters );
  51508. /**
  51509. * The generic default value is overwritten with the
  51510. * standard node library for type mapping. Material
  51511. * mapping is not supported with this version.
  51512. *
  51513. * @type {BasicNodeLibrary}
  51514. */
  51515. this.library = new BasicNodeLibrary();
  51516. /**
  51517. * This flag can be used for type testing.
  51518. *
  51519. * @type {boolean}
  51520. * @readonly
  51521. * @default true
  51522. */
  51523. this.isWebGPURenderer = true;
  51524. }
  51525. }
  51526. /**
  51527. * A specialized group which enables applications access to the
  51528. * Render Bundle API of WebGPU. The group with all its descendant nodes
  51529. * are considered as one render bundle and processed as such by
  51530. * the renderer.
  51531. *
  51532. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  51533. * With a WebGL backend, the group can technically be rendered but without
  51534. * any performance improvements.
  51535. *
  51536. * @augments Group
  51537. */
  51538. class BundleGroup extends Group {
  51539. /**
  51540. * Constructs a new bundle group.
  51541. */
  51542. constructor() {
  51543. super();
  51544. /**
  51545. * This flag can be used for type testing.
  51546. *
  51547. * @type {boolean}
  51548. * @readonly
  51549. * @default true
  51550. */
  51551. this.isBundleGroup = true;
  51552. /**
  51553. * This property is only relevant for detecting types
  51554. * during serialization/deserialization. It should always
  51555. * match the class name.
  51556. *
  51557. * @type {string}
  51558. * @readonly
  51559. * @default 'BundleGroup'
  51560. */
  51561. this.type = 'BundleGroup';
  51562. /**
  51563. * Whether the bundle is static or not. When set to `true`, the structure
  51564. * is assumed to be static and does not change. E.g. no new objects are
  51565. * added to the group
  51566. *
  51567. * If a change is required, an update can still be forced by setting the
  51568. * `needsUpdate` flag to `true`.
  51569. *
  51570. * @type {boolean}
  51571. * @default true
  51572. */
  51573. this.static = true;
  51574. /**
  51575. * The bundle group's version.
  51576. *
  51577. * @type {number}
  51578. * @readonly
  51579. * @default 0
  51580. */
  51581. this.version = 0;
  51582. }
  51583. /**
  51584. * Set this property to `true` when the bundle group has changed.
  51585. *
  51586. * @type {boolean}
  51587. * @default false
  51588. * @param {boolean} value
  51589. */
  51590. set needsUpdate( value ) {
  51591. if ( value === true ) this.version ++;
  51592. }
  51593. }
  51594. /**
  51595. * This module is responsible to manage the post processing setups in apps.
  51596. * You usually create a single instance of this class and use it to define
  51597. * the output of your post processing effect chain.
  51598. * ```js
  51599. * const postProcessing = new PostProcessing( renderer );
  51600. *
  51601. * const scenePass = pass( scene, camera );
  51602. *
  51603. * postProcessing.outputNode = scenePass;
  51604. * ```
  51605. *
  51606. * Note: This module can only be used with `WebGPURenderer`.
  51607. */
  51608. class PostProcessing {
  51609. /**
  51610. * Constructs a new post processing management module.
  51611. *
  51612. * @param {Renderer} renderer - A reference to the renderer.
  51613. * @param {Node<vec4>} outputNode - An optional output node.
  51614. */
  51615. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  51616. /**
  51617. * A reference to the renderer.
  51618. *
  51619. * @type {Renderer}
  51620. */
  51621. this.renderer = renderer;
  51622. /**
  51623. * A node which defines the final output of the post
  51624. * processing. This is usually the last node in a chain
  51625. * of effect nodes.
  51626. *
  51627. * @type {Node<vec4>}
  51628. */
  51629. this.outputNode = outputNode;
  51630. /**
  51631. * Whether the default output tone mapping and color
  51632. * space transformation should be enabled or not.
  51633. *
  51634. * It is enabled by default by it must be disabled when
  51635. * effects must be executed after tone mapping and color
  51636. * space conversion. A typical example is FXAA which
  51637. * requires sRGB input.
  51638. *
  51639. * When set to `false`, the app must control the output
  51640. * transformation with `RenderOutputNode`.
  51641. *
  51642. * ```js
  51643. * const outputPass = renderOutput( scenePass );
  51644. * ```
  51645. *
  51646. * @type {boolean}
  51647. */
  51648. this.outputColorTransform = true;
  51649. /**
  51650. * Must be set to `true` when the output node changes.
  51651. *
  51652. * @type {Node<vec4>}
  51653. */
  51654. this.needsUpdate = true;
  51655. const material = new NodeMaterial();
  51656. material.name = 'PostProcessing';
  51657. /**
  51658. * The full screen quad that is used to render
  51659. * the effects.
  51660. *
  51661. * @private
  51662. * @type {QuadMesh}
  51663. */
  51664. this._quadMesh = new QuadMesh( material );
  51665. }
  51666. /**
  51667. * When `PostProcessing` is used to apply post processing effects,
  51668. * the application must use this version of `render()` inside
  51669. * its animation loop (not the one from the renderer).
  51670. */
  51671. render() {
  51672. this._update();
  51673. const renderer = this.renderer;
  51674. const toneMapping = renderer.toneMapping;
  51675. const outputColorSpace = renderer.outputColorSpace;
  51676. renderer.toneMapping = NoToneMapping;
  51677. renderer.outputColorSpace = LinearSRGBColorSpace;
  51678. //
  51679. const currentXR = renderer.xr.enabled;
  51680. renderer.xr.enabled = false;
  51681. this._quadMesh.render( renderer );
  51682. renderer.xr.enabled = currentXR;
  51683. //
  51684. renderer.toneMapping = toneMapping;
  51685. renderer.outputColorSpace = outputColorSpace;
  51686. }
  51687. /**
  51688. * Frees internal resources.
  51689. */
  51690. dispose() {
  51691. this._quadMesh.material.dispose();
  51692. }
  51693. /**
  51694. * Updates the state of the module.
  51695. *
  51696. * @private
  51697. */
  51698. _update() {
  51699. if ( this.needsUpdate === true ) {
  51700. const renderer = this.renderer;
  51701. const toneMapping = renderer.toneMapping;
  51702. const outputColorSpace = renderer.outputColorSpace;
  51703. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  51704. this._quadMesh.material.needsUpdate = true;
  51705. this.needsUpdate = false;
  51706. }
  51707. }
  51708. /**
  51709. * When `PostProcessing` is used to apply post processing effects,
  51710. * the application must use this version of `renderAsync()` inside
  51711. * its animation loop (not the one from the renderer).
  51712. *
  51713. * @async
  51714. * @return {Promise} A Promise that resolves when the render has been finished.
  51715. */
  51716. async renderAsync() {
  51717. this._update();
  51718. const renderer = this.renderer;
  51719. const toneMapping = renderer.toneMapping;
  51720. const outputColorSpace = renderer.outputColorSpace;
  51721. renderer.toneMapping = NoToneMapping;
  51722. renderer.outputColorSpace = LinearSRGBColorSpace;
  51723. //
  51724. const currentXR = renderer.xr.enabled;
  51725. renderer.xr.enabled = false;
  51726. await this._quadMesh.renderAsync( renderer );
  51727. renderer.xr.enabled = currentXR;
  51728. //
  51729. renderer.toneMapping = toneMapping;
  51730. renderer.outputColorSpace = outputColorSpace;
  51731. }
  51732. }
  51733. /**
  51734. * This special type of texture is intended for compute shaders.
  51735. * It can be used to compute the data of a texture with a compute shader.
  51736. *
  51737. * Note: This type of texture can only be used with `WebGPURenderer`
  51738. * and a WebGPU backend.
  51739. *
  51740. * @augments Texture
  51741. */
  51742. class StorageTexture extends Texture {
  51743. /**
  51744. * Constructs a new storage texture.
  51745. *
  51746. * @param {number} [width=1] - The storage texture's width.
  51747. * @param {number} [height=1] - The storage texture's height.
  51748. */
  51749. constructor( width = 1, height = 1 ) {
  51750. super();
  51751. /**
  51752. * The image object which just represents the texture's dimension.
  51753. *
  51754. * @type {{width: number, height: number}}
  51755. */
  51756. this.image = { width, height };
  51757. /**
  51758. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  51759. *
  51760. * @type {number}
  51761. */
  51762. this.magFilter = LinearFilter;
  51763. /**
  51764. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  51765. *
  51766. * @type {number}
  51767. */
  51768. this.minFilter = LinearFilter;
  51769. /**
  51770. * This flag can be used for type testing.
  51771. *
  51772. * @type {boolean}
  51773. * @readonly
  51774. * @default true
  51775. */
  51776. this.isStorageTexture = true;
  51777. }
  51778. }
  51779. /**
  51780. * This special type of buffer attribute is intended for compute shaders.
  51781. * It can be used to encode draw parameters for indirect draw calls.
  51782. *
  51783. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  51784. * and a WebGPU backend.
  51785. *
  51786. * @augments StorageBufferAttribute
  51787. */
  51788. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  51789. /**
  51790. * Constructs a new storage buffer attribute.
  51791. *
  51792. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  51793. * The subsequent parameter is then obsolete.
  51794. * @param {number} itemSize - The item size.
  51795. */
  51796. constructor( count, itemSize ) {
  51797. super( count, itemSize, Uint32Array );
  51798. /**
  51799. * This flag can be used for type testing.
  51800. *
  51801. * @type {boolean}
  51802. * @readonly
  51803. * @default true
  51804. */
  51805. this.isIndirectStorageBufferAttribute = true;
  51806. }
  51807. }
  51808. /**
  51809. * A loader for loading node objects in the three.js JSON Object/Scene format.
  51810. *
  51811. * @augments Loader
  51812. */
  51813. class NodeLoader extends Loader {
  51814. /**
  51815. * Constructs a new node loader.
  51816. *
  51817. * @param {LoadingManager} [manager] - A reference to a loading manager.
  51818. */
  51819. constructor( manager ) {
  51820. super( manager );
  51821. /**
  51822. * Represents a dictionary of textures.
  51823. *
  51824. * @type {Object<string,Texture>}
  51825. */
  51826. this.textures = {};
  51827. /**
  51828. * Represents a dictionary of node types.
  51829. *
  51830. * @type {Object<string,Node.constructor>}
  51831. */
  51832. this.nodes = {};
  51833. }
  51834. /**
  51835. * Loads the node definitions from the given URL.
  51836. *
  51837. * @param {string} url - The path/URL of the file to be loaded.
  51838. * @param {Function} onLoad - Will be called when load completes.
  51839. * @param {Function} onProgress - Will be called while load progresses.
  51840. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  51841. */
  51842. load( url, onLoad, onProgress, onError ) {
  51843. const loader = new FileLoader( this.manager );
  51844. loader.setPath( this.path );
  51845. loader.setRequestHeader( this.requestHeader );
  51846. loader.setWithCredentials( this.withCredentials );
  51847. loader.load( url, ( text ) => {
  51848. try {
  51849. onLoad( this.parse( JSON.parse( text ) ) );
  51850. } catch ( e ) {
  51851. if ( onError ) {
  51852. onError( e );
  51853. } else {
  51854. console.error( e );
  51855. }
  51856. this.manager.itemError( url );
  51857. }
  51858. }, onProgress, onError );
  51859. }
  51860. /**
  51861. * Parse the node dependencies for the loaded node.
  51862. *
  51863. * @param {Array<Object>} [json] - The JSON definition
  51864. * @return {Object<string,Node>} A dictionary with node dependencies.
  51865. */
  51866. parseNodes( json ) {
  51867. const nodes = {};
  51868. if ( json !== undefined ) {
  51869. for ( const nodeJSON of json ) {
  51870. const { uuid, type } = nodeJSON;
  51871. nodes[ uuid ] = this.createNodeFromType( type );
  51872. nodes[ uuid ].uuid = uuid;
  51873. }
  51874. const meta = { nodes, textures: this.textures };
  51875. for ( const nodeJSON of json ) {
  51876. nodeJSON.meta = meta;
  51877. const node = nodes[ nodeJSON.uuid ];
  51878. node.deserialize( nodeJSON );
  51879. delete nodeJSON.meta;
  51880. }
  51881. }
  51882. return nodes;
  51883. }
  51884. /**
  51885. * Parses the node from the given JSON.
  51886. *
  51887. * @param {Object} json - The JSON definition
  51888. * @param {string} json.type - The node type.
  51889. * @param {string} json.uuid - The node UUID.
  51890. * @param {Array<Object>} [json.nodes] - The node dependencies.
  51891. * @param {Object} [json.meta] - The meta data.
  51892. * @return {Node} The parsed node.
  51893. */
  51894. parse( json ) {
  51895. const node = this.createNodeFromType( json.type );
  51896. node.uuid = json.uuid;
  51897. const nodes = this.parseNodes( json.nodes );
  51898. const meta = { nodes, textures: this.textures };
  51899. json.meta = meta;
  51900. node.deserialize( json );
  51901. delete json.meta;
  51902. return node;
  51903. }
  51904. /**
  51905. * Defines the dictionary of textures.
  51906. *
  51907. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  51908. * @return {NodeLoader} A reference to this loader.
  51909. */
  51910. setTextures( value ) {
  51911. this.textures = value;
  51912. return this;
  51913. }
  51914. /**
  51915. * Defines the dictionary of node types.
  51916. *
  51917. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  51918. * @return {NodeLoader} A reference to this loader.
  51919. */
  51920. setNodes( value ) {
  51921. this.nodes = value;
  51922. return this;
  51923. }
  51924. /**
  51925. * Creates a node object from the given type.
  51926. *
  51927. * @param {string} type - The node type.
  51928. * @return {Node} The created node instance.
  51929. */
  51930. createNodeFromType( type ) {
  51931. if ( this.nodes[ type ] === undefined ) {
  51932. console.error( 'THREE.NodeLoader: Node type not found:', type );
  51933. return float();
  51934. }
  51935. return nodeObject( new this.nodes[ type ]() );
  51936. }
  51937. }
  51938. /**
  51939. * A special type of material loader for loading node materials.
  51940. *
  51941. * @augments MaterialLoader
  51942. */
  51943. class NodeMaterialLoader extends MaterialLoader {
  51944. /**
  51945. * Constructs a new node material loader.
  51946. *
  51947. * @param {LoadingManager} [manager] - A reference to a loading manager.
  51948. */
  51949. constructor( manager ) {
  51950. super( manager );
  51951. /**
  51952. * Represents a dictionary of node types.
  51953. *
  51954. * @type {Object<string,Node.constructor>}
  51955. */
  51956. this.nodes = {};
  51957. /**
  51958. * Represents a dictionary of node material types.
  51959. *
  51960. * @type {Object<string,NodeMaterial.constructor>}
  51961. */
  51962. this.nodeMaterials = {};
  51963. }
  51964. /**
  51965. * Parses the node material from the given JSON.
  51966. *
  51967. * @param {Object} json - The JSON definition
  51968. * @return {NodeMaterial}. The parsed material.
  51969. */
  51970. parse( json ) {
  51971. const material = super.parse( json );
  51972. const nodes = this.nodes;
  51973. const inputNodes = json.inputNodes;
  51974. for ( const property in inputNodes ) {
  51975. const uuid = inputNodes[ property ];
  51976. material[ property ] = nodes[ uuid ];
  51977. }
  51978. return material;
  51979. }
  51980. /**
  51981. * Defines the dictionary of node types.
  51982. *
  51983. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  51984. * @return {NodeLoader} A reference to this loader.
  51985. */
  51986. setNodes( value ) {
  51987. this.nodes = value;
  51988. return this;
  51989. }
  51990. /**
  51991. * Defines the dictionary of node material types.
  51992. *
  51993. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  51994. * @return {NodeLoader} A reference to this loader.
  51995. */
  51996. setNodeMaterials( value ) {
  51997. this.nodeMaterials = value;
  51998. return this;
  51999. }
  52000. /**
  52001. * Creates a node material from the given type.
  52002. *
  52003. * @param {string} type - The node material type.
  52004. * @return {Node} The created node material instance.
  52005. */
  52006. createMaterialFromType( type ) {
  52007. const materialClass = this.nodeMaterials[ type ];
  52008. if ( materialClass !== undefined ) {
  52009. return new materialClass();
  52010. }
  52011. return super.createMaterialFromType( type );
  52012. }
  52013. }
  52014. /**
  52015. * A special type of object loader for loading 3D objects using
  52016. * node materials.
  52017. *
  52018. * @augments ObjectLoader
  52019. */
  52020. class NodeObjectLoader extends ObjectLoader {
  52021. /**
  52022. * Constructs a new node object loader.
  52023. *
  52024. * @param {LoadingManager} [manager] - A reference to a loading manager.
  52025. */
  52026. constructor( manager ) {
  52027. super( manager );
  52028. /**
  52029. * Represents a dictionary of node types.
  52030. *
  52031. * @type {Object<string,Node.constructor>}
  52032. */
  52033. this.nodes = {};
  52034. /**
  52035. * Represents a dictionary of node material types.
  52036. *
  52037. * @type {Object<string,NodeMaterial.constructor>}
  52038. */
  52039. this.nodeMaterials = {};
  52040. /**
  52041. * A reference to hold the `nodes` JSON property.
  52042. *
  52043. * @private
  52044. * @type {?Object[]}
  52045. */
  52046. this._nodesJSON = null;
  52047. }
  52048. /**
  52049. * Defines the dictionary of node types.
  52050. *
  52051. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  52052. * @return {NodeObjectLoader} A reference to this loader.
  52053. */
  52054. setNodes( value ) {
  52055. this.nodes = value;
  52056. return this;
  52057. }
  52058. /**
  52059. * Defines the dictionary of node material types.
  52060. *
  52061. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  52062. * @return {NodeObjectLoader} A reference to this loader.
  52063. */
  52064. setNodeMaterials( value ) {
  52065. this.nodeMaterials = value;
  52066. return this;
  52067. }
  52068. /**
  52069. * Parses the node objects from the given JSON.
  52070. *
  52071. * @param {Object} json - The JSON definition
  52072. * @param {Function} onLoad - The onLoad callback function.
  52073. * @return {Object3D}. The parsed 3D object.
  52074. */
  52075. parse( json, onLoad ) {
  52076. this._nodesJSON = json.nodes;
  52077. const data = super.parse( json, onLoad );
  52078. this._nodesJSON = null; // dispose
  52079. return data;
  52080. }
  52081. /**
  52082. * Parses the node objects from the given JSON and textures.
  52083. *
  52084. * @param {Object[]} json - The JSON definition
  52085. * @param {Object<string,Texture>} textures - The texture library.
  52086. * @return {Object<string,Node>}. The parsed nodes.
  52087. */
  52088. parseNodes( json, textures ) {
  52089. if ( json !== undefined ) {
  52090. const loader = new NodeLoader();
  52091. loader.setNodes( this.nodes );
  52092. loader.setTextures( textures );
  52093. return loader.parseNodes( json );
  52094. }
  52095. return {};
  52096. }
  52097. /**
  52098. * Parses the node objects from the given JSON and textures.
  52099. *
  52100. * @param {Object} json - The JSON definition
  52101. * @param {Object<string,Texture>} textures - The texture library.
  52102. * @return {Object<string,NodeMaterial>}. The parsed materials.
  52103. */
  52104. parseMaterials( json, textures ) {
  52105. const materials = {};
  52106. if ( json !== undefined ) {
  52107. const nodes = this.parseNodes( this._nodesJSON, textures );
  52108. const loader = new NodeMaterialLoader();
  52109. loader.setTextures( textures );
  52110. loader.setNodes( nodes );
  52111. loader.setNodeMaterials( this.nodeMaterials );
  52112. for ( let i = 0, l = json.length; i < l; i ++ ) {
  52113. const data = json[ i ];
  52114. materials[ data.uuid ] = loader.parse( data );
  52115. }
  52116. }
  52117. return materials;
  52118. }
  52119. }
  52120. /**
  52121. * In earlier three.js versions, clipping was defined globally
  52122. * on the renderer or on material level. This special version of
  52123. * `THREE.Group` allows to encode the clipping state into the scene
  52124. * graph. Meaning if you create an instance of this group, all
  52125. * descendant 3D objects will be affected by the respective clipping
  52126. * planes.
  52127. *
  52128. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  52129. *
  52130. * @augments Group
  52131. */
  52132. class ClippingGroup extends Group {
  52133. /**
  52134. * Constructs a new clipping group.
  52135. */
  52136. constructor() {
  52137. super();
  52138. /**
  52139. * This flag can be used for type testing.
  52140. *
  52141. * @type {boolean}
  52142. * @readonly
  52143. * @default true
  52144. */
  52145. this.isClippingGroup = true;
  52146. /**
  52147. * An array with clipping planes.
  52148. *
  52149. * @type {Array<Plane>}
  52150. */
  52151. this.clippingPlanes = [];
  52152. /**
  52153. * Whether clipping should be enabled or not.
  52154. *
  52155. * @type {boolean}
  52156. * @default true
  52157. */
  52158. this.enabled = true;
  52159. /**
  52160. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  52161. *
  52162. * @type {boolean}
  52163. * @default false
  52164. */
  52165. this.clipIntersection = false;
  52166. /**
  52167. * Whether shadows should be clipped or not.
  52168. *
  52169. * @type {boolean}
  52170. * @default false
  52171. */
  52172. this.clipShadows = false;
  52173. }
  52174. }
  52175. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoopNode, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号