three.webgpu.js 2.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix2, Matrix3, Matrix4, error, EventDispatcher, MathUtils, warn, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBufferAttribute, InterleavedBuffer, DynamicDrawUsage, NoColorSpace, log as log$1, warnOnce, Texture, UnsignedIntType, IntType, Compatibility, LessCompare, LessEqualCompare, GreaterCompare, GreaterEqualCompare, NearestFilter, Sphere, BackSide, DoubleSide, CubeTexture, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, NoNormalPacking, NormalRGPacking, NormalGAPacking, ObjectSpaceNormalMap, RGFormat, RED_GREEN_RGTC2_Format, RG11_EAC_Format, InstancedBufferAttribute, InstancedInterleavedBuffer, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, RenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, DataTexture, HalfFloatType, ClampToEdgeWrapping, BufferGeometry, OrthographicCamera, PerspectiveCamera, LinearSRGBColorSpace, RGBAFormat, CubeUVReflectionMapping, BufferAttribute, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, ByteType, UnsignedByteType, ShortType, UnsignedShortType, AlphaFormat, RedFormat, RedIntegerFormat, DepthFormat, DepthStencilFormat, RGBFormat, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedInt101111Type, NormalBlending, SrcAlphaFactor, OneMinusSrcAlphaFactor, AddEquation, MaterialBlending, Object3D, LinearMipMapLinearFilter, Plane, Float32BufferAttribute, UVMapping, PCFShadowMap, PCFSoftShadowMap, VSMShadowMap, BasicShadowMap, CubeDepthTexture, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, yieldToMain, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, FrustumArray, Frustum, RGIntegerFormat, RGBIntegerFormat, RGBAIntegerFormat, TimestampQuery, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, ReversedDepthFuncs, 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, R11_EAC_Format, SIGNED_R11_EAC_Format, SIGNED_RG11_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, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, EqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, getByteLength, isTypedArray, 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, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, 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, Euler, ExternalTexture, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateBezier, 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, 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, Timer, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, getConsoleFunction, setConsoleFunction } 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. * A WeakMap to cache lights data for node materials.
  66. * Cache lights data by render ID to avoid unnecessary recalculations.
  67. *
  68. * @private
  69. * @type {WeakMap<LightsNode,Object>}
  70. */
  71. const _lightsCache = new WeakMap();
  72. /**
  73. * Holds the material data for comparison.
  74. *
  75. * @private
  76. * @type {WeakMap<Material,Object>}
  77. */
  78. const _materialCache = new WeakMap();
  79. /**
  80. * Holds the geometry data for comparison.
  81. *
  82. * @private
  83. * @type {WeakMap<BufferGeometry,Object>}
  84. */
  85. const _geometryCache = new WeakMap();
  86. /**
  87. * This class is used by {@link WebGPURenderer} as management component.
  88. * It's primary purpose is to determine whether render objects require a
  89. * refresh right before they are going to be rendered or not.
  90. */
  91. class NodeMaterialObserver {
  92. /**
  93. * Constructs a new node material observer.
  94. *
  95. * @param {NodeBuilder} builder - The node builder.
  96. */
  97. constructor( builder ) {
  98. /**
  99. * A node material can be used by more than one render object so the
  100. * monitor must maintain a list of render objects.
  101. *
  102. * @type {WeakMap<RenderObject,Object>}
  103. */
  104. this.renderObjects = new WeakMap();
  105. /**
  106. * Whether the material uses node objects or not.
  107. *
  108. * @type {boolean}
  109. */
  110. this.hasNode = this.containsNode( builder );
  111. /**
  112. * Whether the node builder's 3D object is animated or not.
  113. *
  114. * @type {boolean}
  115. */
  116. this.hasAnimation = builder.object.isSkinnedMesh === true;
  117. /**
  118. * A list of all possible material uniforms
  119. *
  120. * @type {Array<string>}
  121. */
  122. this.refreshUniforms = refreshUniforms;
  123. /**
  124. * Holds the current render ID from the node frame.
  125. *
  126. * @type {number}
  127. * @default 0
  128. */
  129. this.renderId = 0;
  130. }
  131. /**
  132. * Returns `true` if the given render object is verified for the first time of this observer.
  133. *
  134. * @param {RenderObject} renderObject - The render object.
  135. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  136. */
  137. firstInitialization( renderObject ) {
  138. const hasInitialized = this.renderObjects.has( renderObject );
  139. if ( hasInitialized === false ) {
  140. this.getRenderObjectData( renderObject );
  141. return true;
  142. }
  143. return false;
  144. }
  145. /**
  146. * Returns `true` if the current rendering produces motion vectors.
  147. *
  148. * @param {Renderer} renderer - The renderer.
  149. * @return {boolean} Whether the current rendering produces motion vectors or not.
  150. */
  151. needsVelocity( renderer ) {
  152. const mrt = renderer.getMRT();
  153. return ( mrt !== null && mrt.has( 'velocity' ) );
  154. }
  155. /**
  156. * Returns monitoring data for the given render object.
  157. *
  158. * @param {RenderObject} renderObject - The render object.
  159. * @return {Object} The monitoring data.
  160. */
  161. getRenderObjectData( renderObject ) {
  162. let data = this.renderObjects.get( renderObject );
  163. if ( data === undefined ) {
  164. const { geometry, object } = renderObject;
  165. data = {
  166. geometryId: geometry.id,
  167. worldMatrix: object.matrixWorld.clone()
  168. };
  169. if ( object.center ) {
  170. data.center = object.center.clone();
  171. }
  172. if ( object.morphTargetInfluences ) {
  173. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  174. }
  175. if ( renderObject.bundle !== null ) {
  176. data.version = renderObject.bundle.version;
  177. }
  178. if ( renderObject.material.transmission > 0 ) {
  179. const { width, height } = renderObject.context;
  180. data.bufferWidth = width;
  181. data.bufferHeight = height;
  182. }
  183. data.lights = this.getLightsData( renderObject.lightsNode.getLights() );
  184. this.renderObjects.set( renderObject, data );
  185. }
  186. return data;
  187. }
  188. /**
  189. * Returns an attribute data structure holding the attributes versions for
  190. * monitoring.
  191. *
  192. * @param {Object} attributes - The geometry attributes.
  193. * @return {Object} An object for monitoring the versions of attributes.
  194. */
  195. getAttributesData( attributes ) {
  196. const attributesData = {};
  197. for ( const name in attributes ) {
  198. const attribute = attributes[ name ];
  199. attributesData[ name ] = {
  200. id: attribute.id,
  201. version: attribute.version,
  202. };
  203. }
  204. return attributesData;
  205. }
  206. /**
  207. * Returns `true` if the node builder's material uses
  208. * node properties.
  209. *
  210. * @param {NodeBuilder} builder - The current node builder.
  211. * @return {boolean} Whether the node builder's material uses node properties or not.
  212. */
  213. containsNode( builder ) {
  214. const material = builder.material;
  215. for ( const property in material ) {
  216. if ( material[ property ] && material[ property ].isNode )
  217. return true;
  218. }
  219. if ( builder.context.modelViewMatrix || builder.context.modelNormalViewMatrix || builder.context.getAO || builder.context.getShadow )
  220. return true;
  221. return false;
  222. }
  223. /**
  224. * Returns a geometry data structure holding the geometry property values for
  225. * monitoring.
  226. *
  227. * @param {BufferGeometry} geometry - The geometry.
  228. * @return {Object} An object for monitoring geometry properties.
  229. */
  230. getGeometryData( geometry ) {
  231. let data = _geometryCache.get( geometry );
  232. if ( data === undefined ) {
  233. data = {
  234. _renderId: -1,
  235. _equal: false,
  236. attributes: this.getAttributesData( geometry.attributes ),
  237. indexId: geometry.index ? geometry.index.id : null,
  238. indexVersion: geometry.index ? geometry.index.version : null,
  239. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  240. };
  241. _geometryCache.set( geometry, data );
  242. }
  243. return data;
  244. }
  245. /**
  246. * Returns a material data structure holding the material property values for
  247. * monitoring.
  248. *
  249. * @param {Material} material - The material.
  250. * @return {Object} An object for monitoring material properties.
  251. */
  252. getMaterialData( material ) {
  253. let data = _materialCache.get( material );
  254. if ( data === undefined ) {
  255. data = { _renderId: -1, _equal: false };
  256. for ( const property of this.refreshUniforms ) {
  257. const value = material[ property ];
  258. if ( value === null || value === undefined ) continue;
  259. if ( typeof value === 'object' && value.clone !== undefined ) {
  260. if ( value.isTexture === true ) {
  261. data[ property ] = { id: value.id, version: value.version };
  262. } else {
  263. data[ property ] = value.clone();
  264. }
  265. } else {
  266. data[ property ] = value;
  267. }
  268. }
  269. _materialCache.set( material, data );
  270. }
  271. return data;
  272. }
  273. /**
  274. * Returns `true` if the given render object has not changed its state.
  275. *
  276. * @param {RenderObject} renderObject - The render object.
  277. * @param {Array<Light>} lightsData - The current material lights.
  278. * @param {number} renderId - The current render ID.
  279. * @return {boolean} Whether the given render object has changed its state or not.
  280. */
  281. equals( renderObject, lightsData, renderId ) {
  282. const { object, material, geometry } = renderObject;
  283. const renderObjectData = this.getRenderObjectData( renderObject );
  284. // world matrix
  285. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  286. renderObjectData.worldMatrix.copy( object.matrixWorld );
  287. return false;
  288. }
  289. // material
  290. const materialData = this.getMaterialData( renderObject.material );
  291. // check the material for the "equal" state just once per render for all render objects
  292. if ( materialData._renderId !== renderId ) {
  293. materialData._renderId = renderId;
  294. for ( const property in materialData ) {
  295. const value = materialData[ property ];
  296. const mtlValue = material[ property ];
  297. if ( property === '_renderId' ) continue;
  298. if ( property === '_equal' ) continue;
  299. if ( value.equals !== undefined ) {
  300. if ( value.equals( mtlValue ) === false ) {
  301. value.copy( mtlValue );
  302. materialData._equal = false;
  303. return false;
  304. }
  305. } else if ( mtlValue.isTexture === true ) {
  306. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  307. value.id = mtlValue.id;
  308. value.version = mtlValue.version;
  309. materialData._equal = false;
  310. return false;
  311. }
  312. } else if ( value !== mtlValue ) {
  313. materialData[ property ] = mtlValue;
  314. materialData._equal = false;
  315. return false;
  316. }
  317. }
  318. if ( materialData.transmission > 0 ) {
  319. const { width, height } = renderObject.context;
  320. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  321. renderObjectData.bufferWidth = width;
  322. renderObjectData.bufferHeight = height;
  323. materialData._equal = false;
  324. return false;
  325. }
  326. }
  327. materialData._equal = true;
  328. } else {
  329. if ( materialData._equal === false ) return false;
  330. }
  331. // geometry
  332. if ( renderObjectData.geometryId !== geometry.id ) {
  333. renderObjectData.geometryId = geometry.id;
  334. return false;
  335. }
  336. const geometryData = this.getGeometryData( renderObject.geometry );
  337. // check the geoemtry for the "equal" state just once per render for all render objects
  338. if ( geometryData._renderId !== renderId ) {
  339. geometryData._renderId = renderId;
  340. // attributes
  341. const attributes = geometry.attributes;
  342. const storedAttributes = geometryData.attributes;
  343. let currentAttributeCount = 0;
  344. let storedAttributeCount = 0;
  345. for ( const _ in attributes ) currentAttributeCount ++; // eslint-disable-line no-unused-vars
  346. for ( const name in storedAttributes ) {
  347. storedAttributeCount ++;
  348. const storedAttributeData = storedAttributes[ name ];
  349. const attribute = attributes[ name ];
  350. if ( attribute === undefined ) {
  351. // attribute was removed
  352. delete storedAttributes[ name ];
  353. geometryData._equal = false;
  354. return false;
  355. }
  356. if ( storedAttributeData.id !== attribute.id || storedAttributeData.version !== attribute.version ) {
  357. storedAttributeData.id = attribute.id;
  358. storedAttributeData.version = attribute.version;
  359. geometryData._equal = false;
  360. return false;
  361. }
  362. }
  363. if ( storedAttributeCount !== currentAttributeCount ) {
  364. geometryData.attributes = this.getAttributesData( attributes );
  365. geometryData._equal = false;
  366. return false;
  367. }
  368. // check index
  369. const index = geometry.index;
  370. const storedIndexId = geometryData.indexId;
  371. const storedIndexVersion = geometryData.indexVersion;
  372. const currentIndexId = index ? index.id : null;
  373. const currentIndexVersion = index ? index.version : null;
  374. if ( storedIndexId !== currentIndexId || storedIndexVersion !== currentIndexVersion ) {
  375. geometryData.indexId = currentIndexId;
  376. geometryData.indexVersion = currentIndexVersion;
  377. geometryData._equal = false;
  378. return false;
  379. }
  380. // check drawRange
  381. if ( geometryData.drawRange.start !== geometry.drawRange.start || geometryData.drawRange.count !== geometry.drawRange.count ) {
  382. geometryData.drawRange.start = geometry.drawRange.start;
  383. geometryData.drawRange.count = geometry.drawRange.count;
  384. geometryData._equal = false;
  385. return false;
  386. }
  387. geometryData._equal = true;
  388. } else {
  389. if ( geometryData._equal === false ) return false;
  390. }
  391. // morph targets
  392. if ( renderObjectData.morphTargetInfluences ) {
  393. let morphChanged = false;
  394. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  395. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  396. renderObjectData.morphTargetInfluences[ i ] = object.morphTargetInfluences[ i ];
  397. morphChanged = true;
  398. }
  399. }
  400. if ( morphChanged ) return false;
  401. }
  402. // lights
  403. if ( renderObjectData.lights ) {
  404. for ( let i = 0; i < lightsData.length; i ++ ) {
  405. if ( renderObjectData.lights[ i ].map !== lightsData[ i ].map ) {
  406. return false;
  407. }
  408. }
  409. }
  410. // center
  411. if ( renderObjectData.center ) {
  412. if ( renderObjectData.center.equals( object.center ) === false ) {
  413. renderObjectData.center.copy( object.center );
  414. return true;
  415. }
  416. }
  417. // bundle
  418. if ( renderObject.bundle !== null ) {
  419. renderObjectData.version = renderObject.bundle.version;
  420. }
  421. return true;
  422. }
  423. /**
  424. * Returns the lights data for the given material lights.
  425. *
  426. * @param {Array<Light>} materialLights - The material lights.
  427. * @return {Array<Object>} The lights data for the given material lights.
  428. */
  429. getLightsData( materialLights ) {
  430. const lights = [];
  431. for ( const light of materialLights ) {
  432. if ( light.isSpotLight === true && light.map !== null ) {
  433. // only add lights that have a map
  434. lights.push( { map: light.map.version } );
  435. }
  436. }
  437. return lights;
  438. }
  439. /**
  440. * Returns the lights for the given lights node and render ID.
  441. *
  442. * @param {LightsNode} lightsNode - The lights node.
  443. * @param {number} renderId - The render ID.
  444. * @return {Array<Object>} The lights for the given lights node and render ID.
  445. */
  446. getLights( lightsNode, renderId ) {
  447. if ( _lightsCache.has( lightsNode ) ) {
  448. const cached = _lightsCache.get( lightsNode );
  449. if ( cached.renderId === renderId ) {
  450. return cached.lightsData;
  451. }
  452. }
  453. const lightsData = this.getLightsData( lightsNode.getLights() );
  454. _lightsCache.set( lightsNode, { renderId, lightsData } );
  455. return lightsData;
  456. }
  457. /**
  458. * Checks if the given render object requires a refresh.
  459. *
  460. * @param {RenderObject} renderObject - The render object.
  461. * @param {NodeFrame} nodeFrame - The current node frame.
  462. * @return {boolean} Whether the given render object requires a refresh or not.
  463. */
  464. needsRefresh( renderObject, nodeFrame ) {
  465. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  466. return true;
  467. const { renderId } = nodeFrame;
  468. if ( this.renderId !== renderId ) {
  469. this.renderId = renderId;
  470. return true;
  471. }
  472. const isStatic = renderObject.object.static === true;
  473. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  474. if ( isStatic || isBundle )
  475. return false;
  476. const lightsData = this.getLights( renderObject.lightsNode, renderId );
  477. const notEqual = this.equals( renderObject, lightsData, renderId ) !== true;
  478. return notEqual;
  479. }
  480. }
  481. // Pre-compiled RegExp patterns for ignored files
  482. const IGNORED_FILES = [
  483. /^StackTrace\.js$/,
  484. /^TSLCore\.js$/,
  485. /^.*Node\.js$/,
  486. /^three\.webgpu.*\.js$/
  487. ];
  488. /**
  489. * Parses the stack trace and filters out ignored files.
  490. * Returns an array with function name, file, line, and column.
  491. */
  492. function getFilteredStack( stack ) {
  493. // Pattern to extract function name, file, line, and column from different browsers
  494. // Chrome: "at functionName (file.js:1:2)" or "at file.js:1:2"
  495. // Firefox: "functionName@file.js:1:2"
  496. const regex = /(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;
  497. return stack.split( '\n' )
  498. .map( line => {
  499. const match = line.match( regex );
  500. if ( ! match ) return null; // Skip if line format is invalid
  501. // Chrome: match[1], Firefox: match[2]
  502. const fn = match[ 1 ] || match[ 2 ] || '';
  503. const file = match[ 3 ].split( '?' )[ 0 ]; // Clean file name (Vite/HMR)
  504. const lineNum = parseInt( match[ 4 ], 10 );
  505. const column = parseInt( match[ 5 ], 10 );
  506. // Extract only the filename from full path
  507. const fileName = file.split( '/' ).pop();
  508. return {
  509. fn: fn,
  510. file: fileName,
  511. line: lineNum,
  512. column: column
  513. };
  514. } )
  515. .filter( frame => {
  516. // Only keep frames that are valid and not in the ignore list
  517. return frame && ! IGNORED_FILES.some( regex => regex.test( frame.file ) );
  518. } );
  519. }
  520. /**
  521. * Class representing a stack trace for debugging purposes.
  522. */
  523. class StackTrace {
  524. /**
  525. * Creates a StackTrace instance by capturing and filtering the current stack trace.
  526. *
  527. * @param {Error|string|null} stackMessage - An optional stack trace to use instead of capturing a new one.
  528. */
  529. constructor( stackMessage = null ) {
  530. /**
  531. * This flag can be used for type testing.
  532. *
  533. * @type {boolean}
  534. * @readonly
  535. * @default true
  536. */
  537. this.isStackTrace = true;
  538. /**
  539. * The stack trace.
  540. *
  541. * @type {Array<{fn: string, file: string, line: number, column: number}>}
  542. */
  543. this.stack = getFilteredStack( stackMessage ? stackMessage : new Error().stack );
  544. }
  545. /**
  546. * Returns a formatted location string of the top stack frame.
  547. *
  548. * @returns {string} The formatted stack trace message.
  549. */
  550. getLocation() {
  551. if ( this.stack.length === 0 ) {
  552. return '[Unknown location]';
  553. }
  554. const mainStack = this.stack[ 0 ];
  555. const fn = mainStack.fn;
  556. const fnName = fn ? `"${ fn }()" at ` : '';
  557. return `${fnName}"${mainStack.file}:${mainStack.line}"`; // :${mainStack.column}
  558. }
  559. /**
  560. * Returns the full error message including the stack trace.
  561. *
  562. * @param {string} message - The error message.
  563. * @returns {string} The full error message with stack trace.
  564. */
  565. getError( message ) {
  566. if ( this.stack.length === 0 ) {
  567. return message;
  568. }
  569. // Output: "Error: message\n at functionName (file.js:line:column)"
  570. const stackString = this.stack.map( frame => {
  571. const location = `${ frame.file }:${ frame.line }:${ frame.column }`;
  572. if ( frame.fn ) {
  573. return ` at ${ frame.fn } (${ location })`;
  574. }
  575. return ` at ${ location }`;
  576. } ).join( '\n' );
  577. return `${ message }\n${ stackString }`;
  578. }
  579. }
  580. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  581. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  582. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  583. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  584. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  585. function cyrb53( value, seed = 0 ) {
  586. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  587. if ( Array.isArray( value ) ) {
  588. for ( let i = 0, val; i < value.length; i ++ ) {
  589. val = value[ i ];
  590. h1 = Math.imul( h1 ^ val, 2654435761 );
  591. h2 = Math.imul( h2 ^ val, 1597334677 );
  592. }
  593. } else {
  594. for ( let i = 0, ch; i < value.length; i ++ ) {
  595. ch = value.charCodeAt( i );
  596. h1 = Math.imul( h1 ^ ch, 2654435761 );
  597. h2 = Math.imul( h2 ^ ch, 1597334677 );
  598. }
  599. }
  600. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  601. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  602. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  603. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  604. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  605. }
  606. /**
  607. * Computes a hash for the given string.
  608. *
  609. * @private
  610. * @method
  611. * @param {string} str - The string to be hashed.
  612. * @return {number} The hash.
  613. */
  614. const hashString = ( str ) => cyrb53( str );
  615. /**
  616. * Computes a hash for the given array.
  617. *
  618. * @private
  619. * @method
  620. * @param {Array<number>} array - The array to be hashed.
  621. * @return {number} The hash.
  622. */
  623. const hashArray = ( array ) => cyrb53( array );
  624. /**
  625. * Computes a hash for the given list of parameters.
  626. *
  627. * @private
  628. * @method
  629. * @param {...number} params - A list of parameters.
  630. * @return {number} The hash.
  631. */
  632. const hash$1 = ( ...params ) => cyrb53( params );
  633. const typeFromLength = /*@__PURE__*/ new Map( [
  634. [ 1, 'float' ],
  635. [ 2, 'vec2' ],
  636. [ 3, 'vec3' ],
  637. [ 4, 'vec4' ],
  638. [ 9, 'mat3' ],
  639. [ 16, 'mat4' ]
  640. ] );
  641. const dataFromObject = /*@__PURE__*/ new WeakMap();
  642. /**
  643. * Returns the data type for the given the length.
  644. *
  645. * @private
  646. * @method
  647. * @param {number} length - The length.
  648. * @return {string} The data type.
  649. */
  650. function getTypeFromLength( length ) {
  651. return typeFromLength.get( length );
  652. }
  653. /**
  654. * Returns the typed array for the given data type.
  655. *
  656. * @private
  657. * @method
  658. * @param {string} type - The data type.
  659. * @return {TypedArray} The typed array.
  660. */
  661. function getTypedArrayFromType( type ) {
  662. // Handle component type for vectors and matrices
  663. if ( /[iu]?vec\d/.test( type ) ) {
  664. // Handle int vectors
  665. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  666. // Handle uint vectors
  667. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  668. // Default to float vectors
  669. return Float32Array;
  670. }
  671. // Handle matrices (always float)
  672. if ( /mat\d/.test( type ) ) return Float32Array;
  673. // Basic types
  674. if ( /float/.test( type ) ) return Float32Array;
  675. if ( /uint/.test( type ) ) return Uint32Array;
  676. if ( /int/.test( type ) ) return Int32Array;
  677. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  678. }
  679. /**
  680. * Returns the length for the given data type.
  681. *
  682. * @private
  683. * @method
  684. * @param {string} type - The data type.
  685. * @return {number} The length.
  686. */
  687. function getLengthFromType( type ) {
  688. if ( /float|int|uint/.test( type ) ) return 1;
  689. if ( /vec2/.test( type ) ) return 2;
  690. if ( /vec3/.test( type ) ) return 3;
  691. if ( /vec4/.test( type ) ) return 4;
  692. if ( /mat2/.test( type ) ) return 4;
  693. if ( /mat3/.test( type ) ) return 9;
  694. if ( /mat4/.test( type ) ) return 16;
  695. error( `TSL: Unsupported type: ${ type }`, new StackTrace() );
  696. }
  697. /**
  698. * Returns the gpu memory length for the given data type.
  699. *
  700. * @private
  701. * @method
  702. * @param {string} type - The data type.
  703. * @return {number} The length.
  704. */
  705. function getMemoryLengthFromType( type ) {
  706. if ( /float|int|uint/.test( type ) ) return 1;
  707. if ( /vec2/.test( type ) ) return 2;
  708. if ( /vec3/.test( type ) ) return 3;
  709. if ( /vec4/.test( type ) ) return 4;
  710. if ( /mat2/.test( type ) ) return 4;
  711. if ( /mat3/.test( type ) ) return 12;
  712. if ( /mat4/.test( type ) ) return 16;
  713. error( `TSL: Unsupported type: ${ type }`, new StackTrace() );
  714. }
  715. /**
  716. * Returns the alignment requirement for the given data type.
  717. *
  718. * @private
  719. * @method
  720. * @param {string} type - The data type.
  721. * @return {number} The alignment requirement in bytes.
  722. */
  723. function getAlignmentFromType( type ) {
  724. if ( /float|int|uint/.test( type ) ) return 4;
  725. if ( /vec2/.test( type ) ) return 8;
  726. if ( /vec3/.test( type ) ) return 16;
  727. if ( /vec4/.test( type ) ) return 16;
  728. if ( /mat2/.test( type ) ) return 8;
  729. if ( /mat3/.test( type ) ) return 16;
  730. if ( /mat4/.test( type ) ) return 16;
  731. error( `TSL: Unsupported type: ${ type }`, new StackTrace() );
  732. }
  733. /**
  734. * Returns the data type for the given value.
  735. *
  736. * @private
  737. * @method
  738. * @param {any} value - The value.
  739. * @return {?string} The data type.
  740. */
  741. function getValueType( value ) {
  742. if ( value === undefined || value === null ) return null;
  743. const typeOf = typeof value;
  744. if ( value.isNode === true ) {
  745. return 'node';
  746. } else if ( typeOf === 'number' ) {
  747. return 'float';
  748. } else if ( typeOf === 'boolean' ) {
  749. return 'bool';
  750. } else if ( typeOf === 'string' ) {
  751. return 'string';
  752. } else if ( typeOf === 'function' ) {
  753. return 'shader';
  754. } else if ( value.isVector2 === true ) {
  755. return 'vec2';
  756. } else if ( value.isVector3 === true ) {
  757. return 'vec3';
  758. } else if ( value.isVector4 === true ) {
  759. return 'vec4';
  760. } else if ( value.isMatrix2 === true ) {
  761. return 'mat2';
  762. } else if ( value.isMatrix3 === true ) {
  763. return 'mat3';
  764. } else if ( value.isMatrix4 === true ) {
  765. return 'mat4';
  766. } else if ( value.isColor === true ) {
  767. return 'color';
  768. } else if ( value instanceof ArrayBuffer ) {
  769. return 'ArrayBuffer';
  770. }
  771. return null;
  772. }
  773. /**
  774. * Returns the value/object for the given data type and parameters.
  775. *
  776. * @private
  777. * @method
  778. * @param {string} type - The given type.
  779. * @param {...any} params - A parameter list.
  780. * @return {any} The value/object.
  781. */
  782. function getValueFromType( type, ...params ) {
  783. const last4 = type ? type.slice( -4 ) : undefined;
  784. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  785. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  786. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  787. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  788. }
  789. if ( type === 'color' ) {
  790. return new Color( ...params );
  791. } else if ( last4 === 'vec2' ) {
  792. return new Vector2( ...params );
  793. } else if ( last4 === 'vec3' ) {
  794. return new Vector3( ...params );
  795. } else if ( last4 === 'vec4' ) {
  796. return new Vector4( ...params );
  797. } else if ( last4 === 'mat2' ) {
  798. return new Matrix2( ...params );
  799. } else if ( last4 === 'mat3' ) {
  800. return new Matrix3( ...params );
  801. } else if ( last4 === 'mat4' ) {
  802. return new Matrix4( ...params );
  803. } else if ( type === 'bool' ) {
  804. return params[ 0 ] || false;
  805. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  806. return params[ 0 ] || 0;
  807. } else if ( type === 'string' ) {
  808. return params[ 0 ] || '';
  809. } else if ( type === 'ArrayBuffer' ) {
  810. return base64ToArrayBuffer( params[ 0 ] );
  811. }
  812. return null;
  813. }
  814. /**
  815. * Gets the object data that can be shared between different rendering steps.
  816. *
  817. * @private
  818. * @param {Object} object - The object to get the data for.
  819. * @return {Object} The object data.
  820. */
  821. function getDataFromObject( object ) {
  822. let data = dataFromObject.get( object );
  823. if ( data === undefined ) {
  824. data = {};
  825. dataFromObject.set( object, data );
  826. }
  827. return data;
  828. }
  829. /**
  830. * Converts the given array buffer to a Base64 string.
  831. *
  832. * @private
  833. * @method
  834. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  835. * @return {string} The Base64 string.
  836. */
  837. function arrayBufferToBase64( arrayBuffer ) {
  838. let chars = '';
  839. const array = new Uint8Array( arrayBuffer );
  840. for ( let i = 0; i < array.length; i ++ ) {
  841. chars += String.fromCharCode( array[ i ] );
  842. }
  843. return btoa( chars );
  844. }
  845. /**
  846. * Converts the given Base64 string to an array buffer.
  847. *
  848. * @private
  849. * @method
  850. * @param {string} base64 - The Base64 string.
  851. * @return {ArrayBuffer} The array buffer.
  852. */
  853. function base64ToArrayBuffer( base64 ) {
  854. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  855. }
  856. var NodeUtils = /*#__PURE__*/Object.freeze({
  857. __proto__: null,
  858. arrayBufferToBase64: arrayBufferToBase64,
  859. base64ToArrayBuffer: base64ToArrayBuffer,
  860. getAlignmentFromType: getAlignmentFromType,
  861. getDataFromObject: getDataFromObject,
  862. getLengthFromType: getLengthFromType,
  863. getMemoryLengthFromType: getMemoryLengthFromType,
  864. getTypeFromLength: getTypeFromLength,
  865. getTypedArrayFromType: getTypedArrayFromType,
  866. getValueFromType: getValueFromType,
  867. getValueType: getValueType,
  868. hash: hash$1,
  869. hashArray: hashArray,
  870. hashString: hashString
  871. });
  872. /**
  873. * Possible shader stages.
  874. *
  875. * @property {string} VERTEX The vertex shader stage.
  876. * @property {string} FRAGMENT The fragment shader stage.
  877. */
  878. const NodeShaderStage = {
  879. VERTEX: 'vertex',
  880. FRAGMENT: 'fragment'
  881. };
  882. /**
  883. * Update types of a node.
  884. *
  885. * @property {string} NONE The update method is not executed.
  886. * @property {string} FRAME The update method is executed per frame.
  887. * @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.
  888. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  889. */
  890. const NodeUpdateType = {
  891. NONE: 'none',
  892. FRAME: 'frame',
  893. RENDER: 'render',
  894. OBJECT: 'object'
  895. };
  896. /**
  897. * Data types of a node.
  898. *
  899. * @property {string} BOOLEAN Boolean type.
  900. * @property {string} INTEGER Integer type.
  901. * @property {string} FLOAT Float type.
  902. * @property {string} VECTOR2 Two-dimensional vector type.
  903. * @property {string} VECTOR3 Three-dimensional vector type.
  904. * @property {string} VECTOR4 Four-dimensional vector type.
  905. * @property {string} MATRIX2 2x2 matrix type.
  906. * @property {string} MATRIX3 3x3 matrix type.
  907. * @property {string} MATRIX4 4x4 matrix type.
  908. */
  909. const NodeType = {
  910. BOOLEAN: 'bool',
  911. INTEGER: 'int',
  912. FLOAT: 'float',
  913. VECTOR2: 'vec2',
  914. VECTOR3: 'vec3',
  915. VECTOR4: 'vec4',
  916. MATRIX2: 'mat2',
  917. MATRIX3: 'mat3',
  918. MATRIX4: 'mat4'
  919. };
  920. /**
  921. * Access types of a node. These are relevant for compute and storage usage.
  922. *
  923. * @property {string} READ_ONLY Read-only access
  924. * @property {string} WRITE_ONLY Write-only access.
  925. * @property {string} READ_WRITE Read and write access.
  926. */
  927. const NodeAccess = {
  928. READ_ONLY: 'readOnly',
  929. WRITE_ONLY: 'writeOnly',
  930. READ_WRITE: 'readWrite',
  931. };
  932. const defaultShaderStages = [ 'fragment', 'vertex' ];
  933. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  934. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  935. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  936. const _parentBuildStage = {
  937. analyze: 'setup',
  938. generate: 'analyze'
  939. };
  940. let _nodeId = 0;
  941. /**
  942. * Base class for all nodes.
  943. *
  944. * @augments EventDispatcher
  945. */
  946. class Node extends EventDispatcher {
  947. static get type() {
  948. return 'Node';
  949. }
  950. /**
  951. * Constructs a new node.
  952. *
  953. * @param {?string} nodeType - The node type.
  954. */
  955. constructor( nodeType = null ) {
  956. super();
  957. /**
  958. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  959. *
  960. * @type {?string}
  961. * @default null
  962. */
  963. this.nodeType = nodeType;
  964. /**
  965. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  966. *
  967. * @type {string}
  968. * @default 'none'
  969. */
  970. this.updateType = NodeUpdateType.NONE;
  971. /**
  972. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  973. *
  974. * @type {string}
  975. * @default 'none'
  976. */
  977. this.updateBeforeType = NodeUpdateType.NONE;
  978. /**
  979. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  980. *
  981. * @type {string}
  982. * @default 'none'
  983. */
  984. this.updateAfterType = NodeUpdateType.NONE;
  985. /**
  986. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  987. *
  988. * @type {number}
  989. * @readonly
  990. * @default 0
  991. */
  992. this.version = 0;
  993. /**
  994. * The name of the node.
  995. *
  996. * @type {string}
  997. * @default ''
  998. */
  999. this.name = '';
  1000. /**
  1001. * Whether this node is global or not. This property is relevant for the internal
  1002. * node caching system. All nodes which should be declared just once should
  1003. * set this flag to `true` (a typical example is {@link AttributeNode}).
  1004. *
  1005. * @type {boolean}
  1006. * @default false
  1007. */
  1008. this.global = false;
  1009. /**
  1010. * Create a list of parents for this node during the build process.
  1011. *
  1012. * @type {boolean}
  1013. * @default false
  1014. */
  1015. this.parents = false;
  1016. /**
  1017. * This flag can be used for type testing.
  1018. *
  1019. * @type {boolean}
  1020. * @readonly
  1021. * @default true
  1022. */
  1023. this.isNode = true;
  1024. // private
  1025. this._beforeNodes = null;
  1026. /**
  1027. * The cache key of this node.
  1028. *
  1029. * @private
  1030. * @type {?number}
  1031. * @default null
  1032. */
  1033. this._cacheKey = null;
  1034. /**
  1035. * The UUID of the node.
  1036. *
  1037. * @type {string}
  1038. * @default null
  1039. * @private
  1040. */
  1041. this._uuid = null;
  1042. /**
  1043. * The cache key's version.
  1044. *
  1045. * @private
  1046. * @type {number}
  1047. * @default 0
  1048. */
  1049. this._cacheKeyVersion = 0;
  1050. /**
  1051. * The unique ID of the node.
  1052. *
  1053. * @type {number}
  1054. * @readonly
  1055. */
  1056. this.id = _nodeId ++;
  1057. /**
  1058. * The stack trace of the node for debugging purposes.
  1059. *
  1060. * @type {?string}
  1061. * @default null
  1062. */
  1063. this.stackTrace = null;
  1064. if ( Node.captureStackTrace === true ) {
  1065. this.stackTrace = new StackTrace();
  1066. }
  1067. }
  1068. /**
  1069. * Set this property to `true` when the node should be regenerated.
  1070. *
  1071. * @type {boolean}
  1072. * @default false
  1073. * @param {boolean} value
  1074. */
  1075. set needsUpdate( value ) {
  1076. if ( value === true ) {
  1077. this.version ++;
  1078. }
  1079. }
  1080. /**
  1081. * The UUID of the node.
  1082. *
  1083. * @type {string}
  1084. * @readonly
  1085. */
  1086. get uuid() {
  1087. if ( this._uuid === null ) {
  1088. this._uuid = MathUtils.generateUUID();
  1089. }
  1090. return this._uuid;
  1091. }
  1092. /**
  1093. * The type of the class. The value is usually the constructor name.
  1094. *
  1095. * @type {string}
  1096. * @readonly
  1097. */
  1098. get type() {
  1099. return this.constructor.type;
  1100. }
  1101. /**
  1102. * Convenient method for defining {@link Node#update}.
  1103. *
  1104. * @param {Function} callback - The update method.
  1105. * @param {string} updateType - The update type.
  1106. * @return {Node} A reference to this node.
  1107. */
  1108. onUpdate( callback, updateType ) {
  1109. this.updateType = updateType;
  1110. this.update = callback.bind( this );
  1111. return this;
  1112. }
  1113. /**
  1114. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1115. * this method automatically sets the update type to `FRAME`.
  1116. *
  1117. * @param {Function} callback - The update method.
  1118. * @return {Node} A reference to this node.
  1119. */
  1120. onFrameUpdate( callback ) {
  1121. return this.onUpdate( callback, NodeUpdateType.FRAME );
  1122. }
  1123. /**
  1124. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1125. * this method automatically sets the update type to `RENDER`.
  1126. *
  1127. * @param {Function} callback - The update method.
  1128. * @return {Node} A reference to this node.
  1129. */
  1130. onRenderUpdate( callback ) {
  1131. return this.onUpdate( callback, NodeUpdateType.RENDER );
  1132. }
  1133. /**
  1134. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1135. * this method automatically sets the update type to `OBJECT`.
  1136. *
  1137. * @param {Function} callback - The update method.
  1138. * @return {Node} A reference to this node.
  1139. */
  1140. onObjectUpdate( callback ) {
  1141. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  1142. }
  1143. /**
  1144. * Convenient method for defining {@link Node#updateReference}.
  1145. *
  1146. * @param {Function} callback - The update method.
  1147. * @return {Node} A reference to this node.
  1148. */
  1149. onReference( callback ) {
  1150. this.updateReference = callback.bind( this );
  1151. return this;
  1152. }
  1153. /**
  1154. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  1155. * to such objects based on a given state (e.g. the current node frame or builder).
  1156. *
  1157. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  1158. * @return {any} The updated reference.
  1159. */
  1160. updateReference( /*state*/ ) {
  1161. return this;
  1162. }
  1163. /**
  1164. * By default this method returns the value of the {@link Node#global} flag. This method
  1165. * can be overwritten in derived classes if an analytical way is required to determine the
  1166. * global cache referring to the current shader-stage.
  1167. *
  1168. * @param {NodeBuilder} builder - The current node builder.
  1169. * @return {boolean} Whether this node is global or not.
  1170. */
  1171. isGlobal( /*builder*/ ) {
  1172. return this.global;
  1173. }
  1174. /**
  1175. * Generator function that can be used to iterate over the child nodes.
  1176. *
  1177. * @generator
  1178. * @yields {Node} A child node.
  1179. */
  1180. * getChildren() {
  1181. for ( const { childNode } of this._getChildren() ) {
  1182. yield childNode;
  1183. }
  1184. }
  1185. /**
  1186. * Calling this method dispatches the `dispose` event. This event can be used
  1187. * to register event listeners for clean up tasks.
  1188. */
  1189. dispose() {
  1190. this.dispatchEvent( { type: 'dispose' } );
  1191. }
  1192. /**
  1193. * Callback for {@link Node#traverse}.
  1194. *
  1195. * @callback traverseCallback
  1196. * @param {Node} node - The current node.
  1197. */
  1198. /**
  1199. * Can be used to traverse through the node's hierarchy.
  1200. *
  1201. * @param {traverseCallback} callback - A callback that is executed per node.
  1202. */
  1203. traverse( callback ) {
  1204. callback( this );
  1205. for ( const childNode of this.getChildren() ) {
  1206. childNode.traverse( callback );
  1207. }
  1208. }
  1209. /**
  1210. * Returns the child nodes of this node.
  1211. *
  1212. * @private
  1213. * @param {Set<Node>} [ignores=new Set()] - A set of nodes to ignore during the search to avoid circular references.
  1214. * @returns {Array<Object>} An array of objects describing the child nodes.
  1215. */
  1216. _getChildren( ignores = new Set() ) {
  1217. const children = [];
  1218. // avoid circular references
  1219. ignores.add( this );
  1220. for ( const property of Object.getOwnPropertyNames( this ) ) {
  1221. const object = this[ property ];
  1222. // Ignore private properties and ignored nodes.
  1223. if ( property.startsWith( '_' ) === true || ignores.has( object ) ) continue;
  1224. if ( Array.isArray( object ) === true ) {
  1225. for ( let i = 0; i < object.length; i ++ ) {
  1226. const child = object[ i ];
  1227. if ( child && child.isNode === true ) {
  1228. children.push( { property, index: i, childNode: child } );
  1229. }
  1230. }
  1231. } else if ( object && object.isNode === true ) {
  1232. children.push( { property, childNode: object } );
  1233. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  1234. for ( const subProperty in object ) {
  1235. // Ignore private sub-properties.
  1236. if ( subProperty.startsWith( '_' ) === true ) continue;
  1237. const child = object[ subProperty ];
  1238. if ( child && child.isNode === true ) {
  1239. children.push( { property, index: subProperty, childNode: child } );
  1240. }
  1241. }
  1242. }
  1243. }
  1244. //
  1245. return children;
  1246. }
  1247. /**
  1248. * Returns the cache key for this node.
  1249. *
  1250. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1251. * @param {Set<Node>} [ignores=null] - A set of nodes to ignore during the computation of the cache key.
  1252. * @return {number} The cache key of the node.
  1253. */
  1254. getCacheKey( force = false, ignores = null ) {
  1255. force = force || this.version !== this._cacheKeyVersion;
  1256. if ( force === true || this._cacheKey === null ) {
  1257. if ( ignores === null ) ignores = new Set();
  1258. //
  1259. const values = [];
  1260. for ( const { property, childNode } of this._getChildren( ignores ) ) {
  1261. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey( force, ignores ) );
  1262. }
  1263. //
  1264. this._cacheKey = hash$1( hashArray( values ), this.customCacheKey() );
  1265. this._cacheKeyVersion = this.version;
  1266. }
  1267. return this._cacheKey;
  1268. }
  1269. /**
  1270. * Generate a custom cache key for this node.
  1271. *
  1272. * @return {number} The cache key of the node.
  1273. */
  1274. customCacheKey() {
  1275. return this.id;
  1276. }
  1277. /**
  1278. * Returns the references to this node which is by default `this`.
  1279. *
  1280. * @return {Node} A reference to this node.
  1281. */
  1282. getScope() {
  1283. return this;
  1284. }
  1285. /**
  1286. * Returns the hash of the node which is used to identify the node. By default it's
  1287. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1288. * depending on their implementation.
  1289. *
  1290. * @param {NodeBuilder} builder - The current node builder.
  1291. * @return {string} The hash.
  1292. */
  1293. getHash( /*builder*/ ) {
  1294. return String( this.id );
  1295. }
  1296. /**
  1297. * Returns the update type of {@link Node#update}.
  1298. *
  1299. * @return {NodeUpdateType} The update type.
  1300. */
  1301. getUpdateType() {
  1302. return this.updateType;
  1303. }
  1304. /**
  1305. * Returns the update type of {@link Node#updateBefore}.
  1306. *
  1307. * @return {NodeUpdateType} The update type.
  1308. */
  1309. getUpdateBeforeType() {
  1310. return this.updateBeforeType;
  1311. }
  1312. /**
  1313. * Returns the update type of {@link Node#updateAfter}.
  1314. *
  1315. * @return {NodeUpdateType} The update type.
  1316. */
  1317. getUpdateAfterType() {
  1318. return this.updateAfterType;
  1319. }
  1320. /**
  1321. * Certain types are composed of multiple elements. For example a `vec3`
  1322. * is composed of three `float` values. This method returns the type of
  1323. * these elements.
  1324. *
  1325. * @param {NodeBuilder} builder - The current node builder.
  1326. * @return {string} The type of the node.
  1327. */
  1328. getElementType( builder ) {
  1329. const type = this.getNodeType( builder );
  1330. const elementType = builder.getElementType( type );
  1331. return elementType;
  1332. }
  1333. /**
  1334. * Returns the node member type for the given name.
  1335. *
  1336. * @param {NodeBuilder} builder - The current node builder.
  1337. * @param {string} name - The name of the member.
  1338. * @return {string} The type of the node.
  1339. */
  1340. getMemberType( /*builder, name*/ ) {
  1341. return 'void';
  1342. }
  1343. /**
  1344. * Returns the node's type.
  1345. *
  1346. * @param {NodeBuilder} builder - The current node builder.
  1347. * @param {string} [output=null] - The output of the node.
  1348. * @return {string} The type of the node.
  1349. */
  1350. getNodeType( builder, output = null ) {
  1351. const nodeData = builder.getDataFromNode( this );
  1352. let type;
  1353. if ( output !== null ) {
  1354. nodeData.typeFromOutput = nodeData.typeFromOutput || {};
  1355. type = nodeData.typeFromOutput[ output ];
  1356. if ( type === undefined ) {
  1357. type = this.generateNodeType( builder, output );
  1358. nodeData.typeFromOutput[ output ] = type;
  1359. }
  1360. } else {
  1361. type = nodeData.type;
  1362. if ( type === undefined ) {
  1363. type = this.generateNodeType( builder );
  1364. nodeData.type = type;
  1365. }
  1366. }
  1367. return type;
  1368. }
  1369. /**
  1370. * Returns the node's type.
  1371. *
  1372. * @param {NodeBuilder} builder - The current node builder.
  1373. * @param {string} [output=null] - The output of the node.
  1374. * @return {string} The type of the node.
  1375. */
  1376. generateNodeType( builder, output = null ) {
  1377. const nodeProperties = builder.getNodeProperties( this );
  1378. if ( nodeProperties.outputNode ) {
  1379. return nodeProperties.outputNode.getNodeType( builder, output );
  1380. }
  1381. return this.nodeType;
  1382. }
  1383. /**
  1384. * This method is used during the build process of a node and ensures
  1385. * equal nodes are not built multiple times but just once. For example if
  1386. * `attribute( 'uv' )` is used multiple times by the user, the build
  1387. * process makes sure to process just the first node.
  1388. *
  1389. * @param {NodeBuilder} builder - The current node builder.
  1390. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1391. */
  1392. getShared( builder ) {
  1393. const hash = this.getHash( builder );
  1394. const nodeFromHash = builder.getNodeFromHash( hash );
  1395. return nodeFromHash || this;
  1396. }
  1397. /**
  1398. * Returns the number of elements in the node array.
  1399. *
  1400. * @param {NodeBuilder} builder - The current node builder.
  1401. * @return {?number} The number of elements in the node array.
  1402. */
  1403. getArrayCount( /*builder*/ ) {
  1404. return null;
  1405. }
  1406. /**
  1407. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1408. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1409. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1410. *
  1411. * @param {NodeBuilder} builder - The current node builder.
  1412. * @return {?Node} The output node.
  1413. */
  1414. setup( builder ) {
  1415. const nodeProperties = builder.getNodeProperties( this );
  1416. let index = 0;
  1417. for ( const childNode of this.getChildren() ) {
  1418. nodeProperties[ 'node' + index ++ ] = childNode;
  1419. }
  1420. // return a outputNode if exists or null
  1421. return nodeProperties.outputNode || null;
  1422. }
  1423. /**
  1424. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1425. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1426. *
  1427. * @param {NodeBuilder} builder - The current node builder.
  1428. * @param {?Node} output - The target output node.
  1429. */
  1430. analyze( builder, output = null ) {
  1431. const usageCount = builder.increaseUsage( this );
  1432. if ( this.parents === true ) {
  1433. const nodeData = builder.getDataFromNode( this, 'any' );
  1434. nodeData.stages = nodeData.stages || {};
  1435. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1436. nodeData.stages[ builder.shaderStage ].push( output );
  1437. }
  1438. if ( usageCount === 1 ) {
  1439. // node flow children
  1440. const nodeProperties = builder.getNodeProperties( this );
  1441. for ( const childNode of Object.values( nodeProperties ) ) {
  1442. if ( childNode && childNode.isNode === true ) {
  1443. childNode.build( builder, this );
  1444. }
  1445. }
  1446. }
  1447. }
  1448. /**
  1449. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1450. * This state builds the output node and returns the resulting shader string.
  1451. *
  1452. * @param {NodeBuilder} builder - The current node builder.
  1453. * @param {?string} [output] - Can be used to define the output type.
  1454. * @return {?string} The generated shader string.
  1455. */
  1456. generate( builder, output ) {
  1457. const { outputNode } = builder.getNodeProperties( this );
  1458. if ( outputNode && outputNode.isNode === true ) {
  1459. return outputNode.build( builder, output );
  1460. }
  1461. }
  1462. /**
  1463. * The method can be implemented to update the node's internal state before it is used to render an object.
  1464. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1465. *
  1466. * @abstract
  1467. * @param {NodeFrame} frame - A reference to the current node frame.
  1468. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1469. */
  1470. updateBefore( /*frame*/ ) {
  1471. warn( 'Abstract function.' );
  1472. }
  1473. /**
  1474. * The method can be implemented to update the node's internal state after it was used to render an object.
  1475. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1476. *
  1477. * @abstract
  1478. * @param {NodeFrame} frame - A reference to the current node frame.
  1479. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1480. */
  1481. updateAfter( /*frame*/ ) {
  1482. warn( 'Abstract function.' );
  1483. }
  1484. /**
  1485. * The method can be implemented to update the node's internal state when it is used to render an object.
  1486. * The {@link Node#updateType} property defines how often the update is executed.
  1487. *
  1488. * @abstract
  1489. * @param {NodeFrame} frame - A reference to the current node frame.
  1490. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1491. */
  1492. update( /*frame*/ ) {
  1493. warn( 'Abstract function.' );
  1494. }
  1495. before( node ) {
  1496. if ( this._beforeNodes === null ) this._beforeNodes = [];
  1497. this._beforeNodes.push( node );
  1498. return this;
  1499. }
  1500. /**
  1501. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1502. * - **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.
  1503. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1504. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1505. *
  1506. * @param {NodeBuilder} builder - The current node builder.
  1507. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1508. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1509. */
  1510. build( builder, output = null ) {
  1511. const refNode = this.getShared( builder );
  1512. if ( this !== refNode ) {
  1513. return refNode.build( builder, output );
  1514. }
  1515. //
  1516. if ( this._beforeNodes !== null ) {
  1517. const currentBeforeNodes = this._beforeNodes;
  1518. this._beforeNodes = null;
  1519. for ( const beforeNode of currentBeforeNodes ) {
  1520. beforeNode.build( builder, output );
  1521. }
  1522. this._beforeNodes = currentBeforeNodes;
  1523. }
  1524. //
  1525. const nodeData = builder.getDataFromNode( this );
  1526. nodeData.buildStages = nodeData.buildStages || {};
  1527. nodeData.buildStages[ builder.buildStage ] = true;
  1528. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1529. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1530. // force parent build stage (setup or analyze)
  1531. const previousBuildStage = builder.getBuildStage();
  1532. builder.setBuildStage( parentBuildStage );
  1533. this.build( builder );
  1534. builder.setBuildStage( previousBuildStage );
  1535. }
  1536. //
  1537. builder.addChain( this );
  1538. /* Build stages expected results:
  1539. - "setup" -> Node
  1540. - "analyze" -> null
  1541. - "generate" -> String
  1542. */
  1543. let result = null;
  1544. const buildStage = builder.getBuildStage();
  1545. if ( buildStage === 'setup' ) {
  1546. builder.addNode( this );
  1547. this.updateReference( builder );
  1548. const properties = builder.getNodeProperties( this );
  1549. if ( properties.initialized !== true ) {
  1550. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1551. properties.initialized = true;
  1552. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1553. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1554. // !! no outputNode !!
  1555. //outputNode = builder.stack;
  1556. }*/
  1557. for ( const childNode of Object.values( properties ) ) {
  1558. if ( childNode && childNode.isNode === true ) {
  1559. if ( childNode.parents === true ) {
  1560. const childProperties = builder.getNodeProperties( childNode );
  1561. childProperties.parents = childProperties.parents || [];
  1562. childProperties.parents.push( this );
  1563. }
  1564. childNode.build( builder );
  1565. }
  1566. }
  1567. builder.addSequentialNode( this );
  1568. }
  1569. result = properties.outputNode;
  1570. } else if ( buildStage === 'analyze' ) {
  1571. this.analyze( builder, output );
  1572. } else if ( buildStage === 'generate' ) {
  1573. // If generate has just one argument, it means the output type is not required.
  1574. // This means that the node does not handle output conversions internally,
  1575. // so the value is stored in a cache and the builder handles the conversion
  1576. // for all requested output types.
  1577. const isGenerateOnce = this.generate.length < 2;
  1578. if ( isGenerateOnce ) {
  1579. const type = this.getNodeType( builder );
  1580. const nodeData = builder.getDataFromNode( this );
  1581. result = nodeData.snippet;
  1582. if ( result === undefined ) {
  1583. if ( nodeData.generated === undefined ) {
  1584. nodeData.generated = true;
  1585. result = this.generate( builder ) || '';
  1586. nodeData.snippet = result;
  1587. } else {
  1588. warn( 'Node: Recursion detected.', this );
  1589. result = '/* Recursion detected. */';
  1590. }
  1591. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1592. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1593. }
  1594. result = builder.format( result, type, output );
  1595. } else {
  1596. result = this.generate( builder, output ) || '';
  1597. }
  1598. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1599. // if no snippet is generated, return a default value
  1600. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1601. result = builder.generateConst( output );
  1602. }
  1603. }
  1604. builder.removeChain( this );
  1605. return result;
  1606. }
  1607. /**
  1608. * Returns the child nodes as a JSON object.
  1609. *
  1610. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1611. */
  1612. getSerializeChildren() {
  1613. return this._getChildren();
  1614. }
  1615. /**
  1616. * Serializes the node to JSON.
  1617. *
  1618. * @param {Object} json - The output JSON object.
  1619. */
  1620. serialize( json ) {
  1621. const nodeChildren = this.getSerializeChildren();
  1622. const inputNodes = {};
  1623. for ( const { property, index, childNode } of nodeChildren ) {
  1624. if ( index !== undefined ) {
  1625. if ( inputNodes[ property ] === undefined ) {
  1626. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1627. }
  1628. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1629. } else {
  1630. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1631. }
  1632. }
  1633. if ( Object.keys( inputNodes ).length > 0 ) {
  1634. json.inputNodes = inputNodes;
  1635. }
  1636. }
  1637. /**
  1638. * Deserializes the node from the given JSON.
  1639. *
  1640. * @param {Object} json - The JSON object.
  1641. */
  1642. deserialize( json ) {
  1643. if ( json.inputNodes !== undefined ) {
  1644. const nodes = json.meta.nodes;
  1645. for ( const property in json.inputNodes ) {
  1646. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1647. const inputArray = [];
  1648. for ( const uuid of json.inputNodes[ property ] ) {
  1649. inputArray.push( nodes[ uuid ] );
  1650. }
  1651. this[ property ] = inputArray;
  1652. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1653. const inputObject = {};
  1654. for ( const subProperty in json.inputNodes[ property ] ) {
  1655. const uuid = json.inputNodes[ property ][ subProperty ];
  1656. inputObject[ subProperty ] = nodes[ uuid ];
  1657. }
  1658. this[ property ] = inputObject;
  1659. } else {
  1660. const uuid = json.inputNodes[ property ];
  1661. this[ property ] = nodes[ uuid ];
  1662. }
  1663. }
  1664. }
  1665. }
  1666. /**
  1667. * Serializes the node into the three.js JSON Object/Scene format.
  1668. *
  1669. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1670. * @return {Object} The serialized node.
  1671. */
  1672. toJSON( meta ) {
  1673. const { uuid, type } = this;
  1674. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1675. if ( isRoot ) {
  1676. meta = {
  1677. textures: {},
  1678. images: {},
  1679. nodes: {}
  1680. };
  1681. }
  1682. // serialize
  1683. let data = meta.nodes[ uuid ];
  1684. if ( data === undefined ) {
  1685. data = {
  1686. uuid,
  1687. type,
  1688. meta,
  1689. metadata: {
  1690. version: 4.7,
  1691. type: 'Node',
  1692. generator: 'Node.toJSON'
  1693. }
  1694. };
  1695. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1696. this.serialize( data );
  1697. delete data.meta;
  1698. }
  1699. // TODO: Copied from Object3D.toJSON
  1700. function extractFromCache( cache ) {
  1701. const values = [];
  1702. for ( const key in cache ) {
  1703. const data = cache[ key ];
  1704. delete data.metadata;
  1705. values.push( data );
  1706. }
  1707. return values;
  1708. }
  1709. if ( isRoot ) {
  1710. const textures = extractFromCache( meta.textures );
  1711. const images = extractFromCache( meta.images );
  1712. const nodes = extractFromCache( meta.nodes );
  1713. if ( textures.length > 0 ) data.textures = textures;
  1714. if ( images.length > 0 ) data.images = images;
  1715. if ( nodes.length > 0 ) data.nodes = nodes;
  1716. }
  1717. return data;
  1718. }
  1719. }
  1720. /**
  1721. * Enables or disables the automatic capturing of stack traces for nodes.
  1722. *
  1723. * @type {boolean}
  1724. * @default false
  1725. */
  1726. Node.captureStackTrace = false;
  1727. /**
  1728. * Base class for representing element access on an array-like
  1729. * node data structures.
  1730. *
  1731. * @augments Node
  1732. */
  1733. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1734. static get type() {
  1735. return 'ArrayElementNode';
  1736. }
  1737. /**
  1738. * Constructs an array element node.
  1739. *
  1740. * @param {Node} node - The array-like node.
  1741. * @param {Node} indexNode - The index node that defines the element access.
  1742. */
  1743. constructor( node, indexNode ) {
  1744. super();
  1745. /**
  1746. * The array-like node.
  1747. *
  1748. * @type {Node}
  1749. */
  1750. this.node = node;
  1751. /**
  1752. * The index node that defines the element access.
  1753. *
  1754. * @type {Node}
  1755. */
  1756. this.indexNode = indexNode;
  1757. /**
  1758. * This flag can be used for type testing.
  1759. *
  1760. * @type {boolean}
  1761. * @readonly
  1762. * @default true
  1763. */
  1764. this.isArrayElementNode = true;
  1765. }
  1766. /**
  1767. * This method is overwritten since the node type is inferred from the array-like node.
  1768. *
  1769. * @param {NodeBuilder} builder - The current node builder.
  1770. * @return {string} The node type.
  1771. */
  1772. generateNodeType( builder ) {
  1773. return this.node.getElementType( builder );
  1774. }
  1775. /**
  1776. * This method is overwritten since the member type is inferred from the array-like node.
  1777. *
  1778. * @param {NodeBuilder} builder - The current node builder.
  1779. * @param {string} name - The member name.
  1780. * @return {string} The member type.
  1781. */
  1782. getMemberType( builder, name ) {
  1783. return this.node.getMemberType( builder, name );
  1784. }
  1785. generate( builder ) {
  1786. const indexType = this.indexNode.getNodeType( builder );
  1787. const nodeSnippet = this.node.build( builder );
  1788. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1789. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1790. }
  1791. }
  1792. /**
  1793. * This module is part of the TSL core and usually not used in app level code.
  1794. * It represents a convert operation during the shader generation process
  1795. * meaning it converts the data type of a node to a target data type.
  1796. *
  1797. * @augments Node
  1798. */
  1799. class ConvertNode extends Node {
  1800. static get type() {
  1801. return 'ConvertNode';
  1802. }
  1803. /**
  1804. * Constructs a new convert node.
  1805. *
  1806. * @param {Node} node - The node which type should be converted.
  1807. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1808. */
  1809. constructor( node, convertTo ) {
  1810. super();
  1811. /**
  1812. * The node which type should be converted.
  1813. *
  1814. * @type {Node}
  1815. */
  1816. this.node = node;
  1817. /**
  1818. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1819. *
  1820. * @type {string}
  1821. */
  1822. this.convertTo = convertTo;
  1823. }
  1824. /**
  1825. * This method is overwritten since the implementation tries to infer the best
  1826. * matching type from the {@link ConvertNode#convertTo} property.
  1827. *
  1828. * @param {NodeBuilder} builder - The current node builder.
  1829. * @return {string} The node type.
  1830. */
  1831. generateNodeType( builder ) {
  1832. const requestType = this.node.getNodeType( builder );
  1833. let convertTo = null;
  1834. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1835. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1836. convertTo = overloadingType;
  1837. }
  1838. }
  1839. return convertTo;
  1840. }
  1841. serialize( data ) {
  1842. super.serialize( data );
  1843. data.convertTo = this.convertTo;
  1844. }
  1845. deserialize( data ) {
  1846. super.deserialize( data );
  1847. this.convertTo = data.convertTo;
  1848. }
  1849. generate( builder, output ) {
  1850. const node = this.node;
  1851. const type = this.getNodeType( builder );
  1852. const snippet = node.build( builder, type );
  1853. return builder.format( snippet, type, output );
  1854. }
  1855. }
  1856. /**
  1857. * This module uses cache management to create temporary variables
  1858. * if the node is used more than once to prevent duplicate calculations.
  1859. *
  1860. * The class acts as a base class for many other nodes types.
  1861. *
  1862. * @augments Node
  1863. */
  1864. class TempNode extends Node {
  1865. static get type() {
  1866. return 'TempNode';
  1867. }
  1868. /**
  1869. * Constructs a temp node.
  1870. *
  1871. * @param {?string} nodeType - The node type.
  1872. */
  1873. constructor( nodeType = null ) {
  1874. super( nodeType );
  1875. /**
  1876. * This flag can be used for type testing.
  1877. *
  1878. * @type {boolean}
  1879. * @readonly
  1880. * @default true
  1881. */
  1882. this.isTempNode = true;
  1883. }
  1884. /**
  1885. * Whether this node is used more than once in context of other nodes.
  1886. *
  1887. * @param {NodeBuilder} builder - The node builder.
  1888. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1889. */
  1890. hasDependencies( builder ) {
  1891. return builder.getDataFromNode( this ).usageCount > 1;
  1892. }
  1893. build( builder, output ) {
  1894. const buildStage = builder.getBuildStage();
  1895. if ( buildStage === 'generate' ) {
  1896. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1897. const nodeData = builder.getDataFromNode( this );
  1898. if ( nodeData.propertyName !== undefined ) {
  1899. return builder.format( nodeData.propertyName, type, output );
  1900. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1901. const snippet = super.build( builder, type );
  1902. const nodeVar = builder.getVarFromNode( this, null, type );
  1903. const propertyName = builder.getPropertyName( nodeVar );
  1904. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1905. nodeData.snippet = snippet;
  1906. nodeData.propertyName = propertyName;
  1907. return builder.format( nodeData.propertyName, type, output );
  1908. }
  1909. }
  1910. return super.build( builder, output );
  1911. }
  1912. }
  1913. /**
  1914. * This module is part of the TSL core and usually not used in app level code.
  1915. * It represents a join operation during the shader generation process.
  1916. * For example in can compose/join two single floats into a `vec2` type.
  1917. *
  1918. * @augments TempNode
  1919. */
  1920. class JoinNode extends TempNode {
  1921. static get type() {
  1922. return 'JoinNode';
  1923. }
  1924. /**
  1925. * Constructs a new join node.
  1926. *
  1927. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1928. * @param {?string} [nodeType=null] - The node type.
  1929. */
  1930. constructor( nodes = [], nodeType = null ) {
  1931. super( nodeType );
  1932. /**
  1933. * An array of nodes that should be joined.
  1934. *
  1935. * @type {Array<Node>}
  1936. */
  1937. this.nodes = nodes;
  1938. }
  1939. /**
  1940. * This method is overwritten since the node type must be inferred from the
  1941. * joined data length if not explicitly defined.
  1942. *
  1943. * @param {NodeBuilder} builder - The current node builder.
  1944. * @return {string} The node type.
  1945. */
  1946. generateNodeType( builder ) {
  1947. if ( this.nodeType !== null ) {
  1948. return builder.getVectorType( this.nodeType );
  1949. }
  1950. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1951. }
  1952. generate( builder, output ) {
  1953. const type = this.getNodeType( builder );
  1954. const maxLength = builder.getTypeLength( type );
  1955. const nodes = this.nodes;
  1956. const primitiveType = builder.getComponentType( type );
  1957. const snippetValues = [];
  1958. let length = 0;
  1959. for ( const input of nodes ) {
  1960. if ( length >= maxLength ) {
  1961. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.`, this.stackTrace );
  1962. break;
  1963. }
  1964. let inputType = input.getNodeType( builder );
  1965. let inputTypeLength = builder.getTypeLength( inputType );
  1966. let inputSnippet;
  1967. if ( length + inputTypeLength > maxLength ) {
  1968. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.`, this.stackTrace );
  1969. inputTypeLength = maxLength - length;
  1970. inputType = builder.getTypeFromLength( inputTypeLength );
  1971. }
  1972. length += inputTypeLength;
  1973. inputSnippet = input.build( builder, inputType );
  1974. const inputPrimitiveType = builder.getComponentType( inputType );
  1975. if ( inputPrimitiveType !== primitiveType ) {
  1976. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1977. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1978. }
  1979. snippetValues.push( inputSnippet );
  1980. }
  1981. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1982. return builder.format( snippet, type, output );
  1983. }
  1984. }
  1985. const _stringVectorComponents = vectorComponents.join( '' );
  1986. /**
  1987. * This module is part of the TSL core and usually not used in app level code.
  1988. * `SplitNode` represents a property access operation which means it is
  1989. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1990. * For example:
  1991. * ```js
  1992. * const redValue = color.r;
  1993. * ```
  1994. *
  1995. * @augments Node
  1996. */
  1997. class SplitNode extends Node {
  1998. static get type() {
  1999. return 'SplitNode';
  2000. }
  2001. /**
  2002. * Constructs a new split node.
  2003. *
  2004. * @param {Node} node - The node that should be accessed.
  2005. * @param {string} [components='x'] - The components that should be accessed.
  2006. */
  2007. constructor( node, components = 'x' ) {
  2008. super();
  2009. /**
  2010. * The node that should be accessed.
  2011. *
  2012. * @type {Node}
  2013. */
  2014. this.node = node;
  2015. /**
  2016. * The components that should be accessed.
  2017. *
  2018. * @type {string}
  2019. */
  2020. this.components = components;
  2021. /**
  2022. * This flag can be used for type testing.
  2023. *
  2024. * @type {boolean}
  2025. * @readonly
  2026. * @default true
  2027. */
  2028. this.isSplitNode = true;
  2029. }
  2030. /**
  2031. * Returns the vector length which is computed based on the requested components.
  2032. *
  2033. * @return {number} The vector length.
  2034. */
  2035. getVectorLength() {
  2036. let vectorLength = this.components.length;
  2037. for ( const c of this.components ) {
  2038. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  2039. }
  2040. return vectorLength;
  2041. }
  2042. /**
  2043. * Returns the component type of the node's type.
  2044. *
  2045. * @param {NodeBuilder} builder - The current node builder.
  2046. * @return {string} The component type.
  2047. */
  2048. getComponentType( builder ) {
  2049. return builder.getComponentType( this.node.getNodeType( builder ) );
  2050. }
  2051. /**
  2052. * This method is overwritten since the node type is inferred from requested components.
  2053. *
  2054. * @param {NodeBuilder} builder - The current node builder.
  2055. * @return {string} The node type.
  2056. */
  2057. generateNodeType( builder ) {
  2058. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  2059. }
  2060. /**
  2061. * Returns the scope of the node.
  2062. *
  2063. * @return {Node} The scope of the node.
  2064. */
  2065. getScope() {
  2066. return this.node.getScope();
  2067. }
  2068. generate( builder, output ) {
  2069. const node = this.node;
  2070. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  2071. let snippet = null;
  2072. if ( nodeTypeLength > 1 ) {
  2073. let type = null;
  2074. const componentsLength = this.getVectorLength();
  2075. if ( componentsLength >= nodeTypeLength ) {
  2076. // needed expand the input node
  2077. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  2078. }
  2079. const nodeSnippet = node.build( builder, type );
  2080. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  2081. // unnecessary swizzle
  2082. snippet = builder.format( nodeSnippet, type, output );
  2083. } else {
  2084. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  2085. }
  2086. } else {
  2087. // ignore .components if .node returns float/integer
  2088. snippet = node.build( builder, output );
  2089. }
  2090. return snippet;
  2091. }
  2092. serialize( data ) {
  2093. super.serialize( data );
  2094. data.components = this.components;
  2095. }
  2096. deserialize( data ) {
  2097. super.deserialize( data );
  2098. this.components = data.components;
  2099. }
  2100. }
  2101. /**
  2102. * This module is part of the TSL core and usually not used in app level code.
  2103. * `SetNode` represents a set operation which means it is used to implement any
  2104. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  2105. * For example:
  2106. * ```js
  2107. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  2108. * ```
  2109. *
  2110. * @augments TempNode
  2111. */
  2112. class SetNode extends TempNode {
  2113. static get type() {
  2114. return 'SetNode';
  2115. }
  2116. /**
  2117. * Constructs a new set node.
  2118. *
  2119. * @param {Node} sourceNode - The node that should be updated.
  2120. * @param {string} components - The components that should be updated.
  2121. * @param {Node} targetNode - The value node.
  2122. */
  2123. constructor( sourceNode, components, targetNode ) {
  2124. super();
  2125. /**
  2126. * The node that should be updated.
  2127. *
  2128. * @type {Node}
  2129. */
  2130. this.sourceNode = sourceNode;
  2131. /**
  2132. * The components that should be updated.
  2133. *
  2134. * @type {string}
  2135. */
  2136. this.components = components;
  2137. /**
  2138. * The value node.
  2139. *
  2140. * @type {Node}
  2141. */
  2142. this.targetNode = targetNode;
  2143. }
  2144. /**
  2145. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  2146. *
  2147. * @param {NodeBuilder} builder - The current node builder.
  2148. * @return {string} The node type.
  2149. */
  2150. generateNodeType( builder ) {
  2151. return this.sourceNode.getNodeType( builder );
  2152. }
  2153. generate( builder ) {
  2154. const { sourceNode, components, targetNode } = this;
  2155. const sourceType = this.getNodeType( builder );
  2156. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  2157. const targetType = builder.getTypeFromLength( components.length, componentType );
  2158. const targetSnippet = targetNode.build( builder, targetType );
  2159. const sourceSnippet = sourceNode.build( builder, sourceType );
  2160. const length = builder.getTypeLength( sourceType );
  2161. const snippetValues = [];
  2162. for ( let i = 0; i < length; i ++ ) {
  2163. const component = vectorComponents[ i ];
  2164. if ( component === components[ 0 ] ) {
  2165. snippetValues.push( targetSnippet );
  2166. i += components.length - 1;
  2167. } else {
  2168. snippetValues.push( sourceSnippet + '.' + component );
  2169. }
  2170. }
  2171. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2172. }
  2173. }
  2174. /**
  2175. * This module is part of the TSL core and usually not used in app level code.
  2176. * It represents a flip operation during the shader generation process
  2177. * meaning it flips normalized values with the following formula:
  2178. * ```
  2179. * x = 1 - x;
  2180. * ```
  2181. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  2182. * `flipSTPQ()` method invocations on node objects. For example:
  2183. * ```js
  2184. * uvNode = uvNode.flipY();
  2185. * ```
  2186. *
  2187. * @augments TempNode
  2188. */
  2189. class FlipNode extends TempNode {
  2190. static get type() {
  2191. return 'FlipNode';
  2192. }
  2193. /**
  2194. * Constructs a new flip node.
  2195. *
  2196. * @param {Node} sourceNode - The node which component(s) should be flipped.
  2197. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  2198. */
  2199. constructor( sourceNode, components ) {
  2200. super();
  2201. /**
  2202. * The node which component(s) should be flipped.
  2203. *
  2204. * @type {Node}
  2205. */
  2206. this.sourceNode = sourceNode;
  2207. /**
  2208. * The components that should be flipped e.g. `'x'` or `'xy'`.
  2209. *
  2210. * @type {string}
  2211. */
  2212. this.components = components;
  2213. }
  2214. /**
  2215. * This method is overwritten since the node type is inferred from the source node.
  2216. *
  2217. * @param {NodeBuilder} builder - The current node builder.
  2218. * @return {string} The node type.
  2219. */
  2220. generateNodeType( builder ) {
  2221. return this.sourceNode.getNodeType( builder );
  2222. }
  2223. generate( builder ) {
  2224. const { components, sourceNode } = this;
  2225. const sourceType = this.getNodeType( builder );
  2226. const sourceSnippet = sourceNode.build( builder );
  2227. const sourceCache = builder.getVarFromNode( this );
  2228. const sourceProperty = builder.getPropertyName( sourceCache );
  2229. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  2230. const length = builder.getTypeLength( sourceType );
  2231. const snippetValues = [];
  2232. let componentIndex = 0;
  2233. for ( let i = 0; i < length; i ++ ) {
  2234. const component = vectorComponents[ i ];
  2235. if ( component === components[ componentIndex ] ) {
  2236. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  2237. componentIndex ++;
  2238. } else {
  2239. snippetValues.push( sourceProperty + '.' + component );
  2240. }
  2241. }
  2242. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2243. }
  2244. }
  2245. /**
  2246. * Base class for representing data input nodes.
  2247. *
  2248. * @augments Node
  2249. */
  2250. class InputNode extends Node {
  2251. static get type() {
  2252. return 'InputNode';
  2253. }
  2254. /**
  2255. * Constructs a new input node.
  2256. *
  2257. * @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).
  2258. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2259. */
  2260. constructor( value, nodeType = null ) {
  2261. super( nodeType );
  2262. /**
  2263. * This flag can be used for type testing.
  2264. *
  2265. * @type {boolean}
  2266. * @readonly
  2267. * @default true
  2268. */
  2269. this.isInputNode = true;
  2270. /**
  2271. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2272. *
  2273. * @type {any}
  2274. */
  2275. this.value = value;
  2276. /**
  2277. * The precision of the value in the shader.
  2278. *
  2279. * @type {?('low'|'medium'|'high')}
  2280. * @default null
  2281. */
  2282. this.precision = null;
  2283. }
  2284. generateNodeType( /*builder*/ ) {
  2285. if ( this.nodeType === null ) {
  2286. return getValueType( this.value );
  2287. }
  2288. return this.nodeType;
  2289. }
  2290. /**
  2291. * Returns the input type of the node which is by default the node type. Derived modules
  2292. * might overwrite this method and use a fixed type or compute one analytically.
  2293. *
  2294. * A typical example for different input and node types are textures. The input type of a
  2295. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2296. *
  2297. * @param {NodeBuilder} builder - The current node builder.
  2298. * @return {string} The input type.
  2299. */
  2300. getInputType( builder ) {
  2301. return this.getNodeType( builder );
  2302. }
  2303. /**
  2304. * Sets the precision to the given value. The method can be
  2305. * overwritten in derived classes if the final precision must be computed
  2306. * analytically.
  2307. *
  2308. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2309. * @return {InputNode} A reference to this node.
  2310. */
  2311. setPrecision( precision ) {
  2312. this.precision = precision;
  2313. return this;
  2314. }
  2315. serialize( data ) {
  2316. super.serialize( data );
  2317. data.value = this.value;
  2318. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2319. data.valueType = getValueType( this.value );
  2320. data.nodeType = this.nodeType;
  2321. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2322. data.precision = this.precision;
  2323. }
  2324. deserialize( data ) {
  2325. super.deserialize( data );
  2326. this.nodeType = data.nodeType;
  2327. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2328. this.precision = data.precision || null;
  2329. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2330. }
  2331. generate( /*builder, output*/ ) {
  2332. warn( 'Abstract function.' );
  2333. }
  2334. }
  2335. const _regNum = /float|u?int/;
  2336. /**
  2337. * Class for representing a constant value in the shader.
  2338. *
  2339. * @augments InputNode
  2340. */
  2341. class ConstNode extends InputNode {
  2342. static get type() {
  2343. return 'ConstNode';
  2344. }
  2345. /**
  2346. * Constructs a new input node.
  2347. *
  2348. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2349. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2350. */
  2351. constructor( value, nodeType = null ) {
  2352. super( value, nodeType );
  2353. /**
  2354. * This flag can be used for type testing.
  2355. *
  2356. * @type {boolean}
  2357. * @readonly
  2358. * @default true
  2359. */
  2360. this.isConstNode = true;
  2361. }
  2362. /**
  2363. * Generates the shader string of the value with the current node builder.
  2364. *
  2365. * @param {NodeBuilder} builder - The current node builder.
  2366. * @return {string} The generated value as a shader string.
  2367. */
  2368. generateConst( builder ) {
  2369. return builder.generateConst( this.getNodeType( builder ), this.value );
  2370. }
  2371. generate( builder, output ) {
  2372. const type = this.getNodeType( builder );
  2373. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2374. return builder.generateConst( output, this.value );
  2375. }
  2376. return builder.format( this.generateConst( builder ), type, output );
  2377. }
  2378. }
  2379. /**
  2380. * Base class for representing member access on an object-like
  2381. * node data structures.
  2382. *
  2383. * @augments Node
  2384. */
  2385. class MemberNode extends Node {
  2386. static get type() {
  2387. return 'MemberNode';
  2388. }
  2389. /**
  2390. * Constructs a member node.
  2391. *
  2392. * @param {Node} structNode - The struct node.
  2393. * @param {string} property - The property name.
  2394. */
  2395. constructor( structNode, property ) {
  2396. super();
  2397. /**
  2398. * The struct node.
  2399. *
  2400. * @type {Node}
  2401. */
  2402. this.structNode = structNode;
  2403. /**
  2404. * The property name.
  2405. *
  2406. * @type {Node}
  2407. */
  2408. this.property = property;
  2409. /**
  2410. * This flag can be used for type testing.
  2411. *
  2412. * @type {boolean}
  2413. * @readonly
  2414. * @default true
  2415. */
  2416. this.isMemberNode = true;
  2417. }
  2418. hasMember( builder ) {
  2419. if ( this.structNode.isMemberNode ) {
  2420. if ( this.structNode.hasMember( builder ) === false ) {
  2421. return false;
  2422. }
  2423. }
  2424. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2425. }
  2426. generateNodeType( builder ) {
  2427. if ( this.hasMember( builder ) === false ) {
  2428. // default type if member does not exist
  2429. return 'float';
  2430. }
  2431. return this.structNode.getMemberType( builder, this.property );
  2432. }
  2433. getMemberType( builder, name ) {
  2434. if ( this.hasMember( builder ) === false ) {
  2435. // default type if member does not exist
  2436. return 'float';
  2437. }
  2438. const type = this.getNodeType( builder );
  2439. const struct = builder.getStructTypeNode( type );
  2440. return struct.getMemberType( builder, name );
  2441. }
  2442. generate( builder ) {
  2443. if ( this.hasMember( builder ) === false ) {
  2444. warn( `TSL: Member "${ this.property }" does not exist in struct.`, this.stackTrace );
  2445. const type = this.getNodeType( builder );
  2446. return builder.generateConst( type );
  2447. }
  2448. const propertyName = this.structNode.build( builder );
  2449. return propertyName + '.' + this.property;
  2450. }
  2451. }
  2452. let currentStack = null;
  2453. const NodeElements = new Map();
  2454. // Extend Node Class for TSL using prototype
  2455. function addMethodChaining( name, nodeElement ) {
  2456. // No require StackTrace because this is internal API
  2457. if ( NodeElements.has( name ) ) {
  2458. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2459. return;
  2460. }
  2461. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2462. NodeElements.set( name, nodeElement );
  2463. if ( name !== 'assign' ) {
  2464. // Changing Node prototype to add method chaining
  2465. Node.prototype[ name ] = function ( ...params ) {
  2466. //if ( name === 'toVarIntent' ) return this;
  2467. return this.isStackNode ? this.addToStack( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2468. };
  2469. // Adding assign method chaining
  2470. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2471. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2472. };
  2473. }
  2474. }
  2475. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2476. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2477. Node.prototype.assign = function ( ...params ) {
  2478. if ( this.isStackNode !== true ) {
  2479. if ( currentStack !== null ) {
  2480. currentStack.assign( this, ...params );
  2481. } else {
  2482. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().', new StackTrace() );
  2483. }
  2484. return this;
  2485. } else {
  2486. const nodeElement = NodeElements.get( 'assign' );
  2487. return this.addToStack( nodeElement( ...params ) );
  2488. }
  2489. };
  2490. Node.prototype.toVarIntent = function () {
  2491. return this;
  2492. };
  2493. Node.prototype.get = function ( value ) {
  2494. return new MemberNode( this, value );
  2495. };
  2496. // Cache prototype for TSL
  2497. const proto = {};
  2498. // Set swizzle properties for xyzw, rgba, and stpq.
  2499. function setProtoSwizzle( property, altA, altB ) {
  2500. // swizzle properties
  2501. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2502. get() {
  2503. this._cache = this._cache || {};
  2504. //
  2505. let split = this._cache[ property ];
  2506. if ( split === undefined ) {
  2507. split = new SplitNode( this, property );
  2508. this._cache[ property ] = split;
  2509. }
  2510. return split;
  2511. },
  2512. set( value ) {
  2513. this[ property ].assign( nodeObject( value ) );
  2514. }
  2515. };
  2516. // set properties ( swizzle ) and sort to xyzw sequence
  2517. const propUpper = property.toUpperCase();
  2518. const altAUpper = altA.toUpperCase();
  2519. const altBUpper = altB.toUpperCase();
  2520. // Set methods for swizzle properties
  2521. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2522. const swizzle = parseSwizzleAndSort( property );
  2523. return new SetNode( this, swizzle, nodeObject( value ) );
  2524. };
  2525. // Set methods for flip properties
  2526. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2527. const swizzle = parseSwizzleAndSort( property );
  2528. return new FlipNode( this, swizzle );
  2529. };
  2530. }
  2531. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2532. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2533. const swizzleC = [ 's', 't', 'p', 'q' ];
  2534. for ( let a = 0; a < 4; a ++ ) {
  2535. let prop = swizzleA[ a ];
  2536. let altA = swizzleB[ a ];
  2537. let altB = swizzleC[ a ];
  2538. setProtoSwizzle( prop, altA, altB );
  2539. for ( let b = 0; b < 4; b ++ ) {
  2540. prop = swizzleA[ a ] + swizzleA[ b ];
  2541. altA = swizzleB[ a ] + swizzleB[ b ];
  2542. altB = swizzleC[ a ] + swizzleC[ b ];
  2543. setProtoSwizzle( prop, altA, altB );
  2544. for ( let c = 0; c < 4; c ++ ) {
  2545. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2546. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2547. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2548. setProtoSwizzle( prop, altA, altB );
  2549. for ( let d = 0; d < 4; d ++ ) {
  2550. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2551. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2552. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2553. setProtoSwizzle( prop, altA, altB );
  2554. }
  2555. }
  2556. }
  2557. }
  2558. // Set/get static properties for array elements (0-31).
  2559. for ( let i = 0; i < 32; i ++ ) {
  2560. proto[ i ] = {
  2561. get() {
  2562. this._cache = this._cache || {};
  2563. //
  2564. let element = this._cache[ i ];
  2565. if ( element === undefined ) {
  2566. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2567. this._cache[ i ] = element;
  2568. }
  2569. return element;
  2570. },
  2571. set( value ) {
  2572. this[ i ].assign( nodeObject( value ) );
  2573. }
  2574. };
  2575. }
  2576. /*
  2577. // Set properties for width, height, and depth.
  2578. function setProtoProperty( property, target ) {
  2579. proto[ property ] = {
  2580. get() {
  2581. this._cache = this._cache || {};
  2582. //
  2583. let split = this._cache[ target ];
  2584. if ( split === undefined ) {
  2585. split = new SplitNode( this, target );
  2586. this._cache[ target ] = split;
  2587. }
  2588. return split;
  2589. },
  2590. set( value ) {
  2591. this[ target ].assign( nodeObject( value ) );
  2592. }
  2593. };
  2594. }
  2595. setProtoProperty( 'width', 'x' );
  2596. setProtoProperty( 'height', 'y' );
  2597. setProtoProperty( 'depth', 'z' );
  2598. */
  2599. Object.defineProperties( Node.prototype, proto );
  2600. // --- FINISH ---
  2601. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2602. const ShaderNodeObject = function ( obj, altType = null ) {
  2603. const type = getValueType( obj );
  2604. if ( type === 'node' ) {
  2605. return obj;
  2606. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2607. return nodeObject( getConstNode( obj, altType ) );
  2608. } else if ( type === 'shader' ) {
  2609. return obj.isFn ? obj : Fn( obj );
  2610. }
  2611. return obj;
  2612. };
  2613. const ShaderNodeObjects = function ( objects, altType = null ) {
  2614. for ( const name in objects ) {
  2615. objects[ name ] = nodeObject( objects[ name ], altType );
  2616. }
  2617. return objects;
  2618. };
  2619. const ShaderNodeArray = function ( array, altType = null ) {
  2620. const len = array.length;
  2621. for ( let i = 0; i < len; i ++ ) {
  2622. array[ i ] = nodeObject( array[ i ], altType );
  2623. }
  2624. return array;
  2625. };
  2626. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2627. function assignNode( node ) {
  2628. if ( settings !== null ) {
  2629. node = nodeObject( Object.assign( node, settings ) );
  2630. if ( settings.intent === true ) {
  2631. node = node.toVarIntent();
  2632. }
  2633. } else {
  2634. node = nodeObject( node );
  2635. }
  2636. return node;
  2637. }
  2638. let fn, name = scope, minParams, maxParams;
  2639. function verifyParamsLimit( params ) {
  2640. let tslName;
  2641. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2642. else tslName = NodeClass.type;
  2643. if ( minParams !== undefined && params.length < minParams ) {
  2644. error( `TSL: "${ tslName }" parameter length is less than minimum required.`, new StackTrace() );
  2645. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2646. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2647. error( `TSL: "${ tslName }" parameter length exceeds limit.`, new StackTrace() );
  2648. return params.slice( 0, maxParams );
  2649. }
  2650. return params;
  2651. }
  2652. if ( scope === null ) {
  2653. fn = ( ...params ) => {
  2654. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2655. };
  2656. } else if ( factor !== null ) {
  2657. factor = nodeObject( factor );
  2658. fn = ( ...params ) => {
  2659. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2660. };
  2661. } else {
  2662. fn = ( ...params ) => {
  2663. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2664. };
  2665. }
  2666. fn.setParameterLength = ( ...params ) => {
  2667. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2668. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2669. return fn;
  2670. };
  2671. fn.setName = ( value ) => {
  2672. name = value;
  2673. return fn;
  2674. };
  2675. return fn;
  2676. };
  2677. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2678. return new NodeClass( ...nodeArray( params ) );
  2679. };
  2680. class ShaderCallNodeInternal extends Node {
  2681. constructor( shaderNode, rawInputs ) {
  2682. super();
  2683. this.shaderNode = shaderNode;
  2684. this.rawInputs = rawInputs;
  2685. this.isShaderCallNodeInternal = true;
  2686. }
  2687. generateNodeType( builder ) {
  2688. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2689. }
  2690. getElementType( builder ) {
  2691. return this.getOutputNode( builder ).getElementType( builder );
  2692. }
  2693. getMemberType( builder, name ) {
  2694. return this.getOutputNode( builder ).getMemberType( builder, name );
  2695. }
  2696. call( builder ) {
  2697. const { shaderNode, rawInputs } = this;
  2698. const properties = builder.getNodeProperties( shaderNode );
  2699. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2700. const subBuildProperty = subBuild || 'default';
  2701. if ( properties[ subBuildProperty ] ) {
  2702. return properties[ subBuildProperty ];
  2703. }
  2704. //
  2705. const previousSubBuildFn = builder.subBuildFn;
  2706. const previousFnCall = builder.fnCall;
  2707. builder.subBuildFn = subBuild;
  2708. builder.fnCall = this;
  2709. let result = null;
  2710. if ( shaderNode.layout ) {
  2711. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2712. if ( functionNodesCacheMap === undefined ) {
  2713. functionNodesCacheMap = new WeakMap();
  2714. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2715. }
  2716. let functionNode = functionNodesCacheMap.get( shaderNode );
  2717. if ( functionNode === undefined ) {
  2718. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2719. functionNodesCacheMap.set( shaderNode, functionNode );
  2720. }
  2721. builder.addInclude( functionNode );
  2722. //
  2723. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2724. result = nodeObject( functionNode.call( inputs ) );
  2725. } else {
  2726. const secureNodeBuilder = new Proxy( builder, {
  2727. get: ( target, property, receiver ) => {
  2728. let value;
  2729. if ( Symbol.iterator === property ) {
  2730. value = function* () {
  2731. yield undefined;
  2732. };
  2733. } else {
  2734. value = Reflect.get( target, property, receiver );
  2735. }
  2736. return value;
  2737. }
  2738. } );
  2739. //
  2740. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2741. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2742. const jsFunc = shaderNode.jsFunc;
  2743. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2744. result = nodeObject( outputNode );
  2745. }
  2746. builder.subBuildFn = previousSubBuildFn;
  2747. builder.fnCall = previousFnCall;
  2748. if ( shaderNode.once ) {
  2749. properties[ subBuildProperty ] = result;
  2750. }
  2751. return result;
  2752. }
  2753. setupOutput( builder ) {
  2754. builder.addStack();
  2755. builder.stack.outputNode = this.call( builder );
  2756. return builder.removeStack();
  2757. }
  2758. getOutputNode( builder ) {
  2759. const properties = builder.getNodeProperties( this );
  2760. const subBuildOutput = builder.getSubBuildOutput( this );
  2761. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2762. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2763. return properties[ subBuildOutput ];
  2764. }
  2765. build( builder, output = null ) {
  2766. let result = null;
  2767. const buildStage = builder.getBuildStage();
  2768. const properties = builder.getNodeProperties( this );
  2769. const subBuildOutput = builder.getSubBuildOutput( this );
  2770. const outputNode = this.getOutputNode( builder );
  2771. const previousFnCall = builder.fnCall;
  2772. builder.fnCall = this;
  2773. if ( buildStage === 'setup' ) {
  2774. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2775. if ( properties[ subBuildInitialized ] !== true ) {
  2776. properties[ subBuildInitialized ] = true;
  2777. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2778. properties[ subBuildOutput ].build( builder );
  2779. // If the shaderNode has subBuilds, add them to the chaining nodes
  2780. // so they can be built later in the build process.
  2781. if ( this.shaderNode.subBuilds ) {
  2782. for ( const node of builder.chaining ) {
  2783. const nodeData = builder.getDataFromNode( node, 'any' );
  2784. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2785. for ( const subBuild of this.shaderNode.subBuilds ) {
  2786. nodeData.subBuilds.add( subBuild );
  2787. }
  2788. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2789. }
  2790. }
  2791. }
  2792. result = properties[ subBuildOutput ];
  2793. } else if ( buildStage === 'analyze' ) {
  2794. outputNode.build( builder, output );
  2795. } else if ( buildStage === 'generate' ) {
  2796. result = outputNode.build( builder, output ) || '';
  2797. }
  2798. builder.fnCall = previousFnCall;
  2799. return result;
  2800. }
  2801. }
  2802. function getLayoutParameters( params ) {
  2803. let output;
  2804. nodeObjects( params );
  2805. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2806. if ( isArrayAsParameter ) {
  2807. output = [ ...params ];
  2808. } else {
  2809. output = params[ 0 ];
  2810. }
  2811. return output;
  2812. }
  2813. function getProxyParameters( params ) {
  2814. let index = 0;
  2815. nodeObjects( params );
  2816. return new Proxy( params, {
  2817. get: ( target, property, receiver ) => {
  2818. let value;
  2819. if ( property === 'length' ) {
  2820. value = params.length;
  2821. return value;
  2822. }
  2823. if ( Symbol.iterator === property ) {
  2824. value = function* () {
  2825. for ( const inputNode of params ) {
  2826. yield nodeObject( inputNode );
  2827. }
  2828. };
  2829. } else {
  2830. if ( params.length > 0 ) {
  2831. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2832. const objectTarget = params[ 0 ];
  2833. if ( objectTarget[ property ] === undefined ) {
  2834. value = objectTarget[ index ++ ];
  2835. } else {
  2836. value = Reflect.get( objectTarget, property, receiver );
  2837. }
  2838. } else if ( params[ 0 ] instanceof Node ) {
  2839. if ( params[ property ] === undefined ) {
  2840. value = params[ index ++ ];
  2841. } else {
  2842. value = Reflect.get( params, property, receiver );
  2843. }
  2844. }
  2845. } else {
  2846. value = Reflect.get( target, property, receiver );
  2847. }
  2848. value = nodeObject( value );
  2849. }
  2850. return value;
  2851. }
  2852. } );
  2853. }
  2854. class ShaderNodeInternal extends Node {
  2855. constructor( jsFunc, nodeType ) {
  2856. super( nodeType );
  2857. this.jsFunc = jsFunc;
  2858. this.layout = null;
  2859. this.global = true;
  2860. this.once = false;
  2861. }
  2862. setLayout( layout ) {
  2863. this.layout = layout;
  2864. return this;
  2865. }
  2866. getLayout() {
  2867. return this.layout;
  2868. }
  2869. call( rawInputs = null ) {
  2870. return new ShaderCallNodeInternal( this, rawInputs );
  2871. }
  2872. setup() {
  2873. return this.call();
  2874. }
  2875. }
  2876. const bools = [ false, true ];
  2877. const uints = [ 0, 1, 2, 3 ];
  2878. const ints = [ -1, -2 ];
  2879. 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 ];
  2880. const boolsCacheMap = new Map();
  2881. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2882. const uintsCacheMap = new Map();
  2883. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2884. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2885. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2886. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2887. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2888. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2889. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2890. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2891. const getConstNode = ( value, type ) => {
  2892. if ( constNodesCacheMap.has( value ) ) {
  2893. return constNodesCacheMap.get( value );
  2894. } else if ( value.isNode === true ) {
  2895. return value;
  2896. } else {
  2897. return new ConstNode( value, type );
  2898. }
  2899. };
  2900. const ConvertType = function ( type, cacheMap = null ) {
  2901. return ( ...params ) => {
  2902. for ( const param of params ) {
  2903. if ( param === undefined ) {
  2904. error( `TSL: Invalid parameter for the type "${ type }".`, new StackTrace() );
  2905. return new ConstNode( 0, type );
  2906. }
  2907. }
  2908. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2909. const paramType = typeof param;
  2910. return paramType !== 'object' && paramType !== 'function';
  2911. } ) ) ) {
  2912. params = [ getValueFromType( type, ...params ) ];
  2913. }
  2914. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2915. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2916. }
  2917. if ( params.length === 1 ) {
  2918. const node = getConstNode( params[ 0 ], type );
  2919. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2920. return nodeObjectIntent( new ConvertNode( node, type ) );
  2921. }
  2922. const nodes = params.map( param => getConstNode( param ) );
  2923. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2924. };
  2925. };
  2926. // exports
  2927. function defined( value ) {
  2928. if ( value && value.isNode ) {
  2929. value.traverse( ( node ) => {
  2930. if ( node.isConstNode ) {
  2931. value = node.value;
  2932. }
  2933. } );
  2934. }
  2935. return Boolean( value );
  2936. }
  2937. // utils
  2938. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2939. // shader node base
  2940. function ShaderNode( jsFunc, nodeType ) {
  2941. return new ShaderNodeInternal( jsFunc, nodeType );
  2942. }
  2943. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2944. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2945. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2946. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2947. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2948. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2949. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { ...settings, intent: true } );
  2950. let fnId = 0;
  2951. class FnNode extends Node {
  2952. constructor( jsFunc, layout = null ) {
  2953. super();
  2954. let nodeType = null;
  2955. if ( layout !== null ) {
  2956. if ( typeof layout === 'object' ) {
  2957. nodeType = layout.return;
  2958. } else {
  2959. if ( typeof layout === 'string' ) {
  2960. nodeType = layout;
  2961. } else {
  2962. error( 'TSL: Invalid layout type.', new StackTrace() );
  2963. }
  2964. layout = null;
  2965. }
  2966. }
  2967. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2968. if ( layout !== null ) {
  2969. this.setLayout( layout );
  2970. }
  2971. this.isFn = true;
  2972. }
  2973. setLayout( layout ) {
  2974. const nodeType = this.shaderNode.nodeType;
  2975. if ( typeof layout.inputs !== 'object' ) {
  2976. const fullLayout = {
  2977. name: 'fn' + fnId ++,
  2978. type: nodeType,
  2979. inputs: []
  2980. };
  2981. for ( const name in layout ) {
  2982. if ( name === 'return' ) continue;
  2983. fullLayout.inputs.push( {
  2984. name: name,
  2985. type: layout[ name ]
  2986. } );
  2987. }
  2988. layout = fullLayout;
  2989. }
  2990. this.shaderNode.setLayout( layout );
  2991. return this;
  2992. }
  2993. generateNodeType( builder ) {
  2994. return this.shaderNode.getNodeType( builder ) || 'float';
  2995. }
  2996. call( ...params ) {
  2997. const fnCall = this.shaderNode.call( params );
  2998. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2999. return fnCall.toVarIntent();
  3000. }
  3001. once( subBuilds = null ) {
  3002. this.shaderNode.once = true;
  3003. this.shaderNode.subBuilds = subBuilds;
  3004. return this;
  3005. }
  3006. generate( builder ) {
  3007. const type = this.getNodeType( builder );
  3008. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".', this.stackTrace );
  3009. return builder.generateConst( type );
  3010. }
  3011. }
  3012. function Fn( jsFunc, layout = null ) {
  3013. const instance = new FnNode( jsFunc, layout );
  3014. return new Proxy( () => {}, {
  3015. apply( target, thisArg, params ) {
  3016. return instance.call( ...params );
  3017. },
  3018. get( target, prop, receiver ) {
  3019. return Reflect.get( instance, prop, receiver );
  3020. },
  3021. set( target, prop, value, receiver ) {
  3022. return Reflect.set( instance, prop, value, receiver );
  3023. }
  3024. } );
  3025. }
  3026. //
  3027. const setCurrentStack = ( stack ) => {
  3028. currentStack = stack;
  3029. };
  3030. const getCurrentStack = () => currentStack;
  3031. /**
  3032. * Represent a conditional node using if/else statements.
  3033. *
  3034. * ```js
  3035. * If( condition, function )
  3036. * .ElseIf( condition, function )
  3037. * .Else( function )
  3038. * ```
  3039. * @tsl
  3040. * @function
  3041. * @param {...any} params - The parameters for the conditional node.
  3042. * @returns {StackNode} The conditional node.
  3043. */
  3044. const If = ( ...params ) => currentStack.If( ...params );
  3045. /**
  3046. * Represent a conditional node using switch/case statements.
  3047. *
  3048. * ```js
  3049. * Switch( value )
  3050. * .Case( 1, function )
  3051. * .Case( 2, 3, 4, function )
  3052. * .Default( function )
  3053. * ```
  3054. * @tsl
  3055. * @function
  3056. * @param {...any} params - The parameters for the conditional node.
  3057. * @returns {StackNode} The conditional node.
  3058. */
  3059. const Switch = ( ...params ) => currentStack.Switch( ...params );
  3060. /**
  3061. * Add the given node to the current stack.
  3062. *
  3063. * @param {Node} node - The node to add.
  3064. * @returns {Node} The node that was added to the stack.
  3065. */
  3066. function Stack( node ) {
  3067. if ( currentStack ) currentStack.addToStack( node );
  3068. return node;
  3069. }
  3070. addMethodChaining( 'toStack', Stack );
  3071. // types
  3072. const color = new ConvertType( 'color' );
  3073. const float = new ConvertType( 'float', cacheMaps.float );
  3074. const int = new ConvertType( 'int', cacheMaps.ints );
  3075. const uint = new ConvertType( 'uint', cacheMaps.uint );
  3076. const bool = new ConvertType( 'bool', cacheMaps.bool );
  3077. const vec2 = new ConvertType( 'vec2' );
  3078. const ivec2 = new ConvertType( 'ivec2' );
  3079. const uvec2 = new ConvertType( 'uvec2' );
  3080. const bvec2 = new ConvertType( 'bvec2' );
  3081. const vec3 = new ConvertType( 'vec3' );
  3082. const ivec3 = new ConvertType( 'ivec3' );
  3083. const uvec3 = new ConvertType( 'uvec3' );
  3084. const bvec3 = new ConvertType( 'bvec3' );
  3085. const vec4 = new ConvertType( 'vec4' );
  3086. const ivec4 = new ConvertType( 'ivec4' );
  3087. const uvec4 = new ConvertType( 'uvec4' );
  3088. const bvec4 = new ConvertType( 'bvec4' );
  3089. const mat2 = new ConvertType( 'mat2' );
  3090. const mat3 = new ConvertType( 'mat3' );
  3091. const mat4 = new ConvertType( 'mat4' );
  3092. const string = ( value = '' ) => new ConstNode( value, 'string' );
  3093. const arrayBuffer = ( value ) => new ConstNode( value, 'ArrayBuffer' );
  3094. addMethodChaining( 'toColor', color );
  3095. addMethodChaining( 'toFloat', float );
  3096. addMethodChaining( 'toInt', int );
  3097. addMethodChaining( 'toUint', uint );
  3098. addMethodChaining( 'toBool', bool );
  3099. addMethodChaining( 'toVec2', vec2 );
  3100. addMethodChaining( 'toIVec2', ivec2 );
  3101. addMethodChaining( 'toUVec2', uvec2 );
  3102. addMethodChaining( 'toBVec2', bvec2 );
  3103. addMethodChaining( 'toVec3', vec3 );
  3104. addMethodChaining( 'toIVec3', ivec3 );
  3105. addMethodChaining( 'toUVec3', uvec3 );
  3106. addMethodChaining( 'toBVec3', bvec3 );
  3107. addMethodChaining( 'toVec4', vec4 );
  3108. addMethodChaining( 'toIVec4', ivec4 );
  3109. addMethodChaining( 'toUVec4', uvec4 );
  3110. addMethodChaining( 'toBVec4', bvec4 );
  3111. addMethodChaining( 'toMat2', mat2 );
  3112. addMethodChaining( 'toMat3', mat3 );
  3113. addMethodChaining( 'toMat4', mat4 );
  3114. // basic nodes
  3115. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  3116. const convert = ( node, types ) => new ConvertNode( nodeObject( node ), types );
  3117. const split = ( node, channels ) => new SplitNode( nodeObject( node ), channels );
  3118. addMethodChaining( 'element', element );
  3119. addMethodChaining( 'convert', convert );
  3120. // deprecated
  3121. /**
  3122. * @tsl
  3123. * @function
  3124. * @deprecated since r176. Use {@link Stack} instead.
  3125. *
  3126. * @param {Node} node - The node to add.
  3127. * @returns {Function}
  3128. */
  3129. const append = ( node ) => { // @deprecated, r176
  3130. warn( 'TSL: append() has been renamed to Stack().', new StackTrace() );
  3131. return Stack( node );
  3132. };
  3133. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  3134. warn( 'TSL: .append() has been renamed to .toStack().', new StackTrace() );
  3135. return Stack( node );
  3136. } );
  3137. /**
  3138. * This class represents a shader property. It can be used
  3139. * to explicitly define a property and assign a value to it.
  3140. *
  3141. * ```js
  3142. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  3143. *```
  3144. * `PropertyNode` is used by the engine to predefined common material properties
  3145. * for TSL code.
  3146. *
  3147. * @augments Node
  3148. */
  3149. class PropertyNode extends Node {
  3150. static get type() {
  3151. return 'PropertyNode';
  3152. }
  3153. /**
  3154. * Constructs a new property node.
  3155. *
  3156. * @param {string} nodeType - The type of the node.
  3157. * @param {?string} [name=null] - The name of the property in the shader.
  3158. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  3159. */
  3160. constructor( nodeType, name = null, varying = false ) {
  3161. super( nodeType );
  3162. /**
  3163. * The name of the property in the shader. If no name is defined,
  3164. * the node system auto-generates one.
  3165. *
  3166. * @type {?string}
  3167. * @default null
  3168. */
  3169. this.name = name;
  3170. /**
  3171. * Whether this property is a varying or not.
  3172. *
  3173. * @type {boolean}
  3174. * @default false
  3175. */
  3176. this.varying = varying;
  3177. /**
  3178. * This flag can be used for type testing.
  3179. *
  3180. * @type {boolean}
  3181. * @readonly
  3182. * @default true
  3183. */
  3184. this.isPropertyNode = true;
  3185. /**
  3186. * This flag is used for global cache.
  3187. *
  3188. * @type {boolean}
  3189. * @default true
  3190. */
  3191. this.global = true;
  3192. }
  3193. customCacheKey() {
  3194. return hashString( this.type + ':' + ( this.name || '' ) + ':' + ( this.varying ? '1' : '0' ) );
  3195. }
  3196. getHash( builder ) {
  3197. return this.name || super.getHash( builder );
  3198. }
  3199. generate( builder ) {
  3200. let nodeVar;
  3201. if ( this.varying === true ) {
  3202. nodeVar = builder.getVaryingFromNode( this, this.name );
  3203. nodeVar.needsInterpolation = true;
  3204. } else {
  3205. nodeVar = builder.getVarFromNode( this, this.name );
  3206. }
  3207. return builder.getPropertyName( nodeVar );
  3208. }
  3209. }
  3210. /**
  3211. * TSL function for creating a property node.
  3212. *
  3213. * @tsl
  3214. * @function
  3215. * @param {string} type - The type of the node.
  3216. * @param {?string} [name=null] - The name of the property in the shader.
  3217. * @returns {PropertyNode}
  3218. */
  3219. const property = ( type, name ) => new PropertyNode( type, name );
  3220. /**
  3221. * TSL function for creating a varying property node.
  3222. *
  3223. * @tsl
  3224. * @function
  3225. * @param {string} type - The type of the node.
  3226. * @param {?string} [name=null] - The name of the varying in the shader.
  3227. * @returns {PropertyNode}
  3228. */
  3229. const varyingProperty = ( type, name ) => new PropertyNode( type, name, true );
  3230. /**
  3231. * TSL object that represents the shader variable `DiffuseColor`.
  3232. *
  3233. * @tsl
  3234. * @type {PropertyNode<vec4>}
  3235. */
  3236. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  3237. /**
  3238. * TSL object that represents the shader variable `DiffuseContribution`.
  3239. *
  3240. * @tsl
  3241. * @type {PropertyNode<vec3>}
  3242. */
  3243. const diffuseContribution = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'DiffuseContribution' );
  3244. /**
  3245. * TSL object that represents the shader variable `EmissiveColor`.
  3246. *
  3247. * @tsl
  3248. * @type {PropertyNode<vec3>}
  3249. */
  3250. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  3251. /**
  3252. * TSL object that represents the shader variable `Roughness`.
  3253. *
  3254. * @tsl
  3255. * @type {PropertyNode<float>}
  3256. */
  3257. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  3258. /**
  3259. * TSL object that represents the shader variable `Metalness`.
  3260. *
  3261. * @tsl
  3262. * @type {PropertyNode<float>}
  3263. */
  3264. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3265. /**
  3266. * TSL object that represents the shader variable `Clearcoat`.
  3267. *
  3268. * @tsl
  3269. * @type {PropertyNode<float>}
  3270. */
  3271. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3272. /**
  3273. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3274. *
  3275. * @tsl
  3276. * @type {PropertyNode<float>}
  3277. */
  3278. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3279. /**
  3280. * TSL object that represents the shader variable `Sheen`.
  3281. *
  3282. * @tsl
  3283. * @type {PropertyNode<vec3>}
  3284. */
  3285. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3286. /**
  3287. * TSL object that represents the shader variable `SheenRoughness`.
  3288. *
  3289. * @tsl
  3290. * @type {PropertyNode<float>}
  3291. */
  3292. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3293. /**
  3294. * TSL object that represents the shader variable `Iridescence`.
  3295. *
  3296. * @tsl
  3297. * @type {PropertyNode<float>}
  3298. */
  3299. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3300. /**
  3301. * TSL object that represents the shader variable `IridescenceIOR`.
  3302. *
  3303. * @tsl
  3304. * @type {PropertyNode<float>}
  3305. */
  3306. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3307. /**
  3308. * TSL object that represents the shader variable `IridescenceThickness`.
  3309. *
  3310. * @tsl
  3311. * @type {PropertyNode<float>}
  3312. */
  3313. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3314. /**
  3315. * TSL object that represents the shader variable `AlphaT`.
  3316. *
  3317. * @tsl
  3318. * @type {PropertyNode<float>}
  3319. */
  3320. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3321. /**
  3322. * TSL object that represents the shader variable `Anisotropy`.
  3323. *
  3324. * @tsl
  3325. * @type {PropertyNode<float>}
  3326. */
  3327. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3328. /**
  3329. * TSL object that represents the shader variable `AnisotropyT`.
  3330. *
  3331. * @tsl
  3332. * @type {PropertyNode<vec3>}
  3333. */
  3334. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3335. /**
  3336. * TSL object that represents the shader variable `AnisotropyB`.
  3337. *
  3338. * @tsl
  3339. * @type {PropertyNode<vec3>}
  3340. */
  3341. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3342. /**
  3343. * TSL object that represents the shader variable `SpecularColor`.
  3344. *
  3345. * @tsl
  3346. * @type {PropertyNode<color>}
  3347. */
  3348. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3349. /**
  3350. * TSL object that represents the shader variable `SpecularColorBlended`.
  3351. *
  3352. * @tsl
  3353. * @type {PropertyNode<color>}
  3354. */
  3355. const specularColorBlended = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColorBlended' );
  3356. /**
  3357. * TSL object that represents the shader variable `SpecularF90`.
  3358. *
  3359. * @tsl
  3360. * @type {PropertyNode<float>}
  3361. */
  3362. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3363. /**
  3364. * TSL object that represents the shader variable `Shininess`.
  3365. *
  3366. * @tsl
  3367. * @type {PropertyNode<float>}
  3368. */
  3369. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3370. /**
  3371. * TSL object that represents the shader variable `Output`.
  3372. *
  3373. * @tsl
  3374. * @type {PropertyNode<vec4>}
  3375. */
  3376. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3377. /**
  3378. * TSL object that represents the shader variable `dashSize`.
  3379. *
  3380. * @tsl
  3381. * @type {PropertyNode<float>}
  3382. */
  3383. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3384. /**
  3385. * TSL object that represents the shader variable `gapSize`.
  3386. *
  3387. * @tsl
  3388. * @type {PropertyNode<float>}
  3389. */
  3390. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3391. /**
  3392. * TSL object that represents the shader variable `pointWidth`.
  3393. *
  3394. * @tsl
  3395. * @type {PropertyNode<float>}
  3396. */
  3397. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3398. /**
  3399. * TSL object that represents the shader variable `IOR`.
  3400. *
  3401. * @tsl
  3402. * @type {PropertyNode<float>}
  3403. */
  3404. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3405. /**
  3406. * TSL object that represents the shader variable `Transmission`.
  3407. *
  3408. * @tsl
  3409. * @type {PropertyNode<float>}
  3410. */
  3411. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3412. /**
  3413. * TSL object that represents the shader variable `Thickness`.
  3414. *
  3415. * @tsl
  3416. * @type {PropertyNode<float>}
  3417. */
  3418. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3419. /**
  3420. * TSL object that represents the shader variable `AttenuationDistance`.
  3421. *
  3422. * @tsl
  3423. * @type {PropertyNode<float>}
  3424. */
  3425. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3426. /**
  3427. * TSL object that represents the shader variable `AttenuationColor`.
  3428. *
  3429. * @tsl
  3430. * @type {PropertyNode<color>}
  3431. */
  3432. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3433. /**
  3434. * TSL object that represents the shader variable `Dispersion`.
  3435. *
  3436. * @tsl
  3437. * @type {PropertyNode<float>}
  3438. */
  3439. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3440. /**
  3441. * This node can be used to group single instances of {@link UniformNode}
  3442. * and manage them as a uniform buffer.
  3443. *
  3444. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3445. * will be used when defining the {@link UniformNode#groupNode} property.
  3446. *
  3447. * - `objectGroup`: Uniform buffer per object.
  3448. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3449. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3450. *
  3451. * @augments Node
  3452. */
  3453. class UniformGroupNode extends Node {
  3454. static get type() {
  3455. return 'UniformGroupNode';
  3456. }
  3457. /**
  3458. * Constructs a new uniform group node.
  3459. *
  3460. * @param {string} name - The name of the uniform group node.
  3461. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3462. * @param {number} [order=1] - Influences the internal sorting.
  3463. * @param {string|null} [updateType=null] - The update type of the uniform group node.
  3464. */
  3465. constructor( name, shared = false, order = 1, updateType = null ) {
  3466. super( 'string' );
  3467. /**
  3468. * The name of the uniform group node.
  3469. *
  3470. * @type {string}
  3471. */
  3472. this.name = name;
  3473. /**
  3474. * Whether this uniform group node is shared or not.
  3475. *
  3476. * @type {boolean}
  3477. * @default false
  3478. */
  3479. this.shared = shared;
  3480. /**
  3481. * Influences the internal sorting.
  3482. * TODO: Add details when this property should be changed.
  3483. *
  3484. * @type {number}
  3485. * @default 1
  3486. */
  3487. this.order = order;
  3488. /**
  3489. * The update type of the uniform group node.
  3490. *
  3491. * @type {string|null}
  3492. * @default null
  3493. */
  3494. this.updateType = updateType;
  3495. /**
  3496. * This flag can be used for type testing.
  3497. *
  3498. * @type {boolean}
  3499. * @readonly
  3500. * @default true
  3501. */
  3502. this.isUniformGroup = true;
  3503. }
  3504. /**
  3505. * Marks the uniform group node as needing an update.
  3506. * This will trigger the necessary updates in the rendering process.
  3507. */
  3508. update() {
  3509. this.needsUpdate = true;
  3510. }
  3511. /**
  3512. * Serializes the uniform group node to a JSON object.
  3513. *
  3514. * @param {Object} data - The object to store the serialized data.
  3515. */
  3516. serialize( data ) {
  3517. super.serialize( data );
  3518. data.name = this.name;
  3519. data.version = this.version;
  3520. data.shared = this.shared;
  3521. }
  3522. /**
  3523. * Deserializes the uniform group node from a JSON object.
  3524. *
  3525. * @param {Object} data - The object containing the serialized data.
  3526. */
  3527. deserialize( data ) {
  3528. super.deserialize( data );
  3529. this.name = data.name;
  3530. this.version = data.version;
  3531. this.shared = data.shared;
  3532. }
  3533. }
  3534. /**
  3535. * TSL function for creating a uniform group node with the given name.
  3536. *
  3537. * @tsl
  3538. * @function
  3539. * @param {string} name - The name of the uniform group node.
  3540. * @returns {UniformGroupNode}
  3541. */
  3542. const uniformGroup = ( name, order = 1, updateType = null ) => new UniformGroupNode( name, false, order, updateType );
  3543. /**
  3544. * TSL function for creating a shared uniform group node with the given name and order.
  3545. *
  3546. * @tsl
  3547. * @function
  3548. * @param {string} name - The name of the uniform group node.
  3549. * @param {number} [order=0] - Influences the internal sorting.
  3550. * @returns {UniformGroupNode}
  3551. */
  3552. const sharedUniformGroup = ( name, order = 0, updateType = null ) => new UniformGroupNode( name, true, order, updateType );
  3553. /**
  3554. * TSL object that represents a shared uniform group node which is updated once per frame.
  3555. *
  3556. * @tsl
  3557. * @type {UniformGroupNode}
  3558. */
  3559. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame', 0, NodeUpdateType.FRAME );
  3560. /**
  3561. * TSL object that represents a shared uniform group node which is updated once per render.
  3562. *
  3563. * @tsl
  3564. * @type {UniformGroupNode}
  3565. */
  3566. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render', 0, NodeUpdateType.RENDER );
  3567. /**
  3568. * TSL object that represents a uniform group node which is updated once per object.
  3569. *
  3570. * @tsl
  3571. * @type {UniformGroupNode}
  3572. */
  3573. const objectGroup = /*@__PURE__*/ uniformGroup( 'object', 1, NodeUpdateType.OBJECT );
  3574. /**
  3575. * Class for representing a uniform.
  3576. *
  3577. * @augments InputNode
  3578. */
  3579. class UniformNode extends InputNode {
  3580. static get type() {
  3581. return 'UniformNode';
  3582. }
  3583. /**
  3584. * Constructs a new uniform node.
  3585. *
  3586. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3587. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3588. */
  3589. constructor( value, nodeType = null ) {
  3590. super( value, nodeType );
  3591. /**
  3592. * This flag can be used for type testing.
  3593. *
  3594. * @type {boolean}
  3595. * @readonly
  3596. * @default true
  3597. */
  3598. this.isUniformNode = true;
  3599. /**
  3600. * The name or label of the uniform.
  3601. *
  3602. * @type {string}
  3603. * @default ''
  3604. */
  3605. this.name = '';
  3606. /**
  3607. * The uniform group of this uniform. By default, uniforms are
  3608. * managed per object but they might belong to a shared group
  3609. * which is updated per frame or render call.
  3610. *
  3611. * @type {UniformGroupNode}
  3612. */
  3613. this.groupNode = objectGroup;
  3614. }
  3615. /**
  3616. * Sets the {@link UniformNode#name} property.
  3617. *
  3618. * @param {string} name - The name of the uniform.
  3619. * @return {UniformNode} A reference to this node.
  3620. */
  3621. setName( name ) {
  3622. this.name = name;
  3623. return this;
  3624. }
  3625. /**
  3626. * Sets the {@link UniformNode#name} property.
  3627. *
  3628. * @deprecated
  3629. * @param {string} name - The name of the uniform.
  3630. * @return {UniformNode} A reference to this node.
  3631. */
  3632. label( name ) {
  3633. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  3634. return this.setName( name );
  3635. }
  3636. /**
  3637. * Sets the {@link UniformNode#groupNode} property.
  3638. *
  3639. * @param {UniformGroupNode} group - The uniform group.
  3640. * @return {UniformNode} A reference to this node.
  3641. */
  3642. setGroup( group ) {
  3643. this.groupNode = group;
  3644. return this;
  3645. }
  3646. /**
  3647. * Returns the {@link UniformNode#groupNode}.
  3648. *
  3649. * @return {UniformGroupNode} The uniform group.
  3650. */
  3651. getGroup() {
  3652. return this.groupNode;
  3653. }
  3654. /**
  3655. * By default, this method returns the result of {@link Node#getHash} but derived
  3656. * classes might overwrite this method with a different implementation.
  3657. *
  3658. * @param {NodeBuilder} builder - The current node builder.
  3659. * @return {string} The uniform hash.
  3660. */
  3661. getUniformHash( builder ) {
  3662. return this.getHash( builder );
  3663. }
  3664. onUpdate( callback, updateType ) {
  3665. callback = callback.bind( this );
  3666. return super.onUpdate( ( frame ) => {
  3667. const value = callback( frame, this );
  3668. if ( value !== undefined ) {
  3669. this.value = value;
  3670. }
  3671. }, updateType );
  3672. }
  3673. getInputType( builder ) {
  3674. let type = super.getInputType( builder );
  3675. if ( type === 'bool' ) {
  3676. type = 'uint';
  3677. }
  3678. return type;
  3679. }
  3680. generate( builder, output ) {
  3681. const type = this.getNodeType( builder );
  3682. const hash = this.getUniformHash( builder );
  3683. let sharedNode = builder.getNodeFromHash( hash );
  3684. if ( sharedNode === undefined ) {
  3685. builder.setHashNode( this, hash );
  3686. sharedNode = this;
  3687. }
  3688. const sharedNodeType = sharedNode.getInputType( builder );
  3689. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3690. const uniformName = builder.getPropertyName( nodeUniform );
  3691. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3692. //
  3693. let snippet = uniformName;
  3694. if ( type === 'bool' ) {
  3695. // cache to variable
  3696. const nodeData = builder.getDataFromNode( this );
  3697. let propertyName = nodeData.propertyName;
  3698. if ( propertyName === undefined ) {
  3699. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3700. propertyName = builder.getPropertyName( nodeVar );
  3701. nodeData.propertyName = propertyName;
  3702. snippet = builder.format( uniformName, sharedNodeType, type );
  3703. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3704. }
  3705. snippet = propertyName;
  3706. }
  3707. return builder.format( snippet, type, output );
  3708. }
  3709. }
  3710. /**
  3711. * TSL function for creating a uniform node.
  3712. *
  3713. * @tsl
  3714. * @function
  3715. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3716. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3717. * @returns {UniformNode}
  3718. */
  3719. const uniform = ( value, type ) => {
  3720. const nodeType = getConstNodeType( type || value );
  3721. if ( nodeType === value ) {
  3722. // if the value is a type but no having a value
  3723. value = getValueFromType( nodeType );
  3724. }
  3725. if ( value && value.isNode === true ) {
  3726. let v = value.value;
  3727. value.traverse( n => {
  3728. if ( n.isConstNode === true ) {
  3729. v = n.value;
  3730. }
  3731. } );
  3732. value = v;
  3733. }
  3734. return new UniformNode( value, nodeType );
  3735. };
  3736. /**
  3737. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3738. * ```js
  3739. * const colors = array( [
  3740. * vec3( 1, 0, 0 ),
  3741. * vec3( 0, 1, 0 ),
  3742. * vec3( 0, 0, 1 )
  3743. * ] );
  3744. *
  3745. * const redColor = tintColors.element( 0 );
  3746. * ```
  3747. *
  3748. * @augments TempNode
  3749. */
  3750. class ArrayNode extends TempNode {
  3751. static get type() {
  3752. return 'ArrayNode';
  3753. }
  3754. /**
  3755. * Constructs a new array node.
  3756. *
  3757. * @param {?string} nodeType - The data type of the elements.
  3758. * @param {number} count - Size of the array.
  3759. * @param {?Array<Node>} [values=null] - Array default values.
  3760. */
  3761. constructor( nodeType, count, values = null ) {
  3762. super( nodeType );
  3763. /**
  3764. * Array size.
  3765. *
  3766. * @type {number}
  3767. */
  3768. this.count = count;
  3769. /**
  3770. * Array default values.
  3771. *
  3772. * @type {?Array<Node>}
  3773. */
  3774. this.values = values;
  3775. /**
  3776. * This flag can be used for type testing.
  3777. *
  3778. * @type {boolean}
  3779. * @readonly
  3780. * @default true
  3781. */
  3782. this.isArrayNode = true;
  3783. }
  3784. /**
  3785. * Returns the number of elements in the node array.
  3786. *
  3787. * @param {NodeBuilder} builder - The current node builder.
  3788. * @return {number} The number of elements in the node array.
  3789. */
  3790. getArrayCount( /*builder*/ ) {
  3791. return this.count;
  3792. }
  3793. /**
  3794. * Returns the node's type.
  3795. *
  3796. * @param {NodeBuilder} builder - The current node builder.
  3797. * @return {string} The type of the node.
  3798. */
  3799. generateNodeType( builder ) {
  3800. if ( this.nodeType === null ) {
  3801. return this.values[ 0 ].getNodeType( builder );
  3802. }
  3803. return this.nodeType;
  3804. }
  3805. /**
  3806. * Returns the node's type.
  3807. *
  3808. * @param {NodeBuilder} builder - The current node builder.
  3809. * @return {string} The type of the node.
  3810. */
  3811. getElementType( builder ) {
  3812. return this.getNodeType( builder );
  3813. }
  3814. /**
  3815. * Returns the type of a member variable.
  3816. *
  3817. * @param {NodeBuilder} builder - The current node builder.
  3818. * @param {string} name - The name of the member variable.
  3819. * @return {string} The type of the member variable.
  3820. */
  3821. getMemberType( builder, name ) {
  3822. if ( this.nodeType === null ) {
  3823. return this.values[ 0 ].getMemberType( builder, name );
  3824. }
  3825. return super.getMemberType( builder, name );
  3826. }
  3827. /**
  3828. * This method builds the output node and returns the resulting array as a shader string.
  3829. *
  3830. * @param {NodeBuilder} builder - The current node builder.
  3831. * @return {string} The generated shader string.
  3832. */
  3833. generate( builder ) {
  3834. const type = this.getNodeType( builder );
  3835. return builder.generateArray( type, this.count, this.values );
  3836. }
  3837. }
  3838. /**
  3839. * TSL function for creating an array node.
  3840. *
  3841. * @tsl
  3842. * @function
  3843. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3844. * or an array containing the default values (e.g., [ vec3() ]).
  3845. * @param {?number} [count] - Size of the array.
  3846. * @returns {ArrayNode}
  3847. */
  3848. const array = ( ...params ) => {
  3849. let node;
  3850. if ( params.length === 1 ) {
  3851. const values = params[ 0 ];
  3852. node = new ArrayNode( null, values.length, values );
  3853. } else {
  3854. const nodeType = params[ 0 ];
  3855. const count = params[ 1 ];
  3856. node = new ArrayNode( nodeType, count );
  3857. }
  3858. return nodeObject( node );
  3859. };
  3860. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3861. /**
  3862. * These node represents an assign operation. Meaning a node is assigned
  3863. * to another node.
  3864. *
  3865. * @augments TempNode
  3866. */
  3867. class AssignNode extends TempNode {
  3868. static get type() {
  3869. return 'AssignNode';
  3870. }
  3871. /**
  3872. * Constructs a new assign node.
  3873. *
  3874. * @param {Node} targetNode - The target node.
  3875. * @param {Node} sourceNode - The source type.
  3876. */
  3877. constructor( targetNode, sourceNode ) {
  3878. super();
  3879. /**
  3880. * The target node.
  3881. *
  3882. * @type {Node}
  3883. */
  3884. this.targetNode = targetNode;
  3885. /**
  3886. * The source node.
  3887. *
  3888. * @type {Node}
  3889. */
  3890. this.sourceNode = sourceNode;
  3891. /**
  3892. * This flag can be used for type testing.
  3893. *
  3894. * @type {boolean}
  3895. * @readonly
  3896. * @default true
  3897. */
  3898. this.isAssignNode = true;
  3899. }
  3900. /**
  3901. * Whether this node is used more than once in context of other nodes. This method
  3902. * is overwritten since it always returns `false` (assigns are unique).
  3903. *
  3904. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3905. */
  3906. hasDependencies() {
  3907. return false;
  3908. }
  3909. generateNodeType( builder, output ) {
  3910. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3911. }
  3912. /**
  3913. * Whether a split is required when assigning source to target. This can happen when the component length of
  3914. * target and source data type does not match.
  3915. *
  3916. * @param {NodeBuilder} builder - The current node builder.
  3917. * @return {boolean} Whether a split is required when assigning source to target.
  3918. */
  3919. needsSplitAssign( builder ) {
  3920. const { targetNode } = this;
  3921. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3922. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3923. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3924. return assignDifferentVector;
  3925. }
  3926. return false;
  3927. }
  3928. setup( builder ) {
  3929. const { targetNode, sourceNode } = this;
  3930. const scope = targetNode.getScope();
  3931. const scopeData = builder.getDataFromNode( scope );
  3932. scopeData.assign = true;
  3933. const properties = builder.getNodeProperties( this );
  3934. properties.sourceNode = sourceNode;
  3935. properties.targetNode = targetNode.context( { assign: true } );
  3936. }
  3937. generate( builder, output ) {
  3938. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3939. const needsSplitAssign = this.needsSplitAssign( builder );
  3940. const target = targetNode.build( builder );
  3941. const targetType = targetNode.getNodeType( builder );
  3942. const source = sourceNode.build( builder, targetType );
  3943. const sourceType = sourceNode.getNodeType( builder );
  3944. const nodeData = builder.getDataFromNode( this );
  3945. //
  3946. let snippet;
  3947. if ( nodeData.initialized === true ) {
  3948. if ( output !== 'void' ) {
  3949. snippet = target;
  3950. }
  3951. } else if ( needsSplitAssign ) {
  3952. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3953. const sourceProperty = builder.getPropertyName( sourceVar );
  3954. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3955. const splitNode = targetNode.node;
  3956. const splitTargetNode = splitNode.node.context( { assign: true } );
  3957. const targetRoot = splitTargetNode.build( builder );
  3958. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3959. const component = splitNode.components[ i ];
  3960. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3961. }
  3962. if ( output !== 'void' ) {
  3963. snippet = target;
  3964. }
  3965. } else {
  3966. snippet = `${ target } = ${ source }`;
  3967. if ( output === 'void' || sourceType === 'void' ) {
  3968. builder.addLineFlowCode( snippet, this );
  3969. if ( output !== 'void' ) {
  3970. snippet = target;
  3971. }
  3972. }
  3973. }
  3974. nodeData.initialized = true;
  3975. return builder.format( snippet, targetType, output );
  3976. }
  3977. }
  3978. /**
  3979. * TSL function for creating an assign node.
  3980. *
  3981. * @tsl
  3982. * @function
  3983. * @param {Node} targetNode - The target node.
  3984. * @param {Node} sourceNode - The source type.
  3985. * @returns {AssignNode}
  3986. */
  3987. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3988. addMethodChaining( 'assign', assign );
  3989. /**
  3990. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3991. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3992. * this logic.
  3993. *
  3994. * @augments TempNode
  3995. */
  3996. class FunctionCallNode extends TempNode {
  3997. static get type() {
  3998. return 'FunctionCallNode';
  3999. }
  4000. /**
  4001. * Constructs a new function call node.
  4002. *
  4003. * @param {?FunctionNode} functionNode - The function node.
  4004. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  4005. */
  4006. constructor( functionNode = null, parameters = {} ) {
  4007. super();
  4008. /**
  4009. * The function node.
  4010. *
  4011. * @type {?FunctionNode}
  4012. * @default null
  4013. */
  4014. this.functionNode = functionNode;
  4015. /**
  4016. * The parameters of the function call.
  4017. *
  4018. * @type {Object<string, Node>}
  4019. * @default {}
  4020. */
  4021. this.parameters = parameters;
  4022. }
  4023. /**
  4024. * Sets the parameters of the function call node.
  4025. *
  4026. * @param {Object<string, Node>} parameters - The parameters to set.
  4027. * @return {FunctionCallNode} A reference to this node.
  4028. */
  4029. setParameters( parameters ) {
  4030. this.parameters = parameters;
  4031. return this;
  4032. }
  4033. /**
  4034. * Returns the parameters of the function call node.
  4035. *
  4036. * @return {Object<string, Node>} The parameters of this node.
  4037. */
  4038. getParameters() {
  4039. return this.parameters;
  4040. }
  4041. /**
  4042. * Returns the type of this function call node.
  4043. *
  4044. * @param {NodeBuilder} builder - The current node builder.
  4045. * @returns {string} The type of this node.
  4046. */
  4047. generateNodeType( builder ) {
  4048. return this.functionNode.getNodeType( builder );
  4049. }
  4050. /**
  4051. * Returns the function node of this function call node.
  4052. *
  4053. * @param {NodeBuilder} builder - The current node builder.
  4054. * @param {string} [name] - The name of the member.
  4055. * @returns {string} The type of the member.
  4056. */
  4057. getMemberType( builder, name ) {
  4058. return this.functionNode.getMemberType( builder, name );
  4059. }
  4060. generate( builder ) {
  4061. const params = [];
  4062. const functionNode = this.functionNode;
  4063. const inputs = functionNode.getInputs( builder );
  4064. const parameters = this.parameters;
  4065. const generateInput = ( node, inputNode ) => {
  4066. const type = inputNode.type;
  4067. const pointer = type === 'pointer';
  4068. let output;
  4069. if ( pointer ) output = '&' + node.build( builder );
  4070. else output = node.build( builder, type );
  4071. return output;
  4072. };
  4073. if ( Array.isArray( parameters ) ) {
  4074. if ( parameters.length > inputs.length ) {
  4075. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  4076. parameters.length = inputs.length;
  4077. } else if ( parameters.length < inputs.length ) {
  4078. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  4079. while ( parameters.length < inputs.length ) {
  4080. parameters.push( float( 0 ) );
  4081. }
  4082. }
  4083. for ( let i = 0; i < parameters.length; i ++ ) {
  4084. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  4085. }
  4086. } else {
  4087. for ( const inputNode of inputs ) {
  4088. const node = parameters[ inputNode.name ];
  4089. if ( node !== undefined ) {
  4090. params.push( generateInput( node, inputNode ) );
  4091. } else {
  4092. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  4093. params.push( generateInput( float( 0 ), inputNode ) );
  4094. }
  4095. }
  4096. }
  4097. const functionName = functionNode.build( builder, 'property' );
  4098. return `${ functionName }( ${ params.join( ', ' ) } )`;
  4099. }
  4100. }
  4101. const call = ( func, ...params ) => {
  4102. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  4103. return new FunctionCallNode( nodeObject( func ), params );
  4104. };
  4105. addMethodChaining( 'call', call );
  4106. const _vectorOperators = {
  4107. '==': 'equal',
  4108. '!=': 'notEqual',
  4109. '<': 'lessThan',
  4110. '>': 'greaterThan',
  4111. '<=': 'lessThanEqual',
  4112. '>=': 'greaterThanEqual',
  4113. '%': 'mod'
  4114. };
  4115. /**
  4116. * This node represents basic mathematical and logical operations like addition,
  4117. * subtraction or comparisons (e.g. `equal()`).
  4118. *
  4119. * @augments TempNode
  4120. */
  4121. class OperatorNode extends TempNode {
  4122. static get type() {
  4123. return 'OperatorNode';
  4124. }
  4125. /**
  4126. * Constructs a new operator node.
  4127. *
  4128. * @param {string} op - The operator.
  4129. * @param {Node} aNode - The first input.
  4130. * @param {Node} bNode - The second input.
  4131. * @param {...Node} params - Additional input parameters.
  4132. */
  4133. constructor( op, aNode, bNode, ...params ) {
  4134. super();
  4135. if ( params.length > 0 ) {
  4136. let finalOp = new OperatorNode( op, aNode, bNode );
  4137. for ( let i = 0; i < params.length - 1; i ++ ) {
  4138. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  4139. }
  4140. aNode = finalOp;
  4141. bNode = params[ params.length - 1 ];
  4142. }
  4143. /**
  4144. * The operator.
  4145. *
  4146. * @type {string}
  4147. */
  4148. this.op = op;
  4149. /**
  4150. * The first input.
  4151. *
  4152. * @type {Node}
  4153. */
  4154. this.aNode = aNode;
  4155. /**
  4156. * The second input.
  4157. *
  4158. * @type {Node}
  4159. */
  4160. this.bNode = bNode;
  4161. /**
  4162. * This flag can be used for type testing.
  4163. *
  4164. * @type {boolean}
  4165. * @readonly
  4166. * @default true
  4167. */
  4168. this.isOperatorNode = true;
  4169. }
  4170. /**
  4171. * Returns the operator method name.
  4172. *
  4173. * @param {NodeBuilder} builder - The current node builder.
  4174. * @param {string} output - The output type.
  4175. * @returns {string} The operator method name.
  4176. */
  4177. getOperatorMethod( builder, output ) {
  4178. return builder.getMethod( _vectorOperators[ this.op ], output );
  4179. }
  4180. /**
  4181. * This method is overwritten since the node type is inferred from the operator
  4182. * and the input node types.
  4183. *
  4184. * @param {NodeBuilder} builder - The current node builder.
  4185. * @param {?string} [output=null] - The output type.
  4186. * @return {string} The node type.
  4187. */
  4188. generateNodeType( builder, output = null ) {
  4189. const op = this.op;
  4190. const aNode = this.aNode;
  4191. const bNode = this.bNode;
  4192. const typeA = aNode.getNodeType( builder );
  4193. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  4194. if ( typeA === 'void' || typeB === 'void' ) {
  4195. return output || 'void';
  4196. } else if ( op === '%' ) {
  4197. return typeA;
  4198. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  4199. return builder.getIntegerType( typeA );
  4200. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  4201. return 'bool';
  4202. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  4203. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  4204. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  4205. } else {
  4206. // Handle matrix operations
  4207. if ( builder.isMatrix( typeA ) ) {
  4208. if ( typeB === 'float' ) {
  4209. return typeA; // matrix * scalar = matrix
  4210. } else if ( builder.isVector( typeB ) ) {
  4211. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  4212. } else if ( builder.isMatrix( typeB ) ) {
  4213. return typeA; // matrix * matrix
  4214. }
  4215. } else if ( builder.isMatrix( typeB ) ) {
  4216. if ( typeA === 'float' ) {
  4217. return typeB; // scalar * matrix = matrix
  4218. } else if ( builder.isVector( typeA ) ) {
  4219. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  4220. }
  4221. }
  4222. // Handle non-matrix cases
  4223. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  4224. // anytype x anytype: use the greater length vector
  4225. return typeB;
  4226. }
  4227. return typeA;
  4228. }
  4229. }
  4230. generate( builder, output ) {
  4231. const op = this.op;
  4232. const { aNode, bNode } = this;
  4233. const type = this.getNodeType( builder, output );
  4234. let typeA = null;
  4235. let typeB = null;
  4236. if ( type !== 'void' ) {
  4237. typeA = aNode.getNodeType( builder );
  4238. typeB = bNode ? bNode.getNodeType( builder ) : null;
  4239. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  4240. if ( builder.isVector( typeA ) ) {
  4241. typeB = typeA;
  4242. } else if ( builder.isVector( typeB ) ) {
  4243. typeA = typeB;
  4244. } else if ( typeA !== typeB ) {
  4245. typeA = typeB = 'float';
  4246. }
  4247. } else if ( op === '>>' || op === '<<' ) {
  4248. typeA = type;
  4249. typeB = builder.changeComponentType( typeB, 'uint' );
  4250. } else if ( op === '%' ) {
  4251. typeA = type;
  4252. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  4253. } else if ( builder.isMatrix( typeA ) ) {
  4254. if ( typeB === 'float' ) {
  4255. // Keep matrix type for typeA, but ensure typeB stays float
  4256. typeB = 'float';
  4257. } else if ( builder.isVector( typeB ) ) {
  4258. // matrix x vector
  4259. typeB = builder.getVectorFromMatrix( typeA );
  4260. } else if ( builder.isMatrix( typeB ) ) ; else {
  4261. typeA = typeB = type;
  4262. }
  4263. } else if ( builder.isMatrix( typeB ) ) {
  4264. if ( typeA === 'float' ) {
  4265. // Keep matrix type for typeB, but ensure typeA stays float
  4266. typeA = 'float';
  4267. } else if ( builder.isVector( typeA ) ) {
  4268. // vector x matrix
  4269. typeA = builder.getVectorFromMatrix( typeB );
  4270. } else {
  4271. typeA = typeB = type;
  4272. }
  4273. } else {
  4274. // anytype x anytype
  4275. typeA = typeB = type;
  4276. }
  4277. } else {
  4278. typeA = typeB = type;
  4279. }
  4280. const a = aNode.build( builder, typeA );
  4281. const b = bNode ? bNode.build( builder, typeB ) : null;
  4282. const fnOpSnippet = builder.getFunctionOperator( op );
  4283. if ( output !== 'void' ) {
  4284. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  4285. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  4286. if ( isGLSL ) {
  4287. if ( builder.isVector( typeA ) ) {
  4288. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  4289. } else {
  4290. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4291. }
  4292. } else {
  4293. // WGSL
  4294. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4295. }
  4296. } else if ( op === '%' ) {
  4297. if ( builder.isInteger( typeB ) ) {
  4298. return builder.format( `( ${ a } % ${ b } )`, type, output );
  4299. } else {
  4300. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  4301. }
  4302. } else if ( op === '!' || op === '~' ) {
  4303. return builder.format( `(${op}${a})`, typeA, output );
  4304. } else if ( fnOpSnippet ) {
  4305. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4306. } else {
  4307. // Handle matrix operations
  4308. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4309. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  4310. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4311. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4312. } else {
  4313. let snippet = `( ${ a } ${ op } ${ b } )`;
  4314. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4315. snippet = `all${ snippet }`;
  4316. }
  4317. return builder.format( snippet, type, output );
  4318. }
  4319. }
  4320. } else if ( typeA !== 'void' ) {
  4321. if ( fnOpSnippet ) {
  4322. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4323. } else {
  4324. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4325. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4326. } else {
  4327. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4328. }
  4329. }
  4330. }
  4331. }
  4332. serialize( data ) {
  4333. super.serialize( data );
  4334. data.op = this.op;
  4335. }
  4336. deserialize( data ) {
  4337. super.deserialize( data );
  4338. this.op = data.op;
  4339. }
  4340. }
  4341. /**
  4342. * Returns the addition of two or more value.
  4343. *
  4344. * @tsl
  4345. * @function
  4346. * @param {Node} a - The first input.
  4347. * @param {Node} b - The second input.
  4348. * @param {...Node} params - Additional input parameters.
  4349. * @returns {OperatorNode}
  4350. */
  4351. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4352. /**
  4353. * Returns the subtraction of two or more value.
  4354. *
  4355. * @tsl
  4356. * @function
  4357. * @param {Node} a - The first input.
  4358. * @param {Node} b - The second input.
  4359. * @param {...Node} params - Additional input parameters.
  4360. * @returns {OperatorNode}
  4361. */
  4362. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4363. /**
  4364. * Returns the multiplication of two or more value.
  4365. *
  4366. * @tsl
  4367. * @function
  4368. * @param {Node} a - The first input.
  4369. * @param {Node} b - The second input.
  4370. * @param {...Node} params - Additional input parameters.
  4371. * @returns {OperatorNode}
  4372. */
  4373. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4374. /**
  4375. * Returns the division of two or more value.
  4376. *
  4377. * @tsl
  4378. * @function
  4379. * @param {Node} a - The first input.
  4380. * @param {Node} b - The second input.
  4381. * @param {...Node} params - Additional input parameters.
  4382. * @returns {OperatorNode}
  4383. */
  4384. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4385. /**
  4386. * Computes the remainder of dividing the first node by the second one.
  4387. *
  4388. * @tsl
  4389. * @function
  4390. * @param {Node} a - The first input.
  4391. * @param {Node} b - The second input.
  4392. * @returns {OperatorNode}
  4393. */
  4394. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4395. /**
  4396. * Checks if two nodes are equal.
  4397. *
  4398. * @tsl
  4399. * @function
  4400. * @param {Node} a - The first input.
  4401. * @param {Node} b - The second input.
  4402. * @returns {OperatorNode}
  4403. */
  4404. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4405. /**
  4406. * Checks if two nodes are not equal.
  4407. *
  4408. * @tsl
  4409. * @function
  4410. * @param {Node} a - The first input.
  4411. * @param {Node} b - The second input.
  4412. * @returns {OperatorNode}
  4413. */
  4414. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4415. /**
  4416. * Checks if the first node is less than the second.
  4417. *
  4418. * @tsl
  4419. * @function
  4420. * @param {Node} a - The first input.
  4421. * @param {Node} b - The second input.
  4422. * @returns {OperatorNode}
  4423. */
  4424. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4425. /**
  4426. * Checks if the first node is greater than the second.
  4427. *
  4428. * @tsl
  4429. * @function
  4430. * @param {Node} a - The first input.
  4431. * @param {Node} b - The second input.
  4432. * @returns {OperatorNode}
  4433. */
  4434. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4435. /**
  4436. * Checks if the first node is less than or equal to the second.
  4437. *
  4438. * @tsl
  4439. * @function
  4440. * @param {Node} a - The first input.
  4441. * @param {Node} b - The second input.
  4442. * @returns {OperatorNode}
  4443. */
  4444. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4445. /**
  4446. * Checks if the first node is greater than or equal to the second.
  4447. *
  4448. * @tsl
  4449. * @function
  4450. * @param {Node} a - The first input.
  4451. * @param {Node} b - The second input.
  4452. * @returns {OperatorNode}
  4453. */
  4454. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4455. /**
  4456. * Performs a logical AND operation on multiple nodes.
  4457. *
  4458. * @tsl
  4459. * @function
  4460. * @param {...Node} nodes - The input nodes to be combined using AND.
  4461. * @returns {OperatorNode}
  4462. */
  4463. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4464. /**
  4465. * Performs a logical OR operation on multiple nodes.
  4466. *
  4467. * @tsl
  4468. * @function
  4469. * @param {...Node} nodes - The input nodes to be combined using OR.
  4470. * @returns {OperatorNode}
  4471. */
  4472. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4473. /**
  4474. * Performs logical NOT on a node.
  4475. *
  4476. * @tsl
  4477. * @function
  4478. * @param {Node} value - The value.
  4479. * @returns {OperatorNode}
  4480. */
  4481. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4482. /**
  4483. * Performs logical XOR on two nodes.
  4484. *
  4485. * @tsl
  4486. * @function
  4487. * @param {Node} a - The first input.
  4488. * @param {Node} b - The second input.
  4489. * @returns {OperatorNode}
  4490. */
  4491. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4492. /**
  4493. * Performs bitwise AND on two nodes.
  4494. *
  4495. * @tsl
  4496. * @function
  4497. * @param {Node} a - The first input.
  4498. * @param {Node} b - The second input.
  4499. * @returns {OperatorNode}
  4500. */
  4501. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4502. /**
  4503. * Performs bitwise NOT on a node.
  4504. *
  4505. * @tsl
  4506. * @function
  4507. * @param {Node} a - The first input.
  4508. * @param {Node} b - The second input.
  4509. * @returns {OperatorNode}
  4510. */
  4511. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4512. /**
  4513. * Performs bitwise OR on two nodes.
  4514. *
  4515. * @tsl
  4516. * @function
  4517. * @param {Node} a - The first input.
  4518. * @param {Node} b - The second input.
  4519. * @returns {OperatorNode}
  4520. */
  4521. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4522. /**
  4523. * Performs bitwise XOR on two nodes.
  4524. *
  4525. * @tsl
  4526. * @function
  4527. * @param {Node} a - The first input.
  4528. * @param {Node} b - The second input.
  4529. * @returns {OperatorNode}
  4530. */
  4531. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4532. /**
  4533. * Shifts a node to the left.
  4534. *
  4535. * @tsl
  4536. * @function
  4537. * @param {Node} a - The node to shift.
  4538. * @param {Node} b - The value to shift.
  4539. * @returns {OperatorNode}
  4540. */
  4541. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4542. /**
  4543. * Shifts a node to the right.
  4544. *
  4545. * @tsl
  4546. * @function
  4547. * @param {Node} a - The node to shift.
  4548. * @param {Node} b - The value to shift.
  4549. * @returns {OperatorNode}
  4550. */
  4551. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4552. /**
  4553. * Increments a node by 1.
  4554. *
  4555. * @tsl
  4556. * @function
  4557. * @param {Node} a - The node to increment.
  4558. * @returns {OperatorNode}
  4559. */
  4560. const incrementBefore = Fn( ( [ a ] ) => {
  4561. a.addAssign( 1 );
  4562. return a;
  4563. } );
  4564. /**
  4565. * Decrements a node by 1.
  4566. *
  4567. * @tsl
  4568. * @function
  4569. * @param {Node} a - The node to decrement.
  4570. * @returns {OperatorNode}
  4571. */
  4572. const decrementBefore = Fn( ( [ a ] ) => {
  4573. a.subAssign( 1 );
  4574. return a;
  4575. } );
  4576. /**
  4577. * Increments a node by 1 and returns the previous value.
  4578. *
  4579. * @tsl
  4580. * @function
  4581. * @param {Node} a - The node to increment.
  4582. * @returns {OperatorNode}
  4583. */
  4584. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4585. const temp = int( a ).toConst();
  4586. a.addAssign( 1 );
  4587. return temp;
  4588. } );
  4589. /**
  4590. * Decrements a node by 1 and returns the previous value.
  4591. *
  4592. * @tsl
  4593. * @function
  4594. * @param {Node} a - The node to decrement.
  4595. * @returns {OperatorNode}
  4596. */
  4597. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4598. const temp = int( a ).toConst();
  4599. a.subAssign( 1 );
  4600. return temp;
  4601. } );
  4602. addMethodChaining( 'add', add );
  4603. addMethodChaining( 'sub', sub );
  4604. addMethodChaining( 'mul', mul );
  4605. addMethodChaining( 'div', div );
  4606. addMethodChaining( 'mod', mod );
  4607. addMethodChaining( 'equal', equal );
  4608. addMethodChaining( 'notEqual', notEqual );
  4609. addMethodChaining( 'lessThan', lessThan );
  4610. addMethodChaining( 'greaterThan', greaterThan );
  4611. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4612. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4613. addMethodChaining( 'and', and );
  4614. addMethodChaining( 'or', or );
  4615. addMethodChaining( 'not', not );
  4616. addMethodChaining( 'xor', xor );
  4617. addMethodChaining( 'bitAnd', bitAnd );
  4618. addMethodChaining( 'bitNot', bitNot );
  4619. addMethodChaining( 'bitOr', bitOr );
  4620. addMethodChaining( 'bitXor', bitXor );
  4621. addMethodChaining( 'shiftLeft', shiftLeft );
  4622. addMethodChaining( 'shiftRight', shiftRight );
  4623. addMethodChaining( 'incrementBefore', incrementBefore );
  4624. addMethodChaining( 'decrementBefore', decrementBefore );
  4625. addMethodChaining( 'increment', increment );
  4626. addMethodChaining( 'decrement', decrement );
  4627. /**
  4628. * @tsl
  4629. * @function
  4630. * @deprecated since r175. Use {@link mod} instead.
  4631. *
  4632. * @param {Node} a - The first input.
  4633. * @param {Node} b - The second input.
  4634. * @returns {OperatorNode}
  4635. */
  4636. const modInt = ( a, b ) => { // @deprecated, r175
  4637. warn( 'TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.', new StackTrace() );
  4638. return mod( int( a ), int( b ) );
  4639. };
  4640. addMethodChaining( 'modInt', modInt );
  4641. /**
  4642. * This node represents a variety of mathematical methods available in shaders.
  4643. * They are divided into three categories:
  4644. *
  4645. * - Methods with one input like `sin`, `cos` or `normalize`.
  4646. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4647. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4648. *
  4649. * @augments TempNode
  4650. */
  4651. class MathNode extends TempNode {
  4652. static get type() {
  4653. return 'MathNode';
  4654. }
  4655. /**
  4656. * Constructs a new math node.
  4657. *
  4658. * @param {string} method - The method name.
  4659. * @param {Node} aNode - The first input.
  4660. * @param {?Node} [bNode=null] - The second input.
  4661. * @param {?Node} [cNode=null] - The third input.
  4662. */
  4663. constructor( method, aNode, bNode = null, cNode = null ) {
  4664. super();
  4665. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4666. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4667. let finalOp = new MathNode( method, aNode, bNode );
  4668. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4669. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4670. }
  4671. aNode = finalOp;
  4672. bNode = arguments[ arguments.length - 1 ];
  4673. cNode = null;
  4674. }
  4675. /**
  4676. * The method name.
  4677. *
  4678. * @type {string}
  4679. */
  4680. this.method = method;
  4681. /**
  4682. * The first input.
  4683. *
  4684. * @type {Node}
  4685. */
  4686. this.aNode = aNode;
  4687. /**
  4688. * The second input.
  4689. *
  4690. * @type {?Node}
  4691. * @default null
  4692. */
  4693. this.bNode = bNode;
  4694. /**
  4695. * The third input.
  4696. *
  4697. * @type {?Node}
  4698. * @default null
  4699. */
  4700. this.cNode = cNode;
  4701. /**
  4702. * This flag can be used for type testing.
  4703. *
  4704. * @type {boolean}
  4705. * @readonly
  4706. * @default true
  4707. */
  4708. this.isMathNode = true;
  4709. }
  4710. /**
  4711. * The input type is inferred from the node types of the input nodes.
  4712. *
  4713. * @param {NodeBuilder} builder - The current node builder.
  4714. * @return {string} The input type.
  4715. */
  4716. getInputType( builder ) {
  4717. const aType = this.aNode.getNodeType( builder );
  4718. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4719. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4720. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4721. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4722. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4723. if ( aLen > bLen && aLen > cLen ) {
  4724. return aType;
  4725. } else if ( bLen > cLen ) {
  4726. return bType;
  4727. } else if ( cLen > aLen ) {
  4728. return cType;
  4729. }
  4730. return aType;
  4731. }
  4732. /**
  4733. * The selected method as well as the input type determine the node type of this node.
  4734. *
  4735. * @param {NodeBuilder} builder - The current node builder.
  4736. * @return {string} The node type.
  4737. */
  4738. generateNodeType( builder ) {
  4739. const method = this.method;
  4740. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4741. return 'float';
  4742. } else if ( method === MathNode.CROSS ) {
  4743. return 'vec3';
  4744. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4745. return 'bool';
  4746. } else if ( method === MathNode.EQUALS ) {
  4747. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4748. } else {
  4749. return this.getInputType( builder );
  4750. }
  4751. }
  4752. setup( builder ) {
  4753. const { aNode, bNode, method } = this;
  4754. let outputNode = null;
  4755. if ( method === MathNode.ONE_MINUS ) {
  4756. outputNode = sub( 1.0, aNode );
  4757. } else if ( method === MathNode.RECIPROCAL ) {
  4758. outputNode = div( 1.0, aNode );
  4759. } else if ( method === MathNode.DIFFERENCE ) {
  4760. outputNode = abs( sub( aNode, bNode ) );
  4761. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4762. // dir can be either a direction vector or a normal vector
  4763. // upper-left 3x3 of matrix is assumed to be orthogonal
  4764. let tA = aNode;
  4765. let tB = bNode;
  4766. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4767. tB = vec4( vec3( tB ), 0.0 );
  4768. } else {
  4769. tA = vec4( vec3( tA ), 0.0 );
  4770. }
  4771. const mulNode = mul( tA, tB ).xyz;
  4772. outputNode = normalize( mulNode );
  4773. }
  4774. if ( outputNode !== null ) {
  4775. return outputNode;
  4776. } else {
  4777. return super.setup( builder );
  4778. }
  4779. }
  4780. generate( builder, output ) {
  4781. const properties = builder.getNodeProperties( this );
  4782. if ( properties.outputNode ) {
  4783. return super.generate( builder, output );
  4784. }
  4785. let method = this.method;
  4786. const type = this.getNodeType( builder );
  4787. const inputType = this.getInputType( builder );
  4788. const a = this.aNode;
  4789. const b = this.bNode;
  4790. const c = this.cNode;
  4791. const coordinateSystem = builder.renderer.coordinateSystem;
  4792. if ( method === MathNode.NEGATE ) {
  4793. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4794. } else {
  4795. const params = [];
  4796. if ( method === MathNode.CROSS ) {
  4797. params.push(
  4798. a.build( builder, type ),
  4799. b.build( builder, type )
  4800. );
  4801. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4802. params.push(
  4803. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4804. b.build( builder, inputType )
  4805. );
  4806. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4807. params.push(
  4808. a.build( builder, inputType ),
  4809. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4810. );
  4811. } else if ( method === MathNode.REFRACT ) {
  4812. params.push(
  4813. a.build( builder, inputType ),
  4814. b.build( builder, inputType ),
  4815. c.build( builder, 'float' )
  4816. );
  4817. } else if ( method === MathNode.MIX ) {
  4818. params.push(
  4819. a.build( builder, inputType ),
  4820. b.build( builder, inputType ),
  4821. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4822. );
  4823. } else {
  4824. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4825. method = 'atan2';
  4826. }
  4827. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4828. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.`, this.stackTrace );
  4829. method = '/*' + method + '*/';
  4830. }
  4831. params.push( a.build( builder, inputType ) );
  4832. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4833. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4834. }
  4835. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4836. }
  4837. }
  4838. serialize( data ) {
  4839. super.serialize( data );
  4840. data.method = this.method;
  4841. }
  4842. deserialize( data ) {
  4843. super.deserialize( data );
  4844. this.method = data.method;
  4845. }
  4846. }
  4847. // 1 input
  4848. MathNode.ALL = 'all';
  4849. MathNode.ANY = 'any';
  4850. MathNode.RADIANS = 'radians';
  4851. MathNode.DEGREES = 'degrees';
  4852. MathNode.EXP = 'exp';
  4853. MathNode.EXP2 = 'exp2';
  4854. MathNode.LOG = 'log';
  4855. MathNode.LOG2 = 'log2';
  4856. MathNode.SQRT = 'sqrt';
  4857. MathNode.INVERSE_SQRT = 'inversesqrt';
  4858. MathNode.FLOOR = 'floor';
  4859. MathNode.CEIL = 'ceil';
  4860. MathNode.NORMALIZE = 'normalize';
  4861. MathNode.FRACT = 'fract';
  4862. MathNode.SIN = 'sin';
  4863. MathNode.SINH = 'sinh';
  4864. MathNode.COS = 'cos';
  4865. MathNode.COSH = 'cosh';
  4866. MathNode.TAN = 'tan';
  4867. MathNode.TANH = 'tanh';
  4868. MathNode.ASIN = 'asin';
  4869. MathNode.ASINH = 'asinh';
  4870. MathNode.ACOS = 'acos';
  4871. MathNode.ACOSH = 'acosh';
  4872. MathNode.ATAN = 'atan';
  4873. MathNode.ATANH = 'atanh';
  4874. MathNode.ABS = 'abs';
  4875. MathNode.SIGN = 'sign';
  4876. MathNode.LENGTH = 'length';
  4877. MathNode.NEGATE = 'negate';
  4878. MathNode.ONE_MINUS = 'oneMinus';
  4879. MathNode.DFDX = 'dFdx';
  4880. MathNode.DFDY = 'dFdy';
  4881. MathNode.ROUND = 'round';
  4882. MathNode.RECIPROCAL = 'reciprocal';
  4883. MathNode.TRUNC = 'trunc';
  4884. MathNode.FWIDTH = 'fwidth';
  4885. MathNode.TRANSPOSE = 'transpose';
  4886. MathNode.DETERMINANT = 'determinant';
  4887. MathNode.INVERSE = 'inverse';
  4888. // 2 inputs
  4889. MathNode.EQUALS = 'equals';
  4890. MathNode.MIN = 'min';
  4891. MathNode.MAX = 'max';
  4892. MathNode.STEP = 'step';
  4893. MathNode.REFLECT = 'reflect';
  4894. MathNode.DISTANCE = 'distance';
  4895. MathNode.DIFFERENCE = 'difference';
  4896. MathNode.DOT = 'dot';
  4897. MathNode.CROSS = 'cross';
  4898. MathNode.POW = 'pow';
  4899. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4900. // 3 inputs
  4901. MathNode.MIX = 'mix';
  4902. MathNode.CLAMP = 'clamp';
  4903. MathNode.REFRACT = 'refract';
  4904. MathNode.SMOOTHSTEP = 'smoothstep';
  4905. MathNode.FACEFORWARD = 'faceforward';
  4906. // 1 inputs
  4907. /**
  4908. * A small value used to handle floating-point precision errors.
  4909. *
  4910. * @tsl
  4911. * @type {Node<float>}
  4912. */
  4913. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4914. /**
  4915. * Represents infinity.
  4916. *
  4917. * @tsl
  4918. * @type {Node<float>}
  4919. */
  4920. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4921. /**
  4922. * Represents PI.
  4923. *
  4924. * @tsl
  4925. * @type {Node<float>}
  4926. */
  4927. const PI = /*@__PURE__*/ float( Math.PI );
  4928. /**
  4929. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4930. *
  4931. * @tsl
  4932. * @deprecated
  4933. * @type {Node<float>}
  4934. */
  4935. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4936. /**
  4937. * Represents PI * 2.
  4938. *
  4939. * @tsl
  4940. * @type {Node<float>}
  4941. */
  4942. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4943. /**
  4944. * Represents PI / 2.
  4945. *
  4946. * @tsl
  4947. * @type {Node<float>}
  4948. */
  4949. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4950. /**
  4951. * Returns `true` if all components of `x` are `true`.
  4952. *
  4953. * @tsl
  4954. * @function
  4955. * @param {Node | number} x - The parameter.
  4956. * @returns {Node<bool>}
  4957. */
  4958. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4959. /**
  4960. * Returns `true` if any components of `x` are `true`.
  4961. *
  4962. * @tsl
  4963. * @function
  4964. * @param {Node | number} x - The parameter.
  4965. * @returns {Node<bool>}
  4966. */
  4967. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4968. /**
  4969. * Converts a quantity in degrees to radians.
  4970. *
  4971. * @tsl
  4972. * @function
  4973. * @param {Node | number} x - The input in degrees.
  4974. * @returns {Node}
  4975. */
  4976. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4977. /**
  4978. * Convert a quantity in radians to degrees.
  4979. *
  4980. * @tsl
  4981. * @function
  4982. * @param {Node | number} x - The input in radians.
  4983. * @returns {Node}
  4984. */
  4985. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4986. /**
  4987. * Returns the natural exponentiation of the parameter.
  4988. *
  4989. * @tsl
  4990. * @function
  4991. * @param {Node | number} x - The parameter.
  4992. * @returns {Node}
  4993. */
  4994. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4995. /**
  4996. * Returns 2 raised to the power of the parameter.
  4997. *
  4998. * @tsl
  4999. * @function
  5000. * @param {Node | number} x - The parameter.
  5001. * @returns {Node}
  5002. */
  5003. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  5004. /**
  5005. * Returns the natural logarithm of the parameter.
  5006. *
  5007. * @tsl
  5008. * @function
  5009. * @param {Node | number} x - The parameter.
  5010. * @returns {Node}
  5011. */
  5012. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  5013. /**
  5014. * Returns the base 2 logarithm of the parameter.
  5015. *
  5016. * @tsl
  5017. * @function
  5018. * @param {Node | number} x - The parameter.
  5019. * @returns {Node}
  5020. */
  5021. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  5022. /**
  5023. * Returns the square root of the parameter.
  5024. *
  5025. * @tsl
  5026. * @function
  5027. * @param {Node | number} x - The parameter.
  5028. * @returns {Node}
  5029. */
  5030. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  5031. /**
  5032. * Returns the inverse of the square root of the parameter.
  5033. *
  5034. * @tsl
  5035. * @function
  5036. * @param {Node | number} x - The parameter.
  5037. * @returns {Node}
  5038. */
  5039. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  5040. /**
  5041. * Finds the nearest integer less than or equal to the parameter.
  5042. *
  5043. * @tsl
  5044. * @function
  5045. * @param {Node | number} x - The parameter.
  5046. * @returns {Node}
  5047. */
  5048. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  5049. /**
  5050. * Finds the nearest integer that is greater than or equal to the parameter.
  5051. *
  5052. * @tsl
  5053. * @function
  5054. * @param {Node | number} x - The parameter.
  5055. * @returns {Node}
  5056. */
  5057. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  5058. /**
  5059. * Calculates the unit vector in the same direction as the original vector.
  5060. *
  5061. * @tsl
  5062. * @function
  5063. * @param {Node} x - The input vector.
  5064. * @returns {Node}
  5065. */
  5066. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  5067. /**
  5068. * Computes the fractional part of the parameter.
  5069. *
  5070. * @tsl
  5071. * @function
  5072. * @param {Node | number} x - The parameter.
  5073. * @returns {Node}
  5074. */
  5075. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  5076. /**
  5077. * Returns the sine of the parameter.
  5078. *
  5079. * @tsl
  5080. * @function
  5081. * @param {Node | number} x - The parameter.
  5082. * @returns {Node}
  5083. */
  5084. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  5085. /**
  5086. * Returns the hyperbolic sine of the parameter.
  5087. *
  5088. * @tsl
  5089. * @function
  5090. * @param {Node | number} x - The parameter.
  5091. * @returns {Node}
  5092. */
  5093. const sinh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SINH ).setParameterLength( 1 );
  5094. /**
  5095. * Returns the cosine of the parameter.
  5096. *
  5097. * @tsl
  5098. * @function
  5099. * @param {Node | number} x - The parameter.
  5100. * @returns {Node}
  5101. */
  5102. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  5103. /**
  5104. * Returns the hyperbolic cosine of the parameter.
  5105. *
  5106. * @tsl
  5107. * @function
  5108. * @param {Node | number} x - The parameter.
  5109. * @returns {Node}
  5110. */
  5111. const cosh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COSH ).setParameterLength( 1 );
  5112. /**
  5113. * Returns the tangent of the parameter.
  5114. *
  5115. * @tsl
  5116. * @function
  5117. * @param {Node | number} x - The parameter.
  5118. * @returns {Node}
  5119. */
  5120. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  5121. /**
  5122. * Returns the hyperbolic tangent of the parameter.
  5123. *
  5124. * @tsl
  5125. * @function
  5126. * @param {Node | number} x - The parameter.
  5127. * @returns {Node}
  5128. */
  5129. const tanh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TANH ).setParameterLength( 1 );
  5130. /**
  5131. * Returns the arcsine of the parameter.
  5132. *
  5133. * @tsl
  5134. * @function
  5135. * @param {Node | number} x - The parameter.
  5136. * @returns {Node}
  5137. */
  5138. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  5139. /**
  5140. * Returns the inverse hyperbolic sine of the parameter.
  5141. *
  5142. * @tsl
  5143. * @function
  5144. * @param {Node | number} x - The parameter.
  5145. * @returns {Node}
  5146. */
  5147. const asinh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASINH ).setParameterLength( 1 );
  5148. /**
  5149. * Returns the arccosine of the parameter.
  5150. *
  5151. * @tsl
  5152. * @function
  5153. * @param {Node | number} x - The parameter.
  5154. * @returns {Node}
  5155. */
  5156. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  5157. /**
  5158. * Returns the inverse hyperbolic cosine of the parameter.
  5159. *
  5160. * @tsl
  5161. * @function
  5162. * @param {Node | number} x - The parameter.
  5163. * @returns {Node}
  5164. */
  5165. const acosh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOSH ).setParameterLength( 1 );
  5166. /**
  5167. * Returns the arc-tangent of the parameter.
  5168. * If two parameters are provided, the result is `atan2(y/x)`.
  5169. *
  5170. * @tsl
  5171. * @function
  5172. * @param {Node | number} y - The y parameter.
  5173. * @param {?(Node | number)} x - The x parameter.
  5174. * @returns {Node}
  5175. */
  5176. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  5177. /**
  5178. * Returns the inverse hyperbolic tangent of the parameter.
  5179. *
  5180. * @tsl
  5181. * @function
  5182. * @param {Node | number} x - The parameter.
  5183. * @returns {Node}
  5184. */
  5185. const atanh = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATANH ).setParameterLength( 1 );
  5186. /**
  5187. * Returns the absolute value of the parameter.
  5188. *
  5189. * @tsl
  5190. * @function
  5191. * @param {Node | number} x - The parameter.
  5192. * @returns {Node}
  5193. */
  5194. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  5195. /**
  5196. * Extracts the sign of the parameter.
  5197. *
  5198. * @tsl
  5199. * @function
  5200. * @param {Node | number} x - The parameter.
  5201. * @returns {Node}
  5202. */
  5203. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  5204. /**
  5205. * Calculates the length of a vector.
  5206. *
  5207. * @tsl
  5208. * @function
  5209. * @param {Node} x - The parameter.
  5210. * @returns {Node<float>}
  5211. */
  5212. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  5213. /**
  5214. * Negates the value of the parameter (-x).
  5215. *
  5216. * @tsl
  5217. * @function
  5218. * @param {Node | number} x - The parameter.
  5219. * @returns {Node}
  5220. */
  5221. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  5222. /**
  5223. * Return `1` minus the parameter.
  5224. *
  5225. * @tsl
  5226. * @function
  5227. * @param {Node | number} x - The parameter.
  5228. * @returns {Node}
  5229. */
  5230. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  5231. /**
  5232. * Returns the partial derivative of the parameter with respect to x.
  5233. *
  5234. * @tsl
  5235. * @function
  5236. * @param {Node | number} x - The parameter.
  5237. * @returns {Node}
  5238. */
  5239. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  5240. /**
  5241. * Returns the partial derivative of the parameter with respect to y.
  5242. *
  5243. * @tsl
  5244. * @function
  5245. * @param {Node | number} x - The parameter.
  5246. * @returns {Node}
  5247. */
  5248. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  5249. /**
  5250. * Rounds the parameter to the nearest integer.
  5251. *
  5252. * @tsl
  5253. * @function
  5254. * @param {Node | number} x - The parameter.
  5255. * @returns {Node}
  5256. */
  5257. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  5258. /**
  5259. * Returns the reciprocal of the parameter `(1/x)`.
  5260. *
  5261. * @tsl
  5262. * @function
  5263. * @param {Node | number} x - The parameter.
  5264. * @returns {Node}
  5265. */
  5266. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  5267. /**
  5268. * Truncates the parameter, removing the fractional part.
  5269. *
  5270. * @tsl
  5271. * @function
  5272. * @param {Node | number} x - The parameter.
  5273. * @returns {Node}
  5274. */
  5275. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  5276. /**
  5277. * Returns the sum of the absolute derivatives in x and y.
  5278. *
  5279. * @tsl
  5280. * @function
  5281. * @param {Node | number} x - The parameter.
  5282. * @returns {Node}
  5283. */
  5284. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  5285. /**
  5286. * Returns the transpose of a matrix.
  5287. *
  5288. * @tsl
  5289. * @function
  5290. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5291. * @returns {Node}
  5292. */
  5293. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  5294. /**
  5295. * Returns the determinant of a matrix.
  5296. *
  5297. * @tsl
  5298. * @function
  5299. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5300. * @returns {Node<float>}
  5301. */
  5302. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  5303. /**
  5304. * Returns the inverse of a matrix.
  5305. *
  5306. * @tsl
  5307. * @function
  5308. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5309. * @returns {Node<mat2|mat3|mat4>}
  5310. */
  5311. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  5312. // 2 inputs
  5313. /**
  5314. * Returns the least of the given values.
  5315. *
  5316. * @tsl
  5317. * @function
  5318. * @param {...(Node | number)} values - The values to compare.
  5319. * @returns {Node}
  5320. */
  5321. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  5322. /**
  5323. * Returns the greatest of the given values.
  5324. *
  5325. * @tsl
  5326. * @function
  5327. * @param {...(Node | number)} values - The values to compare.
  5328. * @returns {Node}
  5329. */
  5330. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  5331. /**
  5332. * Generate a step function by comparing two values.
  5333. *
  5334. * @tsl
  5335. * @function
  5336. * @param {Node | number} x - The y parameter.
  5337. * @param {Node | number} y - The x parameter.
  5338. * @returns {Node}
  5339. */
  5340. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  5341. /**
  5342. * Calculates the reflection direction for an incident vector.
  5343. *
  5344. * @tsl
  5345. * @function
  5346. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5347. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5348. * @returns {Node<vec2|vec3|vec4>}
  5349. */
  5350. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  5351. /**
  5352. * Calculates the distance between two points.
  5353. *
  5354. * @tsl
  5355. * @function
  5356. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5357. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5358. * @returns {Node<float>}
  5359. */
  5360. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5361. /**
  5362. * Calculates the absolute difference between two values.
  5363. *
  5364. * @tsl
  5365. * @function
  5366. * @param {Node | number} x - The first parameter.
  5367. * @param {Node | number} y - The second parameter.
  5368. * @returns {Node}
  5369. */
  5370. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5371. /**
  5372. * Calculates the dot product of two vectors.
  5373. *
  5374. * @tsl
  5375. * @function
  5376. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5377. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5378. * @returns {Node<float>}
  5379. */
  5380. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5381. /**
  5382. * Calculates the cross product of two vectors.
  5383. *
  5384. * @tsl
  5385. * @function
  5386. * @param {Node<vec2|vec3>} x - The first vector.
  5387. * @param {Node<vec2|vec3>} y - The second vector.
  5388. * @returns {Node<float|vec3>}
  5389. */
  5390. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5391. /**
  5392. * Return the value of the first parameter raised to the power of the second one.
  5393. *
  5394. * @tsl
  5395. * @function
  5396. * @param {Node | number} x - The first parameter.
  5397. * @param {Node | number} y - The second parameter.
  5398. * @returns {Node}
  5399. */
  5400. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5401. /**
  5402. * Returns the square of the parameter.
  5403. *
  5404. * @tsl
  5405. * @function
  5406. * @param {Node | number} x - The first parameter.
  5407. * @returns {Node}
  5408. */
  5409. const pow2 = ( x ) => mul( x, x );
  5410. /**
  5411. * Returns the cube of the parameter.
  5412. *
  5413. * @tsl
  5414. * @function
  5415. * @param {Node | number} x - The first parameter.
  5416. * @returns {Node}
  5417. */
  5418. const pow3 = ( x ) => mul( x, x, x );
  5419. /**
  5420. * Returns the fourth power of the parameter.
  5421. *
  5422. * @tsl
  5423. * @function
  5424. * @param {Node | number} x - The first parameter.
  5425. * @returns {Node}
  5426. */
  5427. const pow4 = ( x ) => mul( x, x, x, x );
  5428. /**
  5429. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5430. *
  5431. * @tsl
  5432. * @function
  5433. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5434. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5435. * @returns {Node}
  5436. */
  5437. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5438. /**
  5439. * Returns the cube root of a number.
  5440. *
  5441. * @tsl
  5442. * @function
  5443. * @param {Node | number} a - The first parameter.
  5444. * @returns {Node}
  5445. */
  5446. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5447. /**
  5448. * Calculate the squared length of a vector.
  5449. *
  5450. * @tsl
  5451. * @function
  5452. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5453. * @returns {Node<float>}
  5454. */
  5455. const lengthSq = ( a ) => dot( a, a );
  5456. /**
  5457. * Linearly interpolates between two values.
  5458. *
  5459. * @tsl
  5460. * @function
  5461. * @param {Node | number} a - The first parameter.
  5462. * @param {Node | number} b - The second parameter.
  5463. * @param {Node | number} t - The interpolation value.
  5464. * @returns {Node}
  5465. */
  5466. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5467. /**
  5468. * Constrains a value to lie between two further values.
  5469. *
  5470. * @tsl
  5471. * @function
  5472. * @param {Node | number} value - The value to constrain.
  5473. * @param {Node | number} [low=0] - The lower bound.
  5474. * @param {Node | number} [high=1] - The upper bound.
  5475. * @returns {Node}
  5476. */
  5477. const clamp = ( value, low = 0, high = 1 ) => new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) );
  5478. /**
  5479. * Constrains a value between `0` and `1`.
  5480. *
  5481. * @tsl
  5482. * @function
  5483. * @param {Node | number} value - The value to constrain.
  5484. * @returns {Node}
  5485. */
  5486. const saturate = ( value ) => clamp( value );
  5487. /**
  5488. * Calculates the refraction direction for an incident vector.
  5489. *
  5490. * @tsl
  5491. * @function
  5492. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5493. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5494. * @param {Node<float>} eta - The ratio of indices of refraction.
  5495. * @returns {Node<vec2|vec3|vec4>}
  5496. */
  5497. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5498. /**
  5499. * Performs a Hermite interpolation between two values.
  5500. *
  5501. * @tsl
  5502. * @function
  5503. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5504. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5505. * @param {Node | number} x - The source value for interpolation.
  5506. * @returns {Node}
  5507. */
  5508. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5509. /**
  5510. * Returns a vector pointing in the same direction as another.
  5511. *
  5512. * @tsl
  5513. * @function
  5514. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5515. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5516. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5517. * @returns {Node<vec2|vec3|vec4>}
  5518. */
  5519. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5520. /**
  5521. * Returns a random value for the given uv.
  5522. *
  5523. * @tsl
  5524. * @function
  5525. * @param {Node<vec2>} uv - The uv node.
  5526. * @returns {Node<float>}
  5527. */
  5528. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5529. const a = 12.9898, b = 78.233, c = 43758.5453;
  5530. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5531. return fract( sin( sn ).mul( c ) );
  5532. } );
  5533. /**
  5534. * Alias for `mix()` with a different parameter order.
  5535. *
  5536. * @tsl
  5537. * @function
  5538. * @param {Node | number} t - The interpolation value.
  5539. * @param {Node | number} e1 - The first parameter.
  5540. * @param {Node | number} e2 - The second parameter.
  5541. * @returns {Node}
  5542. */
  5543. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5544. /**
  5545. * Alias for `smoothstep()` with a different parameter order.
  5546. *
  5547. * @tsl
  5548. * @function
  5549. * @param {Node | number} x - The source value for interpolation.
  5550. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5551. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5552. * @returns {Node}
  5553. */
  5554. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5555. /**
  5556. * Alias for `step()` with a different parameter order.
  5557. *
  5558. * @tsl
  5559. * @function
  5560. * @param {Node | number} x - The source value for interpolation.
  5561. * @param {Node | number} edge - The edge value.
  5562. * @returns {Node}
  5563. */
  5564. const stepElement = ( x, edge ) => step( edge, x );
  5565. // GLSL alias function
  5566. const faceforward = faceForward;
  5567. const inversesqrt = inverseSqrt;
  5568. // Method chaining
  5569. addMethodChaining( 'all', all );
  5570. addMethodChaining( 'any', any );
  5571. addMethodChaining( 'radians', radians );
  5572. addMethodChaining( 'degrees', degrees );
  5573. addMethodChaining( 'exp', exp );
  5574. addMethodChaining( 'exp2', exp2 );
  5575. addMethodChaining( 'log', log );
  5576. addMethodChaining( 'log2', log2 );
  5577. addMethodChaining( 'sqrt', sqrt );
  5578. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5579. addMethodChaining( 'floor', floor );
  5580. addMethodChaining( 'ceil', ceil );
  5581. addMethodChaining( 'normalize', normalize );
  5582. addMethodChaining( 'fract', fract );
  5583. addMethodChaining( 'sin', sin );
  5584. addMethodChaining( 'sinh', sinh );
  5585. addMethodChaining( 'cos', cos );
  5586. addMethodChaining( 'cosh', cosh );
  5587. addMethodChaining( 'tan', tan );
  5588. addMethodChaining( 'tanh', tanh );
  5589. addMethodChaining( 'asin', asin );
  5590. addMethodChaining( 'asinh', asinh );
  5591. addMethodChaining( 'acos', acos );
  5592. addMethodChaining( 'acosh', acosh );
  5593. addMethodChaining( 'atan', atan );
  5594. addMethodChaining( 'atanh', atanh );
  5595. addMethodChaining( 'abs', abs );
  5596. addMethodChaining( 'sign', sign );
  5597. addMethodChaining( 'length', length );
  5598. addMethodChaining( 'lengthSq', lengthSq );
  5599. addMethodChaining( 'negate', negate );
  5600. addMethodChaining( 'oneMinus', oneMinus );
  5601. addMethodChaining( 'dFdx', dFdx );
  5602. addMethodChaining( 'dFdy', dFdy );
  5603. addMethodChaining( 'round', round );
  5604. addMethodChaining( 'reciprocal', reciprocal );
  5605. addMethodChaining( 'trunc', trunc );
  5606. addMethodChaining( 'fwidth', fwidth );
  5607. addMethodChaining( 'min', min$1 );
  5608. addMethodChaining( 'max', max$1 );
  5609. addMethodChaining( 'step', stepElement );
  5610. addMethodChaining( 'reflect', reflect );
  5611. addMethodChaining( 'distance', distance );
  5612. addMethodChaining( 'dot', dot );
  5613. addMethodChaining( 'cross', cross );
  5614. addMethodChaining( 'pow', pow );
  5615. addMethodChaining( 'pow2', pow2 );
  5616. addMethodChaining( 'pow3', pow3 );
  5617. addMethodChaining( 'pow4', pow4 );
  5618. addMethodChaining( 'transformDirection', transformDirection );
  5619. addMethodChaining( 'mix', mixElement );
  5620. addMethodChaining( 'clamp', clamp );
  5621. addMethodChaining( 'refract', refract );
  5622. addMethodChaining( 'smoothstep', smoothstepElement );
  5623. addMethodChaining( 'faceForward', faceForward );
  5624. addMethodChaining( 'difference', difference );
  5625. addMethodChaining( 'saturate', saturate );
  5626. addMethodChaining( 'cbrt', cbrt );
  5627. addMethodChaining( 'transpose', transpose );
  5628. addMethodChaining( 'determinant', determinant );
  5629. addMethodChaining( 'inverse', inverse );
  5630. addMethodChaining( 'rand', rand );
  5631. /**
  5632. * Represents a logical `if/else` statement. Can be used as an alternative
  5633. * to the `If()`/`Else()` syntax.
  5634. *
  5635. * The corresponding TSL `select()` looks like so:
  5636. * ```js
  5637. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5638. * ```
  5639. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5640. * determine the outcome of the entire statement.
  5641. *
  5642. * @augments Node
  5643. */
  5644. class ConditionalNode extends Node {
  5645. static get type() {
  5646. return 'ConditionalNode';
  5647. }
  5648. /**
  5649. * Constructs a new conditional node.
  5650. *
  5651. * @param {Node} condNode - The node that defines the condition.
  5652. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5653. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5654. */
  5655. constructor( condNode, ifNode, elseNode = null ) {
  5656. super();
  5657. /**
  5658. * The node that defines the condition.
  5659. *
  5660. * @type {Node}
  5661. */
  5662. this.condNode = condNode;
  5663. /**
  5664. * The node that is evaluate when the condition ends up `true`.
  5665. *
  5666. * @type {Node}
  5667. */
  5668. this.ifNode = ifNode;
  5669. /**
  5670. * The node that is evaluate when the condition ends up `false`.
  5671. *
  5672. * @type {?Node}
  5673. * @default null
  5674. */
  5675. this.elseNode = elseNode;
  5676. }
  5677. /**
  5678. * This method is overwritten since the node type is inferred from the if/else
  5679. * nodes.
  5680. *
  5681. * @param {NodeBuilder} builder - The current node builder.
  5682. * @return {string} The node type.
  5683. */
  5684. generateNodeType( builder ) {
  5685. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5686. if ( ifNode === undefined ) {
  5687. // fallback setup
  5688. builder.flowBuildStage( this, 'setup' );
  5689. return this.getNodeType( builder );
  5690. }
  5691. const ifType = ifNode.getNodeType( builder );
  5692. if ( elseNode !== null ) {
  5693. const elseType = elseNode.getNodeType( builder );
  5694. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5695. return elseType;
  5696. }
  5697. }
  5698. return ifType;
  5699. }
  5700. setup( builder ) {
  5701. const condNode = this.condNode;
  5702. const ifNode = this.ifNode.isolate();
  5703. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5704. //
  5705. const currentNodeBlock = builder.context.nodeBlock;
  5706. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5707. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5708. //
  5709. const isUniformFlow = builder.context.uniformFlow;
  5710. const properties = builder.getNodeProperties( this );
  5711. properties.condNode = condNode;
  5712. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5713. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5714. }
  5715. generate( builder, output ) {
  5716. const type = this.getNodeType( builder );
  5717. const nodeData = builder.getDataFromNode( this );
  5718. if ( nodeData.nodeProperty !== undefined ) {
  5719. return nodeData.nodeProperty;
  5720. }
  5721. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5722. const functionNode = builder.currentFunctionNode;
  5723. const needsOutput = output !== 'void';
  5724. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5725. nodeData.nodeProperty = nodeProperty;
  5726. const nodeSnippet = condNode.build( builder, 'bool' );
  5727. const isUniformFlow = builder.context.uniformFlow;
  5728. if ( isUniformFlow && elseNode !== null ) {
  5729. const ifSnippet = ifNode.build( builder, type );
  5730. const elseSnippet = elseNode.build( builder, type );
  5731. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5732. // TODO: If node property already exists return something else
  5733. return builder.format( mathSnippet, type, output );
  5734. }
  5735. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5736. let ifSnippet = ifNode.build( builder, type );
  5737. if ( ifSnippet ) {
  5738. if ( needsOutput ) {
  5739. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5740. } else {
  5741. ifSnippet = 'return ' + ifSnippet + ';';
  5742. if ( functionNode === null ) {
  5743. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.', this.stackTrace );
  5744. ifSnippet = '// ' + ifSnippet;
  5745. }
  5746. }
  5747. }
  5748. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5749. if ( elseNode !== null ) {
  5750. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5751. let elseSnippet = elseNode.build( builder, type );
  5752. if ( elseSnippet ) {
  5753. if ( needsOutput ) {
  5754. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5755. } else {
  5756. elseSnippet = 'return ' + elseSnippet + ';';
  5757. if ( functionNode === null ) {
  5758. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.', this.stackTrace );
  5759. elseSnippet = '// ' + elseSnippet;
  5760. }
  5761. }
  5762. }
  5763. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5764. } else {
  5765. builder.addFlowCode( '\n\n' );
  5766. }
  5767. return builder.format( nodeProperty, type, output );
  5768. }
  5769. }
  5770. /**
  5771. * TSL function for creating a conditional node.
  5772. *
  5773. * @tsl
  5774. * @function
  5775. * @param {Node} condNode - The node that defines the condition.
  5776. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5777. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5778. * @returns {ConditionalNode}
  5779. */
  5780. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5781. addMethodChaining( 'select', select );
  5782. /**
  5783. * This node can be used as a context management component for another node.
  5784. * {@link NodeBuilder} performs its node building process in a specific context and
  5785. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5786. *
  5787. * ```js
  5788. *node.context( { getUV: () => customCoord } );
  5789. *\// or
  5790. *material.contextNode = context( { getUV: () => customCoord } );
  5791. *\// or
  5792. *renderer.contextNode = context( { getUV: () => customCoord } );
  5793. *\// or
  5794. *scenePass.contextNode = context( { getUV: () => customCoord } );
  5795. *```
  5796. * @augments Node
  5797. */
  5798. class ContextNode extends Node {
  5799. static get type() {
  5800. return 'ContextNode';
  5801. }
  5802. /**
  5803. * Constructs a new context node.
  5804. *
  5805. * @param {Node} node - The node whose context should be modified.
  5806. * @param {Object} [value={}] - The modified context data.
  5807. */
  5808. constructor( node = null, value = {} ) {
  5809. super();
  5810. /**
  5811. * This flag can be used for type testing.
  5812. *
  5813. * @type {boolean}
  5814. * @readonly
  5815. * @default true
  5816. */
  5817. this.isContextNode = true;
  5818. /**
  5819. * The node whose context should be modified.
  5820. *
  5821. * @type {Node}
  5822. */
  5823. this.node = node;
  5824. /**
  5825. * The modified context data.
  5826. *
  5827. * @type {Object}
  5828. * @default {}
  5829. */
  5830. this.value = value;
  5831. }
  5832. /**
  5833. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5834. *
  5835. * @return {Node} A reference to {@link ContextNode#node}.
  5836. */
  5837. getScope() {
  5838. return this.node.getScope();
  5839. }
  5840. /**
  5841. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5842. *
  5843. * @param {NodeBuilder} builder - The current node builder.
  5844. * @return {string} The node type.
  5845. */
  5846. generateNodeType( builder ) {
  5847. return this.node.getNodeType( builder );
  5848. }
  5849. /**
  5850. * Gathers the context data from all parent context nodes.
  5851. *
  5852. * @return {Object} The gathered context data.
  5853. */
  5854. getFlowContextData() {
  5855. const children = [];
  5856. this.traverse( ( node ) => {
  5857. if ( node.isContextNode === true ) {
  5858. children.push( node.value );
  5859. }
  5860. } );
  5861. return Object.assign( {}, ...children );
  5862. }
  5863. /**
  5864. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5865. *
  5866. * @param {NodeBuilder} builder - The current node builder.
  5867. * @param {string} name - The member name.
  5868. * @returns {string} The member type.
  5869. */
  5870. getMemberType( builder, name ) {
  5871. return this.node.getMemberType( builder, name );
  5872. }
  5873. analyze( builder ) {
  5874. const previousContext = builder.addContext( this.value );
  5875. this.node.build( builder );
  5876. builder.setContext( previousContext );
  5877. }
  5878. setup( builder ) {
  5879. const previousContext = builder.addContext( this.value );
  5880. this.node.build( builder );
  5881. builder.setContext( previousContext );
  5882. }
  5883. generate( builder, output ) {
  5884. const previousContext = builder.addContext( this.value );
  5885. const snippet = this.node.build( builder, output );
  5886. builder.setContext( previousContext );
  5887. return snippet;
  5888. }
  5889. }
  5890. /**
  5891. * TSL function for creating a context node.
  5892. *
  5893. * @tsl
  5894. * @function
  5895. * @param {Node|Object} [nodeOrValue={}] - The node whose context should be modified or the modified context data.
  5896. * @param {Object} [value={}] - The modified context data.
  5897. * @returns {ContextNode}
  5898. */
  5899. const context = ( nodeOrValue = null, value = {} ) => {
  5900. let node = nodeOrValue;
  5901. if ( node === null || node.isNode !== true ) {
  5902. value = node || value;
  5903. node = null;
  5904. }
  5905. return new ContextNode( node, value );
  5906. };
  5907. /**
  5908. * TSL function for defining a uniformFlow context value for a given node.
  5909. *
  5910. * @tsl
  5911. * @function
  5912. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5913. * @returns {ContextNode}
  5914. */
  5915. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5916. /**
  5917. * TSL function for defining a name for the context value for a given node.
  5918. *
  5919. * @tsl
  5920. * @function
  5921. * @param {Node} node - The node whose context should be modified.
  5922. * @param {string} name - The name to set.
  5923. * @returns {ContextNode}
  5924. */
  5925. const setName = ( node, name ) => context( node, { nodeName: name } );
  5926. /**
  5927. * TSL function for defining a built-in shadow context for a given node.
  5928. *
  5929. * @tsl
  5930. * @function
  5931. * @param {ShadowNode} shadowNode - The shadow node representing the light's shadow.
  5932. * @param {Light} light - The light associated with the shadow.
  5933. * @param {Node} [node=null] - The node whose context should be modified.
  5934. * @returns {ContextNode}
  5935. */
  5936. function builtinShadowContext( shadowNode, light, node = null ) {
  5937. return context( node, {
  5938. getShadow: ( { light: shadowLight, shadowColorNode } ) => {
  5939. if ( light === shadowLight ) {
  5940. return shadowColorNode.mul( shadowNode );
  5941. }
  5942. return shadowColorNode;
  5943. }
  5944. } );
  5945. }
  5946. /**
  5947. * TSL function for defining a built-in ambient occlusion context for a given node.
  5948. *
  5949. * @tsl
  5950. * @function
  5951. * @param {Node} aoNode - The ambient occlusion value node to apply.
  5952. * @param {Node} [node=null] - The node whose context should be modified.
  5953. * @returns {ContextNode}
  5954. */
  5955. function builtinAOContext( aoNode, node = null ) {
  5956. return context( node, {
  5957. getAO: ( inputNode, { material } ) => {
  5958. if ( material.transparent === true ) return inputNode;
  5959. return inputNode !== null ? inputNode.mul( aoNode ) : aoNode;
  5960. }
  5961. } );
  5962. }
  5963. /**
  5964. * TSL function for defining a label context value for a given node.
  5965. *
  5966. * @tsl
  5967. * @function
  5968. * @deprecated
  5969. * @param {Node} node - The node whose context should be modified.
  5970. * @param {string} name - The name/label to set.
  5971. * @returns {ContextNode}
  5972. */
  5973. function label( node, name ) {
  5974. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5975. return setName( node, name );
  5976. }
  5977. addMethodChaining( 'context', context );
  5978. addMethodChaining( 'label', label );
  5979. addMethodChaining( 'uniformFlow', uniformFlow );
  5980. addMethodChaining( 'setName', setName );
  5981. addMethodChaining( 'builtinShadowContext', ( node, shadowNode, light ) => builtinShadowContext( shadowNode, light, node ) );
  5982. addMethodChaining( 'builtinAOContext', ( node, aoValue ) => builtinAOContext( aoValue, node ) );
  5983. /**
  5984. * Class for representing shader variables as nodes. Variables are created from
  5985. * existing nodes like the following:
  5986. *
  5987. * ```js
  5988. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5989. * ```
  5990. *
  5991. * @augments Node
  5992. */
  5993. class VarNode extends Node {
  5994. static get type() {
  5995. return 'VarNode';
  5996. }
  5997. /**
  5998. * Constructs a new variable node.
  5999. *
  6000. * @param {Node} node - The node for which a variable should be created.
  6001. * @param {?string} [name=null] - The name of the variable in the shader.
  6002. * @param {boolean} [readOnly=false] - The read-only flag.
  6003. */
  6004. constructor( node, name = null, readOnly = false ) {
  6005. super();
  6006. /**
  6007. * The node for which a variable should be created.
  6008. *
  6009. * @type {Node}
  6010. */
  6011. this.node = node;
  6012. /**
  6013. * The name of the variable in the shader. If no name is defined,
  6014. * the node system auto-generates one.
  6015. *
  6016. * @type {?string}
  6017. * @default null
  6018. */
  6019. this.name = name;
  6020. /**
  6021. * `VarNode` sets this property to `true` by default.
  6022. *
  6023. * @type {boolean}
  6024. * @default true
  6025. */
  6026. this.global = true;
  6027. /**
  6028. * This flag can be used for type testing.
  6029. *
  6030. * @type {boolean}
  6031. * @readonly
  6032. * @default true
  6033. */
  6034. this.isVarNode = true;
  6035. /**
  6036. *
  6037. * The read-only flag.
  6038. *
  6039. * @type {boolean}
  6040. * @default false
  6041. */
  6042. this.readOnly = readOnly;
  6043. /**
  6044. *
  6045. * Add this flag to the node system to indicate that this node require parents.
  6046. *
  6047. * @type {boolean}
  6048. * @default true
  6049. */
  6050. this.parents = true;
  6051. /**
  6052. * This flag is used to indicate that this node is used for intent.
  6053. *
  6054. * @type {boolean}
  6055. * @default false
  6056. */
  6057. this.intent = false;
  6058. }
  6059. /**
  6060. * Sets the intent flag for this node.
  6061. *
  6062. * This flag is used to indicate that this node is used for intent
  6063. * and should not be built directly. Instead, it is used to indicate that
  6064. * the node should be treated as a variable intent.
  6065. *
  6066. * It's useful for assigning variables without needing creating a new variable node.
  6067. *
  6068. * @param {boolean} value - The value to set for the intent flag.
  6069. * @returns {VarNode} This node.
  6070. */
  6071. setIntent( value ) {
  6072. this.intent = value;
  6073. return this;
  6074. }
  6075. /**
  6076. * Checks if this node is used for intent.
  6077. *
  6078. * @param {NodeBuilder} builder - The node builder.
  6079. * @returns {boolean} Whether this node is used for intent.
  6080. */
  6081. isIntent( builder ) {
  6082. const data = builder.getDataFromNode( this );
  6083. if ( data.forceDeclaration === true ) return false;
  6084. return this.intent;
  6085. }
  6086. /**
  6087. * Returns the intent flag of this node.
  6088. *
  6089. * @return {boolean} The intent flag.
  6090. */
  6091. getIntent() {
  6092. return this.intent;
  6093. }
  6094. getMemberType( builder, name ) {
  6095. return this.node.getMemberType( builder, name );
  6096. }
  6097. getElementType( builder ) {
  6098. return this.node.getElementType( builder );
  6099. }
  6100. generateNodeType( builder ) {
  6101. return this.node.getNodeType( builder );
  6102. }
  6103. getArrayCount( builder ) {
  6104. return this.node.getArrayCount( builder );
  6105. }
  6106. isAssign( builder ) {
  6107. const data = builder.getDataFromNode( this );
  6108. return data.assign;
  6109. }
  6110. build( ...params ) {
  6111. const builder = params[ 0 ];
  6112. if ( this._hasStack( builder ) === false && builder.buildStage === 'setup' ) {
  6113. if ( builder.context.nodeLoop || builder.context.nodeBlock ) {
  6114. let addBefore = false;
  6115. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  6116. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  6117. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  6118. if ( shaderNodeData.hasLoop ) {
  6119. const data = builder.getDataFromNode( this );
  6120. data.forceDeclaration = true;
  6121. addBefore = true;
  6122. }
  6123. }
  6124. }
  6125. const baseStack = builder.getBaseStack();
  6126. if ( addBefore ) {
  6127. baseStack.addToStackBefore( this );
  6128. } else {
  6129. baseStack.addToStack( this );
  6130. }
  6131. }
  6132. }
  6133. if ( this.isIntent( builder ) ) {
  6134. if ( this.isAssign( builder ) !== true ) {
  6135. return this.node.build( ...params );
  6136. }
  6137. }
  6138. return super.build( ...params );
  6139. }
  6140. generate( builder ) {
  6141. const { node, name, readOnly } = this;
  6142. const { renderer } = builder;
  6143. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  6144. let isDeterministic = false;
  6145. let shouldTreatAsReadOnly = false;
  6146. if ( readOnly ) {
  6147. isDeterministic = builder.isDeterministic( node );
  6148. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  6149. }
  6150. const nodeType = this.getNodeType( builder );
  6151. if ( nodeType == 'void' ) {
  6152. if ( this.isIntent( builder ) !== true ) {
  6153. error( 'TSL: ".toVar()" can not be used with void type.', this.stackTrace );
  6154. }
  6155. const snippet = node.build( builder );
  6156. return snippet;
  6157. }
  6158. const vectorType = builder.getVectorType( nodeType );
  6159. const snippet = node.build( builder, vectorType );
  6160. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  6161. const propertyName = builder.getPropertyName( nodeVar );
  6162. let declarationPrefix = propertyName;
  6163. if ( shouldTreatAsReadOnly ) {
  6164. if ( isWebGPUBackend ) {
  6165. declarationPrefix = isDeterministic
  6166. ? `const ${ propertyName }`
  6167. : `let ${ propertyName }`;
  6168. } else {
  6169. const count = node.getArrayCount( builder );
  6170. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  6171. }
  6172. }
  6173. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  6174. return propertyName;
  6175. }
  6176. _hasStack( builder ) {
  6177. const nodeData = builder.getDataFromNode( this );
  6178. return nodeData.stack !== undefined;
  6179. }
  6180. }
  6181. /**
  6182. * TSL function for creating a var node.
  6183. *
  6184. * @tsl
  6185. * @function
  6186. * @param {Node} node - The node for which a variable should be created.
  6187. * @param {?string} name - The name of the variable in the shader.
  6188. * @returns {VarNode}
  6189. */
  6190. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  6191. /**
  6192. * TSL function for creating a var node.
  6193. *
  6194. * @tsl
  6195. * @function
  6196. * @param {Node} node - The node for which a variable should be created.
  6197. * @param {?string} name - The name of the variable in the shader.
  6198. * @returns {VarNode}
  6199. */
  6200. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  6201. /**
  6202. * TSL function for creating a const node.
  6203. *
  6204. * @tsl
  6205. * @function
  6206. * @param {Node} node - The node for which a constant should be created.
  6207. * @param {?string} name - The name of the constant in the shader.
  6208. * @returns {VarNode}
  6209. */
  6210. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  6211. //
  6212. //
  6213. /**
  6214. * TSL function for creating a var intent node.
  6215. *
  6216. * @tsl
  6217. * @function
  6218. * @param {Node} node - The node for which a variable should be created.
  6219. * @param {?string} name - The name of the variable in the shader.
  6220. * @returns {VarNode}
  6221. */
  6222. const VarIntent = ( node ) => {
  6223. return createVar( node ).setIntent( true ).toStack();
  6224. };
  6225. // Method chaining
  6226. addMethodChaining( 'toVar', Var );
  6227. addMethodChaining( 'toConst', Const );
  6228. addMethodChaining( 'toVarIntent', VarIntent );
  6229. /**
  6230. * This node is used to build a sub-build in the node system.
  6231. *
  6232. * @augments Node
  6233. * @param {Node} node - The node to be built in the sub-build.
  6234. * @param {string} name - The name of the sub-build.
  6235. * @param {?string} [nodeType=null] - The type of the node, if known.
  6236. */
  6237. class SubBuildNode extends Node {
  6238. static get type() {
  6239. return 'SubBuild';
  6240. }
  6241. constructor( node, name, nodeType = null ) {
  6242. super( nodeType );
  6243. /**
  6244. * The node to be built in the sub-build.
  6245. *
  6246. * @type {Node}
  6247. */
  6248. this.node = node;
  6249. /**
  6250. * The name of the sub-build.
  6251. *
  6252. * @type {string}
  6253. */
  6254. this.name = name;
  6255. /**
  6256. * This flag can be used for type testing.
  6257. *
  6258. * @type {boolean}
  6259. * @readonly
  6260. * @default true
  6261. */
  6262. this.isSubBuildNode = true;
  6263. }
  6264. generateNodeType( builder ) {
  6265. if ( this.nodeType !== null ) return this.nodeType;
  6266. builder.addSubBuild( this.name );
  6267. const nodeType = this.node.getNodeType( builder );
  6268. builder.removeSubBuild();
  6269. return nodeType;
  6270. }
  6271. build( builder, ...params ) {
  6272. builder.addSubBuild( this.name );
  6273. const data = this.node.build( builder, ...params );
  6274. builder.removeSubBuild();
  6275. return data;
  6276. }
  6277. }
  6278. /**
  6279. * Creates a new sub-build node.
  6280. *
  6281. * @tsl
  6282. * @function
  6283. * @param {Node} node - The node to be built in the sub-build.
  6284. * @param {string} name - The name of the sub-build.
  6285. * @param {?string} [type=null] - The type of the node, if known.
  6286. * @returns {Node} A node object wrapping the SubBuildNode instance.
  6287. */
  6288. const subBuild = ( node, name, type = null ) => new SubBuildNode( nodeObject( node ), name, type );
  6289. /**
  6290. * Class for representing shader varyings as nodes. Varyings are create from
  6291. * existing nodes like the following:
  6292. *
  6293. * ```js
  6294. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  6295. * ```
  6296. *
  6297. * @augments Node
  6298. */
  6299. class VaryingNode extends Node {
  6300. static get type() {
  6301. return 'VaryingNode';
  6302. }
  6303. /**
  6304. * Constructs a new varying node.
  6305. *
  6306. * @param {Node} node - The node for which a varying should be created.
  6307. * @param {?string} name - The name of the varying in the shader.
  6308. */
  6309. constructor( node, name = null ) {
  6310. super();
  6311. /**
  6312. * The node for which a varying should be created.
  6313. *
  6314. * @type {Node}
  6315. */
  6316. this.node = subBuild( node, 'VERTEX' );
  6317. /**
  6318. * The name of the varying in the shader. If no name is defined,
  6319. * the node system auto-generates one.
  6320. *
  6321. * @type {?string}
  6322. * @default null
  6323. */
  6324. this.name = name;
  6325. /**
  6326. * This flag can be used for type testing.
  6327. *
  6328. * @type {boolean}
  6329. * @readonly
  6330. * @default true
  6331. */
  6332. this.isVaryingNode = true;
  6333. /**
  6334. * The interpolation type of the varying data.
  6335. *
  6336. * @type {?string}
  6337. * @default null
  6338. */
  6339. this.interpolationType = null;
  6340. /**
  6341. * The interpolation sampling type of varying data.
  6342. *
  6343. * @type {?string}
  6344. * @default null
  6345. */
  6346. this.interpolationSampling = null;
  6347. /**
  6348. * This flag is used for global cache.
  6349. *
  6350. * @type {boolean}
  6351. * @default true
  6352. */
  6353. this.global = true;
  6354. }
  6355. /**
  6356. * Defines the interpolation type of the varying.
  6357. *
  6358. * @param {string} type - The interpolation type.
  6359. * @param {?string} sampling - The interpolation sampling type
  6360. * @return {VaryingNode} A reference to this node.
  6361. */
  6362. setInterpolation( type, sampling = null ) {
  6363. this.interpolationType = type;
  6364. this.interpolationSampling = sampling;
  6365. return this;
  6366. }
  6367. getHash( builder ) {
  6368. return this.name || super.getHash( builder );
  6369. }
  6370. generateNodeType( builder ) {
  6371. // VaryingNode is auto type
  6372. return this.node.getNodeType( builder );
  6373. }
  6374. /**
  6375. * This method performs the setup of a varying node with the current node builder.
  6376. *
  6377. * @param {NodeBuilder} builder - The current node builder.
  6378. * @return {NodeVarying} The node varying from the node builder.
  6379. */
  6380. setupVarying( builder ) {
  6381. const properties = builder.getNodeProperties( this );
  6382. let varying = properties.varying;
  6383. if ( varying === undefined ) {
  6384. const name = this.name;
  6385. const type = this.getNodeType( builder );
  6386. const interpolationType = this.interpolationType;
  6387. const interpolationSampling = this.interpolationSampling;
  6388. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  6389. properties.node = subBuild( this.node, 'VERTEX' );
  6390. }
  6391. // this property can be used to check if the varying can be optimized for a variable
  6392. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  6393. return varying;
  6394. }
  6395. setup( builder ) {
  6396. this.setupVarying( builder );
  6397. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6398. }
  6399. analyze( builder ) {
  6400. this.setupVarying( builder );
  6401. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6402. }
  6403. generate( builder ) {
  6404. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  6405. const properties = builder.getNodeProperties( this );
  6406. const varying = this.setupVarying( builder );
  6407. if ( properties[ propertyKey ] === undefined ) {
  6408. const type = this.getNodeType( builder );
  6409. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  6410. // force node run in vertex stage
  6411. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  6412. properties[ propertyKey ] = propertyName;
  6413. }
  6414. return builder.getPropertyName( varying );
  6415. }
  6416. }
  6417. /**
  6418. * TSL function for creating a varying node.
  6419. *
  6420. * @tsl
  6421. * @function
  6422. * @param {Node} node - The node for which a varying should be created.
  6423. * @param {?string} name - The name of the varying in the shader.
  6424. * @returns {VaryingNode}
  6425. */
  6426. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6427. /**
  6428. * Computes a node in the vertex stage.
  6429. *
  6430. * @tsl
  6431. * @function
  6432. * @param {Node} node - The node which should be executed in the vertex stage.
  6433. * @returns {VaryingNode}
  6434. */
  6435. const vertexStage = ( node ) => varying( node );
  6436. addMethodChaining( 'toVarying', varying );
  6437. addMethodChaining( 'toVertexStage', vertexStage );
  6438. /**
  6439. * Converts the given color value from sRGB to linear-sRGB color space.
  6440. *
  6441. * @tsl
  6442. * @function
  6443. * @param {Node<vec3>} color - The sRGB color.
  6444. * @return {Node<vec3>} The linear-sRGB color.
  6445. */
  6446. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6447. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6448. const b = color.mul( 0.0773993808 );
  6449. const factor = color.lessThanEqual( 0.04045 );
  6450. const rgbResult = mix( a, b, factor );
  6451. return rgbResult;
  6452. } ).setLayout( {
  6453. name: 'sRGBTransferEOTF',
  6454. type: 'vec3',
  6455. inputs: [
  6456. { name: 'color', type: 'vec3' }
  6457. ]
  6458. } );
  6459. /**
  6460. * Converts the given color value from linear-sRGB to sRGB color space.
  6461. *
  6462. * @tsl
  6463. * @function
  6464. * @param {Node<vec3>} color - The linear-sRGB color.
  6465. * @return {Node<vec3>} The sRGB color.
  6466. */
  6467. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6468. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6469. const b = color.mul( 12.92 );
  6470. const factor = color.lessThanEqual( 0.0031308 );
  6471. const rgbResult = mix( a, b, factor );
  6472. return rgbResult;
  6473. } ).setLayout( {
  6474. name: 'sRGBTransferOETF',
  6475. type: 'vec3',
  6476. inputs: [
  6477. { name: 'color', type: 'vec3' }
  6478. ]
  6479. } );
  6480. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6481. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6482. /**
  6483. * This node represents a color space conversion. Meaning it converts
  6484. * a color value from a source to a target color space.
  6485. *
  6486. * @augments TempNode
  6487. */
  6488. class ColorSpaceNode extends TempNode {
  6489. static get type() {
  6490. return 'ColorSpaceNode';
  6491. }
  6492. /**
  6493. * Constructs a new color space node.
  6494. *
  6495. * @param {Node} colorNode - Represents the color to convert.
  6496. * @param {string} source - The source color space.
  6497. * @param {string} target - The target color space.
  6498. */
  6499. constructor( colorNode, source, target ) {
  6500. super( 'vec4' );
  6501. /**
  6502. * Represents the color to convert.
  6503. *
  6504. * @type {Node}
  6505. */
  6506. this.colorNode = colorNode;
  6507. /**
  6508. * The source color space.
  6509. *
  6510. * @type {string}
  6511. */
  6512. this.source = source;
  6513. /**
  6514. * The target color space.
  6515. *
  6516. * @type {string}
  6517. */
  6518. this.target = target;
  6519. }
  6520. /**
  6521. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6522. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6523. * color management and renderer.
  6524. *
  6525. * @param {NodeBuilder} builder - The current node builder.
  6526. * @param {string} colorSpace - The color space to resolve.
  6527. * @return {string} The resolved color space.
  6528. */
  6529. resolveColorSpace( builder, colorSpace ) {
  6530. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6531. return ColorManagement.workingColorSpace;
  6532. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6533. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6534. }
  6535. return colorSpace;
  6536. }
  6537. setup( builder ) {
  6538. const { colorNode } = this;
  6539. const source = this.resolveColorSpace( builder, this.source );
  6540. const target = this.resolveColorSpace( builder, this.target );
  6541. let outputNode = colorNode;
  6542. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6543. return outputNode;
  6544. }
  6545. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6546. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6547. }
  6548. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6549. outputNode = vec4(
  6550. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6551. outputNode.a
  6552. );
  6553. }
  6554. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6555. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6556. }
  6557. return outputNode;
  6558. }
  6559. }
  6560. /**
  6561. * TSL function for converting a given color node from the current working color space to the given color space.
  6562. *
  6563. * @tsl
  6564. * @function
  6565. * @param {Node} node - Represents the node to convert.
  6566. * @param {string} targetColorSpace - The target color space.
  6567. * @returns {ColorSpaceNode}
  6568. */
  6569. const workingToColorSpace = ( node, targetColorSpace ) => new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace );
  6570. /**
  6571. * TSL function for converting a given color node from the given color space to the current working color space.
  6572. *
  6573. * @tsl
  6574. * @function
  6575. * @param {Node} node - Represents the node to convert.
  6576. * @param {string} sourceColorSpace - The source color space.
  6577. * @returns {ColorSpaceNode}
  6578. */
  6579. const colorSpaceToWorking = ( node, sourceColorSpace ) => new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE );
  6580. /**
  6581. * TSL function for converting a given color node from one color space to another one.
  6582. *
  6583. * @tsl
  6584. * @function
  6585. * @param {Node} node - Represents the node to convert.
  6586. * @param {string} sourceColorSpace - The source color space.
  6587. * @param {string} targetColorSpace - The target color space.
  6588. * @returns {ColorSpaceNode}
  6589. */
  6590. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace );
  6591. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6592. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6593. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  6594. /**
  6595. * This class is only relevant if the referenced property is array-like.
  6596. * In this case, `ReferenceElementNode` allows to refer to a specific
  6597. * element inside the data structure via an index.
  6598. *
  6599. * @augments ArrayElementNode
  6600. */
  6601. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6602. static get type() {
  6603. return 'ReferenceElementNode';
  6604. }
  6605. /**
  6606. * Constructs a new reference element node.
  6607. *
  6608. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6609. * @param {Node} indexNode - The index node that defines the element access.
  6610. */
  6611. constructor( referenceNode, indexNode ) {
  6612. super( referenceNode, indexNode );
  6613. /**
  6614. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6615. * property references to the current node.
  6616. *
  6617. * @type {?ReferenceBaseNode}
  6618. * @default null
  6619. */
  6620. this.referenceNode = referenceNode;
  6621. /**
  6622. * This flag can be used for type testing.
  6623. *
  6624. * @type {boolean}
  6625. * @readonly
  6626. * @default true
  6627. */
  6628. this.isReferenceElementNode = true;
  6629. }
  6630. /**
  6631. * This method is overwritten since the node type is inferred from
  6632. * the uniform type of the reference node.
  6633. *
  6634. * @return {string} The node type.
  6635. */
  6636. generateNodeType() {
  6637. return this.referenceNode.uniformType;
  6638. }
  6639. generate( builder ) {
  6640. const snippet = super.generate( builder );
  6641. const arrayType = this.referenceNode.getNodeType();
  6642. const elementType = this.getNodeType();
  6643. return builder.format( snippet, arrayType, elementType );
  6644. }
  6645. };
  6646. /**
  6647. * Base class for nodes which establishes a reference to a property of another object.
  6648. * In this way, the value of the node is automatically linked to the value of
  6649. * referenced object. Reference nodes internally represent the linked value
  6650. * as a uniform.
  6651. *
  6652. * @augments Node
  6653. */
  6654. class ReferenceBaseNode extends Node {
  6655. static get type() {
  6656. return 'ReferenceBaseNode';
  6657. }
  6658. /**
  6659. * Constructs a new reference base node.
  6660. *
  6661. * @param {string} property - The name of the property the node refers to.
  6662. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6663. * @param {?Object} [object=null] - The object the property belongs to.
  6664. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6665. */
  6666. constructor( property, uniformType, object = null, count = null ) {
  6667. super();
  6668. /**
  6669. * The name of the property the node refers to.
  6670. *
  6671. * @type {string}
  6672. */
  6673. this.property = property;
  6674. /**
  6675. * The uniform type that should be used to represent the property value.
  6676. *
  6677. * @type {string}
  6678. */
  6679. this.uniformType = uniformType;
  6680. /**
  6681. * The object the property belongs to.
  6682. *
  6683. * @type {?Object}
  6684. * @default null
  6685. */
  6686. this.object = object;
  6687. /**
  6688. * When the linked property is an array, this parameter defines its length.
  6689. *
  6690. * @type {?number}
  6691. * @default null
  6692. */
  6693. this.count = count;
  6694. /**
  6695. * The property name might have dots so nested properties can be referred.
  6696. * The hierarchy of the names is stored inside this array.
  6697. *
  6698. * @type {Array<string>}
  6699. */
  6700. this.properties = property.split( '.' );
  6701. /**
  6702. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6703. * since the final reference might be updated from calling code.
  6704. *
  6705. * @type {?Object}
  6706. * @default null
  6707. */
  6708. this.reference = object;
  6709. /**
  6710. * The uniform node that holds the value of the reference node.
  6711. *
  6712. * @type {UniformNode}
  6713. * @default null
  6714. */
  6715. this.node = null;
  6716. /**
  6717. * The uniform group of the internal uniform.
  6718. *
  6719. * @type {UniformGroupNode}
  6720. * @default null
  6721. */
  6722. this.group = null;
  6723. /**
  6724. * Overwritten since reference nodes are updated per object.
  6725. *
  6726. * @type {string}
  6727. * @default 'object'
  6728. */
  6729. this.updateType = NodeUpdateType.OBJECT;
  6730. }
  6731. /**
  6732. * Sets the uniform group for this reference node.
  6733. *
  6734. * @param {UniformGroupNode} group - The uniform group to set.
  6735. * @return {ReferenceBaseNode} A reference to this node.
  6736. */
  6737. setGroup( group ) {
  6738. this.group = group;
  6739. return this;
  6740. }
  6741. /**
  6742. * When the referred property is array-like, this method can be used
  6743. * to access elements via an index node.
  6744. *
  6745. * @param {IndexNode} indexNode - indexNode.
  6746. * @return {ReferenceElementNode} A reference to an element.
  6747. */
  6748. element( indexNode ) {
  6749. return new ReferenceElementNode$1( this, nodeObject( indexNode ) );
  6750. }
  6751. /**
  6752. * Sets the node type which automatically defines the internal
  6753. * uniform type.
  6754. *
  6755. * @param {string} uniformType - The type to set.
  6756. */
  6757. setNodeType( uniformType ) {
  6758. const node = uniform( null, uniformType );
  6759. if ( this.group !== null ) {
  6760. node.setGroup( this.group );
  6761. }
  6762. this.node = node;
  6763. }
  6764. /**
  6765. * This method is overwritten since the node type is inferred from
  6766. * the type of the reference node.
  6767. *
  6768. * @param {NodeBuilder} builder - The current node builder.
  6769. * @return {string} The node type.
  6770. */
  6771. generateNodeType( builder ) {
  6772. if ( this.node === null ) {
  6773. this.updateReference( builder );
  6774. this.updateValue();
  6775. }
  6776. return this.node.getNodeType( builder );
  6777. }
  6778. /**
  6779. * Returns the property value from the given referred object.
  6780. *
  6781. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6782. * @return {any} The value.
  6783. */
  6784. getValueFromReference( object = this.reference ) {
  6785. const { properties } = this;
  6786. let value = object[ properties[ 0 ] ];
  6787. for ( let i = 1; i < properties.length; i ++ ) {
  6788. value = value[ properties[ i ] ];
  6789. }
  6790. return value;
  6791. }
  6792. /**
  6793. * Allows to update the reference based on the given state. The state is only
  6794. * evaluated {@link ReferenceBaseNode#object} is not set.
  6795. *
  6796. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6797. * @return {Object} The updated reference.
  6798. */
  6799. updateReference( state ) {
  6800. this.reference = this.object !== null ? this.object : state.object;
  6801. return this.reference;
  6802. }
  6803. /**
  6804. * The output of the reference node is the internal uniform node.
  6805. *
  6806. * @return {UniformNode} The output node.
  6807. */
  6808. setup() {
  6809. this.updateValue();
  6810. return this.node;
  6811. }
  6812. /**
  6813. * Overwritten to update the internal uniform value.
  6814. *
  6815. * @param {NodeFrame} frame - A reference to the current node frame.
  6816. */
  6817. update( /*frame*/ ) {
  6818. this.updateValue();
  6819. }
  6820. /**
  6821. * Retrieves the value from the referred object property and uses it
  6822. * to updated the internal uniform.
  6823. */
  6824. updateValue() {
  6825. if ( this.node === null ) this.setNodeType( this.uniformType );
  6826. const value = this.getValueFromReference();
  6827. if ( Array.isArray( value ) ) {
  6828. this.node.array = value;
  6829. } else {
  6830. this.node.value = value;
  6831. }
  6832. }
  6833. }
  6834. /**
  6835. * TSL function for creating a reference base node.
  6836. *
  6837. * @tsl
  6838. * @function
  6839. * @param {string} name - The name of the property the node refers to.
  6840. * @param {string} type - The uniform type that should be used to represent the property value.
  6841. * @param {Object} object - The object the property belongs to.
  6842. * @returns {ReferenceBaseNode}
  6843. */
  6844. const reference$1 = ( name, type, object ) => new ReferenceBaseNode( name, type, object );
  6845. /**
  6846. * This node is a special type of reference node which is intended
  6847. * for linking renderer properties with node values.
  6848. * ```js
  6849. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6850. * ```
  6851. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6852. * automatically be updated.
  6853. *
  6854. * @augments ReferenceBaseNode
  6855. */
  6856. class RendererReferenceNode extends ReferenceBaseNode {
  6857. static get type() {
  6858. return 'RendererReferenceNode';
  6859. }
  6860. /**
  6861. * Constructs a new renderer reference node.
  6862. *
  6863. * @param {string} property - The name of the property the node refers to.
  6864. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6865. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6866. * the node refers to the renderer of the current state.
  6867. */
  6868. constructor( property, inputType, renderer = null ) {
  6869. super( property, inputType, renderer );
  6870. /**
  6871. * The renderer the property belongs to. When no renderer is set,
  6872. * the node refers to the renderer of the current state.
  6873. *
  6874. * @type {?Renderer}
  6875. * @default null
  6876. */
  6877. this.renderer = renderer;
  6878. this.setGroup( renderGroup );
  6879. }
  6880. /**
  6881. * Updates the reference based on the given state. The state is only evaluated
  6882. * {@link RendererReferenceNode#renderer} is not set.
  6883. *
  6884. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6885. * @return {Object} The updated reference.
  6886. */
  6887. updateReference( state ) {
  6888. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6889. return this.reference;
  6890. }
  6891. }
  6892. /**
  6893. * TSL function for creating a renderer reference node.
  6894. *
  6895. * @tsl
  6896. * @function
  6897. * @param {string} name - The name of the property the node refers to.
  6898. * @param {string} type - The uniform type that should be used to represent the property value.
  6899. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6900. * the node refers to the renderer of the current state.
  6901. * @returns {RendererReferenceNode}
  6902. */
  6903. const rendererReference = ( name, type, renderer = null ) => new RendererReferenceNode( name, type, renderer );
  6904. /**
  6905. * This node represents a tone mapping operation.
  6906. *
  6907. * @augments TempNode
  6908. */
  6909. class ToneMappingNode extends TempNode {
  6910. static get type() {
  6911. return 'ToneMappingNode';
  6912. }
  6913. /**
  6914. * Constructs a new tone mapping node.
  6915. *
  6916. * @param {number} toneMapping - The tone mapping type.
  6917. * @param {Node} exposureNode - The tone mapping exposure.
  6918. * @param {Node} [colorNode=null] - The color node to process.
  6919. */
  6920. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6921. super( 'vec3' );
  6922. /**
  6923. * The tone mapping type.
  6924. *
  6925. * @private
  6926. * @type {number}
  6927. */
  6928. this._toneMapping = toneMapping;
  6929. /**
  6930. * The tone mapping exposure.
  6931. *
  6932. * @type {Node}
  6933. * @default null
  6934. */
  6935. this.exposureNode = exposureNode;
  6936. /**
  6937. * Represents the color to process.
  6938. *
  6939. * @type {?Node}
  6940. * @default null
  6941. */
  6942. this.colorNode = colorNode;
  6943. }
  6944. /**
  6945. * Overwrites the default `customCacheKey()` implementation by including the tone
  6946. * mapping type into the cache key.
  6947. *
  6948. * @return {number} The hash.
  6949. */
  6950. customCacheKey() {
  6951. return hash$1( this._toneMapping );
  6952. }
  6953. /**
  6954. * Sets the tone mapping type.
  6955. *
  6956. * @param {number} value - The tone mapping type.
  6957. * @return {ToneMappingNode} A reference to this node.
  6958. */
  6959. setToneMapping( value ) {
  6960. this._toneMapping = value;
  6961. return this;
  6962. }
  6963. /**
  6964. * Gets the tone mapping type.
  6965. *
  6966. * @returns {number} The tone mapping type.
  6967. */
  6968. getToneMapping() {
  6969. return this._toneMapping;
  6970. }
  6971. setup( builder ) {
  6972. const colorNode = this.colorNode || builder.context.color;
  6973. const toneMapping = this._toneMapping;
  6974. if ( toneMapping === NoToneMapping ) return colorNode;
  6975. let outputNode = null;
  6976. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6977. if ( toneMappingFn !== null ) {
  6978. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6979. } else {
  6980. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6981. outputNode = colorNode;
  6982. }
  6983. return outputNode;
  6984. }
  6985. }
  6986. /**
  6987. * TSL function for creating a tone mapping node.
  6988. *
  6989. * @tsl
  6990. * @function
  6991. * @param {number} mapping - The tone mapping type.
  6992. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6993. * @param {Node<vec3> | Color} color - The color node to process.
  6994. * @returns {ToneMappingNode<vec3>}
  6995. */
  6996. const toneMapping = ( mapping, exposure, color ) => new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) );
  6997. /**
  6998. * TSL object that represents the global tone mapping exposure of the renderer.
  6999. *
  7000. * @tsl
  7001. * @type {RendererReferenceNode<vec3>}
  7002. */
  7003. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  7004. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  7005. /**
  7006. * Internal buffer attribute library.
  7007. *
  7008. * @private
  7009. * @type {WeakMap<TypedArray, InterleavedBuffer>}
  7010. */
  7011. const _bufferLib = new WeakMap();
  7012. /**
  7013. * Internal method for retrieving or creating interleaved buffers.
  7014. *
  7015. * @private
  7016. * @param {TypedArray} value - The attribute data.
  7017. * @param {number} itemSize - The attribute item size.
  7018. * @returns {InterleavedBuffer} The interleaved buffer.
  7019. */
  7020. function _getBufferAttribute( value, itemSize ) {
  7021. let buffer = _bufferLib.get( value );
  7022. if ( buffer === undefined ) {
  7023. buffer = new InterleavedBuffer( value, itemSize );
  7024. _bufferLib.set( value, buffer );
  7025. }
  7026. return buffer;
  7027. }
  7028. /**
  7029. * In earlier `three.js` versions it was only possible to define attribute data
  7030. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  7031. * on the node level.
  7032. * ```js
  7033. * const geometry = new THREE.PlaneGeometry();
  7034. * const positionAttribute = geometry.getAttribute( 'position' );
  7035. *
  7036. * const colors = [];
  7037. * for ( let i = 0; i < position.count; i ++ ) {
  7038. * colors.push( 1, 0, 0 );
  7039. * }
  7040. *
  7041. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  7042. * ```
  7043. * This new approach is especially interesting when geometry data are generated via
  7044. * compute shaders. The below line converts a storage buffer into an attribute node.
  7045. * ```js
  7046. * material.positionNode = positionBuffer.toAttribute();
  7047. * ```
  7048. * @augments InputNode
  7049. */
  7050. class BufferAttributeNode extends InputNode {
  7051. static get type() {
  7052. return 'BufferAttributeNode';
  7053. }
  7054. /**
  7055. * Constructs a new buffer attribute node.
  7056. *
  7057. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  7058. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  7059. * @param {number} [bufferStride=0] - The buffer stride.
  7060. * @param {number} [bufferOffset=0] - The buffer offset.
  7061. */
  7062. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  7063. super( value, bufferType );
  7064. /**
  7065. * This flag can be used for type testing.
  7066. *
  7067. * @type {boolean}
  7068. * @readonly
  7069. * @default true
  7070. */
  7071. this.isBufferNode = true;
  7072. /**
  7073. * The buffer type (e.g. `'vec3'`).
  7074. *
  7075. * @type {?string}
  7076. * @default null
  7077. */
  7078. this.bufferType = bufferType;
  7079. /**
  7080. * The buffer stride.
  7081. *
  7082. * @type {number}
  7083. * @default 0
  7084. */
  7085. this.bufferStride = bufferStride;
  7086. /**
  7087. * The buffer offset.
  7088. *
  7089. * @type {number}
  7090. * @default 0
  7091. */
  7092. this.bufferOffset = bufferOffset;
  7093. /**
  7094. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  7095. * if you are planning to update the attribute data per frame.
  7096. *
  7097. * @type {number}
  7098. * @default StaticDrawUsage
  7099. */
  7100. this.usage = StaticDrawUsage;
  7101. /**
  7102. * Whether the attribute is instanced or not.
  7103. *
  7104. * @type {boolean}
  7105. * @default false
  7106. */
  7107. this.instanced = false;
  7108. /**
  7109. * A reference to the buffer attribute.
  7110. *
  7111. * @type {?BufferAttribute}
  7112. * @default null
  7113. */
  7114. this.attribute = null;
  7115. /**
  7116. * `BufferAttributeNode` sets this property to `true` by default.
  7117. *
  7118. * @type {boolean}
  7119. * @default true
  7120. */
  7121. this.global = true;
  7122. if ( value && value.isBufferAttribute === true && value.itemSize <= 4 ) {
  7123. this.attribute = value;
  7124. this.usage = value.usage;
  7125. this.instanced = value.isInstancedBufferAttribute;
  7126. }
  7127. }
  7128. /**
  7129. * This method is overwritten since the attribute data might be shared
  7130. * and thus the hash should be shared as well.
  7131. *
  7132. * @param {NodeBuilder} builder - The current node builder.
  7133. * @return {string} The hash.
  7134. */
  7135. getHash( builder ) {
  7136. let id;
  7137. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  7138. let bufferData = builder.globalCache.getData( this.value );
  7139. if ( bufferData === undefined ) {
  7140. bufferData = {
  7141. node: this
  7142. };
  7143. builder.globalCache.setData( this.value, bufferData );
  7144. }
  7145. id = bufferData.node.id;
  7146. } else {
  7147. id = this.id;
  7148. }
  7149. return String( id );
  7150. }
  7151. /**
  7152. * This method is overwritten since the node type is inferred from
  7153. * the buffer attribute.
  7154. *
  7155. * @param {NodeBuilder} builder - The current node builder.
  7156. * @return {string} The node type.
  7157. */
  7158. generateNodeType( builder ) {
  7159. if ( this.bufferType === null ) {
  7160. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  7161. }
  7162. return this.bufferType;
  7163. }
  7164. /**
  7165. * Depending on which value was passed to the node, `setup()` behaves
  7166. * differently. If no instance of `BufferAttribute` was passed, the method
  7167. * creates an internal attribute and configures it respectively.
  7168. *
  7169. * @param {NodeBuilder} builder - The current node builder.
  7170. */
  7171. setup( builder ) {
  7172. if ( this.attribute !== null ) return;
  7173. //
  7174. const type = this.getNodeType( builder );
  7175. const itemSize = builder.getTypeLength( type );
  7176. const value = this.value;
  7177. const stride = this.bufferStride || itemSize;
  7178. const offset = this.bufferOffset;
  7179. let buffer;
  7180. if ( value.isInterleavedBuffer === true ) {
  7181. buffer = value;
  7182. } else if ( value.isBufferAttribute === true ) {
  7183. buffer = _getBufferAttribute( value.array, stride );
  7184. } else {
  7185. buffer = _getBufferAttribute( value, stride );
  7186. }
  7187. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  7188. buffer.setUsage( this.usage );
  7189. this.attribute = bufferAttribute;
  7190. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  7191. }
  7192. /**
  7193. * Generates the code snippet of the buffer attribute node.
  7194. *
  7195. * @param {NodeBuilder} builder - The current node builder.
  7196. * @return {string} The generated code snippet.
  7197. */
  7198. generate( builder ) {
  7199. const nodeType = this.getNodeType( builder );
  7200. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  7201. const propertyName = builder.getPropertyName( nodeAttribute );
  7202. let output = null;
  7203. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  7204. this.name = propertyName;
  7205. output = propertyName;
  7206. } else {
  7207. const nodeVarying = varying( this );
  7208. output = nodeVarying.build( builder, nodeType );
  7209. }
  7210. return output;
  7211. }
  7212. /**
  7213. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  7214. *
  7215. * @param {NodeBuilder} builder - The current node builder.
  7216. * @return {string} The input type.
  7217. */
  7218. getInputType( /*builder*/ ) {
  7219. return 'bufferAttribute';
  7220. }
  7221. /**
  7222. * Sets the `usage` property to the given value.
  7223. *
  7224. * @param {number} value - The usage to set.
  7225. * @return {BufferAttributeNode} A reference to this node.
  7226. */
  7227. setUsage( value ) {
  7228. this.usage = value;
  7229. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  7230. this.attribute.usage = value;
  7231. }
  7232. return this;
  7233. }
  7234. /**
  7235. * Sets the `instanced` property to the given value.
  7236. *
  7237. * @param {boolean} value - The value to set.
  7238. * @return {BufferAttributeNode} A reference to this node.
  7239. */
  7240. setInstanced( value ) {
  7241. this.instanced = value;
  7242. return this;
  7243. }
  7244. }
  7245. /**
  7246. * Internal method for creating buffer attribute nodes.
  7247. *
  7248. * @private
  7249. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7250. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7251. * @param {number} [stride=0] - The buffer stride.
  7252. * @param {number} [offset=0] - The buffer offset.
  7253. * @param {number} [usage=StaticDrawUsage] - The buffer usage.
  7254. * @param {boolean} [instanced=false] - Whether the buffer is instanced.
  7255. * @returns {BufferAttributeNode|Node} The buffer attribute node.
  7256. */
  7257. function createBufferAttribute( array, type = null, stride = 0, offset = 0, usage = StaticDrawUsage, instanced = false ) {
  7258. if ( type === 'mat3' || ( type === null && array.itemSize === 9 ) ) {
  7259. return mat3(
  7260. new BufferAttributeNode( array, 'vec3', 9, 0 ).setUsage( usage ).setInstanced( instanced ),
  7261. new BufferAttributeNode( array, 'vec3', 9, 3 ).setUsage( usage ).setInstanced( instanced ),
  7262. new BufferAttributeNode( array, 'vec3', 9, 6 ).setUsage( usage ).setInstanced( instanced )
  7263. );
  7264. } else if ( type === 'mat4' || ( type === null && array.itemSize === 16 ) ) {
  7265. return mat4(
  7266. new BufferAttributeNode( array, 'vec4', 16, 0 ).setUsage( usage ).setInstanced( instanced ),
  7267. new BufferAttributeNode( array, 'vec4', 16, 4 ).setUsage( usage ).setInstanced( instanced ),
  7268. new BufferAttributeNode( array, 'vec4', 16, 8 ).setUsage( usage ).setInstanced( instanced ),
  7269. new BufferAttributeNode( array, 'vec4', 16, 12 ).setUsage( usage ).setInstanced( instanced )
  7270. );
  7271. }
  7272. return new BufferAttributeNode( array, type, stride, offset ).setUsage( usage );
  7273. }
  7274. /**
  7275. * TSL function for creating a buffer attribute node.
  7276. *
  7277. * @tsl
  7278. * @function
  7279. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7280. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7281. * @param {number} [stride=0] - The buffer stride.
  7282. * @param {number} [offset=0] - The buffer offset.
  7283. * @returns {BufferAttributeNode|Node}
  7284. */
  7285. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset );
  7286. /**
  7287. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  7288. * Use this function if attribute data are updated per frame.
  7289. *
  7290. * @tsl
  7291. * @function
  7292. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7293. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7294. * @param {number} [stride=0] - The buffer stride.
  7295. * @param {number} [offset=0] - The buffer offset.
  7296. * @returns {BufferAttributeNode|Node}
  7297. */
  7298. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage );
  7299. /**
  7300. * TSL function for creating a buffer attribute node but with enabled instancing
  7301. *
  7302. * @tsl
  7303. * @function
  7304. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7305. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7306. * @param {number} [stride=0] - The buffer stride.
  7307. * @param {number} [offset=0] - The buffer offset.
  7308. * @returns {BufferAttributeNode|Node}
  7309. */
  7310. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, StaticDrawUsage, true );
  7311. /**
  7312. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  7313. *
  7314. * @tsl
  7315. * @function
  7316. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7317. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7318. * @param {number} [stride=0] - The buffer stride.
  7319. * @param {number} [offset=0] - The buffer offset.
  7320. * @returns {BufferAttributeNode|Node}
  7321. */
  7322. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage, true );
  7323. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  7324. /**
  7325. * This class represents shader indices of different types. The following predefined node
  7326. * objects cover frequent use cases:
  7327. *
  7328. * - `vertexIndex`: The index of a vertex within a mesh.
  7329. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  7330. * - `drawIndex`: The index of a draw call.
  7331. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  7332. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  7333. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  7334. *
  7335. * @augments Node
  7336. */
  7337. class IndexNode extends Node {
  7338. static get type() {
  7339. return 'IndexNode';
  7340. }
  7341. /**
  7342. * Constructs a new index node.
  7343. *
  7344. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  7345. */
  7346. constructor( scope ) {
  7347. super( 'uint' );
  7348. /**
  7349. * The scope of the index node.
  7350. *
  7351. * @type {string}
  7352. */
  7353. this.scope = scope;
  7354. /**
  7355. * This flag can be used for type testing.
  7356. *
  7357. * @type {boolean}
  7358. * @readonly
  7359. * @default true
  7360. */
  7361. this.isIndexNode = true;
  7362. }
  7363. generate( builder ) {
  7364. const nodeType = this.getNodeType( builder );
  7365. const scope = this.scope;
  7366. let propertyName;
  7367. if ( scope === IndexNode.VERTEX ) {
  7368. propertyName = builder.getVertexIndex();
  7369. } else if ( scope === IndexNode.INSTANCE ) {
  7370. propertyName = builder.getInstanceIndex();
  7371. } else if ( scope === IndexNode.DRAW ) {
  7372. propertyName = builder.getDrawIndex();
  7373. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  7374. propertyName = builder.getInvocationLocalIndex();
  7375. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  7376. propertyName = builder.getInvocationSubgroupIndex();
  7377. } else if ( scope === IndexNode.SUBGROUP ) {
  7378. propertyName = builder.getSubgroupIndex();
  7379. } else {
  7380. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  7381. }
  7382. let output;
  7383. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  7384. output = propertyName;
  7385. } else {
  7386. const nodeVarying = varying( this );
  7387. output = nodeVarying.build( builder, nodeType );
  7388. }
  7389. return output;
  7390. }
  7391. }
  7392. IndexNode.VERTEX = 'vertex';
  7393. IndexNode.INSTANCE = 'instance';
  7394. IndexNode.SUBGROUP = 'subgroup';
  7395. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  7396. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  7397. IndexNode.DRAW = 'draw';
  7398. /**
  7399. * TSL object that represents the index of a vertex within a mesh.
  7400. *
  7401. * @tsl
  7402. * @type {IndexNode}
  7403. */
  7404. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  7405. /**
  7406. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  7407. *
  7408. * @tsl
  7409. * @type {IndexNode}
  7410. */
  7411. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  7412. /**
  7413. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  7414. *
  7415. * @tsl
  7416. * @type {IndexNode}
  7417. */
  7418. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  7419. /**
  7420. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  7421. *
  7422. * @tsl
  7423. * @type {IndexNode}
  7424. */
  7425. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  7426. /**
  7427. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  7428. *
  7429. * @tsl
  7430. * @type {IndexNode}
  7431. */
  7432. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  7433. /**
  7434. * TSL object that represents the index of a draw call.
  7435. *
  7436. * @tsl
  7437. * @type {IndexNode}
  7438. */
  7439. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  7440. /**
  7441. * Represents a compute shader node.
  7442. *
  7443. * @augments Node
  7444. */
  7445. class ComputeNode extends Node {
  7446. static get type() {
  7447. return 'ComputeNode';
  7448. }
  7449. /**
  7450. * Constructs a new compute node.
  7451. *
  7452. * @param {Node} computeNode - The node that defines the compute shader logic.
  7453. * @param {Array<number>} workgroupSize - An array defining the X, Y, and Z dimensions of the workgroup for compute shader execution.
  7454. */
  7455. constructor( computeNode, workgroupSize ) {
  7456. super( 'void' );
  7457. /**
  7458. * This flag can be used for type testing.
  7459. *
  7460. * @type {boolean}
  7461. * @readonly
  7462. * @default true
  7463. */
  7464. this.isComputeNode = true;
  7465. /**
  7466. * The node that defines the compute shader logic.
  7467. *
  7468. * @type {Node}
  7469. */
  7470. this.computeNode = computeNode;
  7471. /**
  7472. * An array defining the X, Y, and Z dimensions of the workgroup for compute shader execution.
  7473. *
  7474. * @type {Array<number>}
  7475. * @default [ 64 ]
  7476. */
  7477. this.workgroupSize = workgroupSize;
  7478. /**
  7479. * The total number of threads (invocations) to execute. If it is a number, it will be used
  7480. * to automatically generate bounds checking against `instanceIndex`.
  7481. *
  7482. * @type {number|Array<number>}
  7483. */
  7484. this.count = null;
  7485. /**
  7486. * The dispatch size for workgroups on X, Y, and Z axes.
  7487. * Used directly if `count` is not provided.
  7488. *
  7489. * @type {number|Array<number>}
  7490. */
  7491. this.dispatchSize = null;
  7492. /**
  7493. * The version of the node.
  7494. *
  7495. * @type {number}
  7496. */
  7497. this.version = 1;
  7498. /**
  7499. * The name or label of the uniform.
  7500. *
  7501. * @type {string}
  7502. * @default ''
  7503. */
  7504. this.name = '';
  7505. /**
  7506. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  7507. * is executed once per object by default.
  7508. *
  7509. * @type {string}
  7510. * @default 'object'
  7511. */
  7512. this.updateBeforeType = NodeUpdateType.OBJECT;
  7513. /**
  7514. * A callback executed when the compute node finishes initialization.
  7515. *
  7516. * @type {?Function}
  7517. */
  7518. this.onInitFunction = null;
  7519. /**
  7520. * A uniform node holding the dispatch count for bounds checking.
  7521. * Created automatically when `count` is a number.
  7522. *
  7523. * @type {?UniformNode}
  7524. */
  7525. this.countNode = null;
  7526. }
  7527. /**
  7528. * Executes the `dispose` event for this node.
  7529. */
  7530. dispose() {
  7531. this.dispatchEvent( { type: 'dispose' } );
  7532. }
  7533. /**
  7534. * Sets the {@link ComputeNode#name} property.
  7535. *
  7536. * @param {string} name - The name of the uniform.
  7537. * @return {ComputeNode} A reference to this node.
  7538. */
  7539. setName( name ) {
  7540. this.name = name;
  7541. return this;
  7542. }
  7543. /**
  7544. * Sets the {@link ComputeNode#name} property.
  7545. *
  7546. * @deprecated
  7547. * @param {string} name - The name of the uniform.
  7548. * @return {ComputeNode} A reference to this node.
  7549. */
  7550. label( name ) {
  7551. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  7552. return this.setName( name );
  7553. }
  7554. /**
  7555. * Sets the callback to run during initialization.
  7556. *
  7557. * @param {Function} callback - The callback function.
  7558. * @return {ComputeNode} A reference to this node.
  7559. */
  7560. onInit( callback ) {
  7561. this.onInitFunction = callback;
  7562. return this;
  7563. }
  7564. /**
  7565. * The method execute the compute for this node.
  7566. *
  7567. * @param {NodeFrame} frame - A reference to the current node frame.
  7568. */
  7569. updateBefore( { renderer } ) {
  7570. renderer.compute( this );
  7571. }
  7572. setup( builder ) {
  7573. if ( this.count !== null && this.countNode === null ) {
  7574. this.countNode = uniform( this.count, 'uint' ).onObjectUpdate( () => this.count );
  7575. }
  7576. const result = this.computeNode.build( builder );
  7577. if ( result ) {
  7578. const properties = builder.getNodeProperties( this );
  7579. properties.outputComputeNode = result.outputNode;
  7580. result.outputNode = null;
  7581. }
  7582. return result;
  7583. }
  7584. generate( builder, output ) {
  7585. const { shaderStage } = builder;
  7586. if ( shaderStage === 'compute' ) {
  7587. const snippet = this.computeNode.build( builder, 'void' );
  7588. if ( snippet !== '' ) {
  7589. builder.addLineFlowCode( snippet, this );
  7590. }
  7591. if ( this.count !== null && builder.allowEarlyReturns === true ) {
  7592. const countSnippet = this.countNode.build( builder, 'uint' );
  7593. const indexSnippet = instanceIndex.build( builder, 'uint' );
  7594. builder.flow.code = `${ builder.tab }if ( ${ indexSnippet } >= ${ countSnippet } ) { return; }\n\n${ builder.flow.code }`;
  7595. }
  7596. } else {
  7597. const properties = builder.getNodeProperties( this );
  7598. const outputComputeNode = properties.outputComputeNode;
  7599. if ( outputComputeNode ) {
  7600. return outputComputeNode.build( builder, output );
  7601. }
  7602. }
  7603. }
  7604. }
  7605. /**
  7606. * TSL function for creating a compute kernel node.
  7607. *
  7608. * @tsl
  7609. * @function
  7610. * @param {Node} node - The TSL logic for the compute shader.
  7611. * @param {Array<number>} [workgroupSize=[64]] - The workgroup size.
  7612. * @returns {ComputeNode}
  7613. */
  7614. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7615. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7616. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements', new StackTrace() );
  7617. }
  7618. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7619. const val = workgroupSize[ i ];
  7620. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7621. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer`, new StackTrace() );
  7622. }
  7623. }
  7624. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7625. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7626. //
  7627. return new ComputeNode( nodeObject( node ), workgroupSize );
  7628. };
  7629. /**
  7630. * TSL function for creating a compute node.
  7631. *
  7632. * @tsl
  7633. * @function
  7634. * @param {Node} node - The TSL logic for the compute shader.
  7635. * @param {number|Array<number>} count - The compute count or dispatch size.
  7636. * @param {Array<number>} [workgroupSize=[64]] - The workgroup size.
  7637. * @returns {ComputeNode}
  7638. , */
  7639. const compute = ( node, count, workgroupSize ) => {
  7640. const computeNode = computeKernel( node, workgroupSize );
  7641. if ( typeof count === 'number' ) {
  7642. computeNode.count = count;
  7643. } else {
  7644. computeNode.dispatchSize = count;
  7645. }
  7646. return computeNode;
  7647. };
  7648. addMethodChaining( 'compute', compute );
  7649. addMethodChaining( 'computeKernel', computeKernel );
  7650. /**
  7651. * This node can be used as a cache management component for another node.
  7652. * Caching is in general used by default in {@link NodeBuilder} but this node
  7653. * allows the usage of a shared parent cache during the build process.
  7654. *
  7655. * @augments Node
  7656. */
  7657. class IsolateNode extends Node {
  7658. static get type() {
  7659. return 'IsolateNode';
  7660. }
  7661. /**
  7662. * Constructs a new cache node.
  7663. *
  7664. * @param {Node} node - The node that should be cached.
  7665. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7666. */
  7667. constructor( node, parent = true ) {
  7668. super();
  7669. /**
  7670. * The node that should be cached.
  7671. *
  7672. * @type {Node}
  7673. */
  7674. this.node = node;
  7675. /**
  7676. * Whether this node refers to a shared parent cache or not.
  7677. *
  7678. * @type {boolean}
  7679. * @default true
  7680. */
  7681. this.parent = parent;
  7682. /**
  7683. * This flag can be used for type testing.
  7684. *
  7685. * @type {boolean}
  7686. * @readonly
  7687. * @default true
  7688. */
  7689. this.isIsolateNode = true;
  7690. }
  7691. generateNodeType( builder ) {
  7692. const previousCache = builder.getCache();
  7693. const cache = builder.getCacheFromNode( this, this.parent );
  7694. builder.setCache( cache );
  7695. const nodeType = this.node.getNodeType( builder );
  7696. builder.setCache( previousCache );
  7697. return nodeType;
  7698. }
  7699. build( builder, ...params ) {
  7700. const previousCache = builder.getCache();
  7701. const cache = builder.getCacheFromNode( this, this.parent );
  7702. builder.setCache( cache );
  7703. const data = this.node.build( builder, ...params );
  7704. builder.setCache( previousCache );
  7705. return data;
  7706. }
  7707. setParent( parent ) {
  7708. this.parent = parent;
  7709. return this;
  7710. }
  7711. getParent() {
  7712. return this.parent;
  7713. }
  7714. }
  7715. /**
  7716. * TSL function for creating a cache node.
  7717. *
  7718. * @tsl
  7719. * @function
  7720. * @param {Node} node - The node that should be cached.
  7721. * @returns {IsolateNode}
  7722. */
  7723. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7724. /**
  7725. * TSL function for creating a cache node.
  7726. *
  7727. * @tsl
  7728. * @function
  7729. * @deprecated
  7730. * @param {Node} node - The node that should be cached.
  7731. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7732. * @returns {IsolateNode}
  7733. */
  7734. function cache( node, parent = true ) {
  7735. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7736. return isolate( node ).setParent( parent );
  7737. }
  7738. addMethodChaining( 'cache', cache );
  7739. addMethodChaining( 'isolate', isolate );
  7740. /**
  7741. * The class generates the code of a given node but returns another node in the output.
  7742. * This can be used to call a method or node that does not return a value, i.e.
  7743. * type `void` on an input where returning a value is required. Example:
  7744. *
  7745. * ```js
  7746. * material.colorNode = myColor.bypass( runVoidFn() )
  7747. *```
  7748. *
  7749. * @augments Node
  7750. */
  7751. class BypassNode extends Node {
  7752. static get type() {
  7753. return 'BypassNode';
  7754. }
  7755. /**
  7756. * Constructs a new bypass node.
  7757. *
  7758. * @param {Node} outputNode - The output node.
  7759. * @param {Node} callNode - The call node.
  7760. */
  7761. constructor( outputNode, callNode ) {
  7762. super();
  7763. /**
  7764. * This flag can be used for type testing.
  7765. *
  7766. * @type {boolean}
  7767. * @readonly
  7768. * @default true
  7769. */
  7770. this.isBypassNode = true;
  7771. /**
  7772. * The output node.
  7773. *
  7774. * @type {Node}
  7775. */
  7776. this.outputNode = outputNode;
  7777. /**
  7778. * The call node.
  7779. *
  7780. * @type {Node}
  7781. */
  7782. this.callNode = callNode;
  7783. }
  7784. generateNodeType( builder ) {
  7785. return this.outputNode.getNodeType( builder );
  7786. }
  7787. generate( builder ) {
  7788. const snippet = this.callNode.build( builder, 'void' );
  7789. if ( snippet !== '' ) {
  7790. builder.addLineFlowCode( snippet, this );
  7791. }
  7792. return this.outputNode.build( builder );
  7793. }
  7794. }
  7795. /**
  7796. * TSL function for creating a bypass node.
  7797. *
  7798. * @tsl
  7799. * @function
  7800. * @param {Node} outputNode - The output node.
  7801. * @param {Node} callNode - The call node.
  7802. * @returns {BypassNode}
  7803. */
  7804. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7805. addMethodChaining( 'bypass', bypass );
  7806. /**
  7807. * This node allows to remap a node value from one range into another. E.g a value of
  7808. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7809. * `remap` takes care of that and converts the original value of `0.4` to `0.5`.
  7810. *
  7811. * @tsl
  7812. * @function
  7813. * @param {Node} node - The node that should be remapped.
  7814. * @param {Node} inLowNode - The source or current lower bound of the range.
  7815. * @param {Node} inHighNode - The source or current upper bound of the range.
  7816. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7817. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7818. * @returns {Node}
  7819. */
  7820. const remap = /*@__PURE__*/ Fn( ( [ node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ), doClamp = bool( false ) ] ) => {
  7821. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7822. if ( defined( doClamp ) ) t = t.clamp();
  7823. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7824. } );
  7825. /**
  7826. * This node allows to remap a node value from one range into another but with enabled clamping. E.g a value of
  7827. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7828. * `remapClamp` takes care of that and converts the original value of `0.4` to `0.5`.
  7829. *
  7830. * @tsl
  7831. * @function
  7832. * @param {Node} node - The node that should be remapped.
  7833. * @param {Node} inLowNode - The source or current lower bound of the range.
  7834. * @param {Node} inHighNode - The source or current upper bound of the range.
  7835. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7836. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7837. * @returns {Node}
  7838. */
  7839. function remapClamp( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7840. return remap( node, inLowNode, inHighNode, outLowNode, outHighNode, true );
  7841. }
  7842. addMethodChaining( 'remap', remap );
  7843. addMethodChaining( 'remapClamp', remapClamp );
  7844. /**
  7845. * This class can be used to implement basic expressions in shader code.
  7846. * Basic examples for that are `return`, `continue` or `discard` statements.
  7847. *
  7848. * @augments Node
  7849. */
  7850. class ExpressionNode extends Node {
  7851. static get type() {
  7852. return 'ExpressionNode';
  7853. }
  7854. /**
  7855. * Constructs a new expression node.
  7856. *
  7857. * @param {string} [snippet=''] - The native code snippet.
  7858. * @param {string} [nodeType='void'] - The node type.
  7859. */
  7860. constructor( snippet = '', nodeType = 'void' ) {
  7861. super( nodeType );
  7862. /**
  7863. * The native code snippet.
  7864. *
  7865. * @type {string}
  7866. * @default ''
  7867. */
  7868. this.snippet = snippet;
  7869. }
  7870. generate( builder, output ) {
  7871. const type = this.getNodeType( builder );
  7872. const snippet = this.snippet;
  7873. if ( type === 'void' ) {
  7874. builder.addLineFlowCode( snippet, this );
  7875. } else {
  7876. return builder.format( snippet, type, output );
  7877. }
  7878. }
  7879. }
  7880. /**
  7881. * TSL function for creating an expression node.
  7882. *
  7883. * @tsl
  7884. * @function
  7885. * @param {string} [snippet] - The native code snippet.
  7886. * @param {?string} [nodeType='void'] - The node type.
  7887. * @returns {ExpressionNode}
  7888. */
  7889. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7890. /**
  7891. * Represents a `discard` shader operation in TSL.
  7892. *
  7893. * @tsl
  7894. * @function
  7895. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7896. * @return {Node} The `discard` expression.
  7897. */
  7898. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7899. /**
  7900. * Represents a `return` shader operation in TSL.
  7901. *
  7902. * @tsl
  7903. * @function
  7904. * @return {ExpressionNode} The `return` expression.
  7905. */
  7906. const Return = () => expression( 'return' ).toStack();
  7907. addMethodChaining( 'discard', Discard );
  7908. /**
  7909. * Normally, tone mapping and color conversion happens automatically just
  7910. * before outputting a pixel to the default (screen) framebuffer. In certain
  7911. * post processing setups this is too late because some effects such as FXAA
  7912. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7913. * to apply tone mapping and color space conversion at an arbitrary point
  7914. * in the effect chain.
  7915. *
  7916. * When applying tone mapping and color space conversion manually with this node,
  7917. * you have to set {@link RenderPipeline#outputColorTransform} to `false`.
  7918. *
  7919. * ```js
  7920. * const postProcessing = new RenderPipeline( renderer );
  7921. * postProcessing.outputColorTransform = false;
  7922. *
  7923. * const scenePass = pass( scene, camera );
  7924. * const outputPass = renderOutput( scenePass );
  7925. *
  7926. * postProcessing.outputNode = outputPass;
  7927. * ```
  7928. *
  7929. * @augments TempNode
  7930. */
  7931. class RenderOutputNode extends TempNode {
  7932. static get type() {
  7933. return 'RenderOutputNode';
  7934. }
  7935. /**
  7936. * Constructs a new render output node.
  7937. *
  7938. * @param {Node} colorNode - The color node to process.
  7939. * @param {?number} toneMapping - The tone mapping type.
  7940. * @param {?string} outputColorSpace - The output color space.
  7941. */
  7942. constructor( colorNode, toneMapping, outputColorSpace ) {
  7943. super( 'vec4' );
  7944. /**
  7945. * The color node to process.
  7946. *
  7947. * @type {Node}
  7948. */
  7949. this.colorNode = colorNode;
  7950. /**
  7951. * The tone mapping type.
  7952. *
  7953. * @private
  7954. * @type {?number}
  7955. */
  7956. this._toneMapping = toneMapping;
  7957. /**
  7958. * The output color space.
  7959. *
  7960. * @type {?string}
  7961. */
  7962. this.outputColorSpace = outputColorSpace;
  7963. /**
  7964. * This flag can be used for type testing.
  7965. *
  7966. * @type {boolean}
  7967. * @readonly
  7968. * @default true
  7969. */
  7970. this.isRenderOutputNode = true;
  7971. }
  7972. /**
  7973. * Sets the tone mapping type.
  7974. *
  7975. * @param {number} value - The tone mapping type.
  7976. * @return {ToneMappingNode} A reference to this node.
  7977. */
  7978. setToneMapping( value ) {
  7979. this._toneMapping = value;
  7980. return this;
  7981. }
  7982. /**
  7983. * Gets the tone mapping type.
  7984. *
  7985. * @returns {number} The tone mapping type.
  7986. */
  7987. getToneMapping() {
  7988. return this._toneMapping;
  7989. }
  7990. setup( { context } ) {
  7991. let outputNode = this.colorNode || context.color;
  7992. // tone mapping
  7993. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  7994. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7995. if ( toneMapping !== NoToneMapping ) {
  7996. outputNode = outputNode.toneMapping( toneMapping );
  7997. }
  7998. // working to output color space
  7999. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  8000. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  8001. }
  8002. return outputNode;
  8003. }
  8004. }
  8005. /**
  8006. * TSL function for creating a render output node.
  8007. *
  8008. * @tsl
  8009. * @function
  8010. * @param {Node} color - The color node to process.
  8011. * @param {?number} [toneMapping=null] - The tone mapping type.
  8012. * @param {?string} [outputColorSpace=null] - The output color space.
  8013. * @returns {RenderOutputNode}
  8014. */
  8015. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace );
  8016. addMethodChaining( 'renderOutput', renderOutput );
  8017. class DebugNode extends TempNode {
  8018. static get type() {
  8019. return 'DebugNode';
  8020. }
  8021. constructor( node, callback = null ) {
  8022. super();
  8023. this.node = node;
  8024. this.callback = callback;
  8025. }
  8026. generateNodeType( builder ) {
  8027. return this.node.getNodeType( builder );
  8028. }
  8029. setup( builder ) {
  8030. return this.node.build( builder );
  8031. }
  8032. analyze( builder ) {
  8033. return this.node.build( builder );
  8034. }
  8035. generate( builder ) {
  8036. const callback = this.callback;
  8037. const snippet = this.node.build( builder );
  8038. if ( callback !== null ) {
  8039. callback( builder, snippet );
  8040. } else {
  8041. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  8042. const border = '-'.repeat( title.length );
  8043. let code = '';
  8044. code += '// #' + title + '#\n';
  8045. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  8046. code += '/* ... */ ' + snippet + ' /* ... */\n';
  8047. code += '// #' + border + '#\n';
  8048. log$1( code );
  8049. }
  8050. return snippet;
  8051. }
  8052. }
  8053. /**
  8054. * TSL function for creating a debug node.
  8055. *
  8056. * @tsl
  8057. * @function
  8058. * @param {Node} node - The node to debug.
  8059. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  8060. * @returns {DebugNode}
  8061. */
  8062. const debug = ( node, callback = null ) => new DebugNode( nodeObject( node ), callback ).toStack();
  8063. addMethodChaining( 'debug', debug );
  8064. /**
  8065. * InspectorBase is the base class for all inspectors.
  8066. *
  8067. * @class InspectorBase
  8068. * @augments EventDispatcher
  8069. */
  8070. class InspectorBase extends EventDispatcher {
  8071. /**
  8072. * Creates a new InspectorBase.
  8073. */
  8074. constructor() {
  8075. super();
  8076. /**
  8077. * The renderer associated with this inspector.
  8078. *
  8079. * @type {WebGLRenderer}
  8080. * @private
  8081. */
  8082. this._renderer = null;
  8083. /**
  8084. * The current frame being processed.
  8085. *
  8086. * @type {Object}
  8087. */
  8088. this.currentFrame = null;
  8089. }
  8090. /**
  8091. * Returns the node frame for the current renderer.
  8092. *
  8093. * @return {Object} The node frame.
  8094. */
  8095. get nodeFrame() {
  8096. return this._renderer._nodes.nodeFrame;
  8097. }
  8098. /**
  8099. * Sets the renderer for this inspector.
  8100. *
  8101. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  8102. * @return {InspectorBase} This inspector instance.
  8103. */
  8104. setRenderer( renderer ) {
  8105. this._renderer = renderer;
  8106. return this;
  8107. }
  8108. /**
  8109. * Returns the renderer associated with this inspector.
  8110. *
  8111. * @return {WebGLRenderer} The associated renderer.
  8112. */
  8113. getRenderer() {
  8114. return this._renderer;
  8115. }
  8116. /**
  8117. * Initializes the inspector.
  8118. */
  8119. init() { }
  8120. /**
  8121. * Called when a frame begins.
  8122. */
  8123. begin() { }
  8124. /**
  8125. * Called when a frame ends.
  8126. */
  8127. finish() { }
  8128. /**
  8129. * Inspects a node.
  8130. *
  8131. * @param {Node} node - The node to inspect.
  8132. */
  8133. inspect( /*node*/ ) { }
  8134. /**
  8135. * When a compute operation is performed.
  8136. *
  8137. * @param {ComputeNode} computeNode - The compute node being executed.
  8138. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  8139. */
  8140. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  8141. /**
  8142. * Called when a compute operation begins.
  8143. *
  8144. * @param {string} uid - A unique identifier for the render context.
  8145. * @param {ComputeNode} computeNode - The compute node being executed.
  8146. */
  8147. beginCompute( /*uid, computeNode*/ ) { }
  8148. /**
  8149. * Called when a compute operation ends.
  8150. *
  8151. * @param {string} uid - A unique identifier for the render context.
  8152. * @param {ComputeNode} computeNode - The compute node being executed.
  8153. */
  8154. finishCompute( /*uid*/ ) { }
  8155. /**
  8156. * Called when a render operation begins.
  8157. *
  8158. * @param {string} uid - A unique identifier for the render context.
  8159. * @param {Scene} scene - The scene being rendered.
  8160. * @param {Camera} camera - The camera being used for rendering.
  8161. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  8162. */
  8163. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  8164. /**
  8165. * Called when an animation loop ends.
  8166. *
  8167. * @param {string} uid - A unique identifier for the render context.
  8168. */
  8169. finishRender( /*uid*/ ) { }
  8170. /**
  8171. * Called when a texture copy operation is performed.
  8172. *
  8173. * @param {Texture} srcTexture - The source texture.
  8174. * @param {Texture} dstTexture - The destination texture.
  8175. */
  8176. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  8177. /**
  8178. * Called when a framebuffer copy operation is performed.
  8179. *
  8180. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  8181. */
  8182. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  8183. }
  8184. /**
  8185. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  8186. * It can be used to debug or analyze node outputs in the rendering pipeline.
  8187. *
  8188. * @augments Node
  8189. */
  8190. class InspectorNode extends Node {
  8191. /**
  8192. * Returns the type of the node.
  8193. *
  8194. * @returns {string}
  8195. */
  8196. static get type() {
  8197. return 'InspectorNode';
  8198. }
  8199. /**
  8200. * Creates an InspectorNode.
  8201. *
  8202. * @param {Node} node - The node to inspect.
  8203. * @param {string} [name=''] - Optional name for the inspector node.
  8204. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  8205. */
  8206. constructor( node, name = '', callback = null ) {
  8207. super();
  8208. this.node = node;
  8209. this.name = name;
  8210. this.callback = callback;
  8211. this.updateType = NodeUpdateType.FRAME;
  8212. this.isInspectorNode = true;
  8213. }
  8214. /**
  8215. * Returns the name of the inspector node.
  8216. *
  8217. * @returns {string}
  8218. */
  8219. getName() {
  8220. return this.name || this.node.name;
  8221. }
  8222. /**
  8223. * Updates the inspector node, allowing inspection of the wrapped node.
  8224. *
  8225. * @param {NodeFrame} frame - A reference to the current node frame.
  8226. */
  8227. update( frame ) {
  8228. frame.renderer.inspector.inspect( this );
  8229. }
  8230. /**
  8231. * Returns the type of the wrapped node.
  8232. *
  8233. * @param {NodeBuilder} builder - The node builder.
  8234. * @returns {string}
  8235. */
  8236. generateNodeType( builder ) {
  8237. return this.node.getNodeType( builder );
  8238. }
  8239. /**
  8240. * Sets up the inspector node.
  8241. *
  8242. * @param {NodeBuilder} builder - The node builder.
  8243. * @returns {Node} The setup node.
  8244. */
  8245. setup( builder ) {
  8246. let node = this.node;
  8247. if ( builder.context.inspector === true && this.callback !== null ) {
  8248. node = this.callback( node );
  8249. }
  8250. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  8251. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  8252. }
  8253. return node;
  8254. }
  8255. }
  8256. /**
  8257. * Creates an inspector node to wrap around a given node for inspection purposes.
  8258. *
  8259. * @tsl
  8260. * @param {Node} node - The node to inspect.
  8261. * @param {string} [name=''] - Optional name for the inspector node.
  8262. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  8263. * @returns {Node} The inspector node.
  8264. */
  8265. function inspector( node, name = '', callback = null ) {
  8266. node = nodeObject( node );
  8267. return node.before( new InspectorNode( node, name, callback ) );
  8268. }
  8269. addMethodChaining( 'toInspector', inspector );
  8270. function addNodeElement( name/*, nodeElement*/ ) {
  8271. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  8272. }
  8273. /**
  8274. * Base class for representing shader attributes as nodes.
  8275. *
  8276. * @augments Node
  8277. */
  8278. class AttributeNode extends Node {
  8279. static get type() {
  8280. return 'AttributeNode';
  8281. }
  8282. /**
  8283. * Constructs a new attribute node.
  8284. *
  8285. * @param {string} attributeName - The name of the attribute.
  8286. * @param {?string} nodeType - The node type.
  8287. */
  8288. constructor( attributeName, nodeType = null ) {
  8289. super( nodeType );
  8290. /**
  8291. * `AttributeNode` sets this property to `true` by default.
  8292. *
  8293. * @type {boolean}
  8294. * @default true
  8295. */
  8296. this.global = true;
  8297. this._attributeName = attributeName;
  8298. }
  8299. getHash( builder ) {
  8300. return this.getAttributeName( builder );
  8301. }
  8302. generateNodeType( builder ) {
  8303. let nodeType = this.nodeType;
  8304. if ( nodeType === null ) {
  8305. const attributeName = this.getAttributeName( builder );
  8306. if ( builder.hasGeometryAttribute( attributeName ) ) {
  8307. const attribute = builder.geometry.getAttribute( attributeName );
  8308. nodeType = builder.getTypeFromAttribute( attribute );
  8309. } else {
  8310. nodeType = 'float';
  8311. }
  8312. }
  8313. return nodeType;
  8314. }
  8315. /**
  8316. * Sets the attribute name to the given value. The method can be
  8317. * overwritten in derived classes if the final name must be computed
  8318. * analytically.
  8319. *
  8320. * @param {string} attributeName - The name of the attribute.
  8321. * @return {AttributeNode} A reference to this node.
  8322. */
  8323. setAttributeName( attributeName ) {
  8324. this._attributeName = attributeName;
  8325. return this;
  8326. }
  8327. /**
  8328. * Returns the attribute name of this node. The method can be
  8329. * overwritten in derived classes if the final name must be computed
  8330. * analytically.
  8331. *
  8332. * @param {NodeBuilder} builder - The current node builder.
  8333. * @return {string} The attribute name.
  8334. */
  8335. getAttributeName( /*builder*/ ) {
  8336. return this._attributeName;
  8337. }
  8338. generate( builder ) {
  8339. const attributeName = this.getAttributeName( builder );
  8340. const nodeType = this.getNodeType( builder );
  8341. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  8342. if ( geometryAttribute === true ) {
  8343. const attribute = builder.geometry.getAttribute( attributeName );
  8344. const attributeType = builder.getTypeFromAttribute( attribute );
  8345. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  8346. if ( builder.shaderStage === 'vertex' ) {
  8347. return builder.format( nodeAttribute.name, attributeType, nodeType );
  8348. } else {
  8349. const nodeVarying = varying( this );
  8350. return nodeVarying.build( builder, nodeType );
  8351. }
  8352. } else {
  8353. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  8354. return builder.generateConst( nodeType );
  8355. }
  8356. }
  8357. serialize( data ) {
  8358. super.serialize( data );
  8359. data.global = this.global;
  8360. data._attributeName = this._attributeName;
  8361. }
  8362. deserialize( data ) {
  8363. super.deserialize( data );
  8364. this.global = data.global;
  8365. this._attributeName = data._attributeName;
  8366. }
  8367. }
  8368. /**
  8369. * TSL function for creating an attribute node.
  8370. *
  8371. * @tsl
  8372. * @function
  8373. * @param {string} name - The name of the attribute.
  8374. * @param {?string} [nodeType=null] - The node type.
  8375. * @returns {AttributeNode}
  8376. */
  8377. const attribute = ( name, nodeType = null ) => new AttributeNode( name, nodeType );
  8378. /**
  8379. * TSL function for creating an uv attribute node with the given index.
  8380. *
  8381. * @tsl
  8382. * @function
  8383. * @param {number} [index=0] - The uv index.
  8384. * @return {AttributeNode<vec2>} The uv attribute node.
  8385. */
  8386. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  8387. /**
  8388. * A node that represents the dimensions of a texture. The texture size is
  8389. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  8390. * or `textureSize()`.
  8391. *
  8392. * @augments Node
  8393. */
  8394. class TextureSizeNode extends Node {
  8395. static get type() {
  8396. return 'TextureSizeNode';
  8397. }
  8398. /**
  8399. * Constructs a new texture size node.
  8400. *
  8401. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8402. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8403. */
  8404. constructor( textureNode, levelNode = null ) {
  8405. super( 'uvec2' );
  8406. /**
  8407. * This flag can be used for type testing.
  8408. *
  8409. * @type {boolean}
  8410. * @readonly
  8411. * @default true
  8412. */
  8413. this.isTextureSizeNode = true;
  8414. /**
  8415. * A texture node which size should be retrieved.
  8416. *
  8417. * @type {TextureNode}
  8418. */
  8419. this.textureNode = textureNode;
  8420. /**
  8421. * A level node which defines the requested mip.
  8422. *
  8423. * @type {Node<int>}
  8424. * @default null
  8425. */
  8426. this.levelNode = levelNode;
  8427. }
  8428. generate( builder, output ) {
  8429. const textureProperty = this.textureNode.build( builder, 'property' );
  8430. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  8431. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  8432. }
  8433. }
  8434. /**
  8435. * TSL function for creating a texture size node.
  8436. *
  8437. * @tsl
  8438. * @function
  8439. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8440. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8441. * @returns {TextureSizeNode}
  8442. */
  8443. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  8444. /**
  8445. * A special type of uniform node that computes the
  8446. * maximum mipmap level for a given texture node.
  8447. *
  8448. * ```js
  8449. * const level = maxMipLevel( textureNode );
  8450. * ```
  8451. *
  8452. * @augments UniformNode
  8453. */
  8454. class MaxMipLevelNode extends UniformNode {
  8455. static get type() {
  8456. return 'MaxMipLevelNode';
  8457. }
  8458. /**
  8459. * Constructs a new max mip level node.
  8460. *
  8461. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8462. */
  8463. constructor( textureNode ) {
  8464. super( 0 );
  8465. /**
  8466. * The texture node to compute the max mip level for.
  8467. *
  8468. * @private
  8469. * @type {TextureNode}
  8470. */
  8471. this._textureNode = textureNode;
  8472. /**
  8473. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  8474. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  8475. *
  8476. * @type {string}
  8477. * @default 'frame'
  8478. */
  8479. this.updateType = NodeUpdateType.FRAME;
  8480. }
  8481. /**
  8482. * The texture node to compute the max mip level for.
  8483. *
  8484. * @readonly
  8485. * @type {TextureNode}
  8486. */
  8487. get textureNode() {
  8488. return this._textureNode;
  8489. }
  8490. /**
  8491. * The texture.
  8492. *
  8493. * @readonly
  8494. * @type {Texture}
  8495. */
  8496. get texture() {
  8497. return this._textureNode.value;
  8498. }
  8499. update() {
  8500. const texture = this.texture;
  8501. const images = texture.images;
  8502. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  8503. if ( image && image.width !== undefined ) {
  8504. const { width, height } = image;
  8505. this.value = Math.log2( Math.max( width, height ) );
  8506. }
  8507. }
  8508. }
  8509. /**
  8510. * TSL function for creating a max mip level node.
  8511. *
  8512. * @tsl
  8513. * @function
  8514. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8515. * @returns {MaxMipLevelNode}
  8516. */
  8517. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  8518. /**
  8519. * Custom error class for node-related errors, including stack trace information.
  8520. */
  8521. class NodeError extends Error {
  8522. constructor( message, stackTrace = null ) {
  8523. super( message );
  8524. /**
  8525. * The name of the error.
  8526. *
  8527. * @type {string}
  8528. */
  8529. this.name = 'NodeError';
  8530. /**
  8531. * The stack trace associated with the error.
  8532. *
  8533. * @type {?StackTrace}
  8534. */
  8535. this.stackTrace = stackTrace;
  8536. }
  8537. }
  8538. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  8539. /**
  8540. * This type of uniform node represents a 2D texture.
  8541. *
  8542. * @augments UniformNode
  8543. */
  8544. class TextureNode extends UniformNode {
  8545. static get type() {
  8546. return 'TextureNode';
  8547. }
  8548. /**
  8549. * Constructs a new texture node.
  8550. *
  8551. * @param {Texture} [value=EmptyTexture] - The texture.
  8552. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8553. * @param {?Node<int>} [levelNode=null] - The level node.
  8554. * @param {?Node<float>} [biasNode=null] - The bias node.
  8555. */
  8556. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  8557. super( value );
  8558. /**
  8559. * This flag can be used for type testing.
  8560. *
  8561. * @type {boolean}
  8562. * @readonly
  8563. * @default true
  8564. */
  8565. this.isTextureNode = true;
  8566. /**
  8567. * Represents the texture coordinates.
  8568. *
  8569. * @type {?Node<vec2|vec3>}
  8570. * @default null
  8571. */
  8572. this.uvNode = uvNode;
  8573. /**
  8574. * Represents the mip level that should be selected.
  8575. *
  8576. * @type {?Node<int>}
  8577. * @default null
  8578. */
  8579. this.levelNode = levelNode;
  8580. /**
  8581. * Represents the bias to be applied during level-of-detail computation.
  8582. *
  8583. * @type {?Node<float>}
  8584. * @default null
  8585. */
  8586. this.biasNode = biasNode;
  8587. /**
  8588. * Represents a reference value a texture sample is compared to.
  8589. *
  8590. * @type {?Node<float>}
  8591. * @default null
  8592. */
  8593. this.compareNode = null;
  8594. /**
  8595. * When using texture arrays, the depth node defines the layer to select.
  8596. *
  8597. * @type {?Node<int>}
  8598. * @default null
  8599. */
  8600. this.depthNode = null;
  8601. /**
  8602. * When defined, a texture is sampled using explicit gradients.
  8603. *
  8604. * @type {?Array<Node<vec2>>}
  8605. * @default null
  8606. */
  8607. this.gradNode = null;
  8608. /**
  8609. * Represents the optional texel offset applied to the unnormalized texture
  8610. * coordinate before sampling the texture.
  8611. *
  8612. * @type {?Node<ivec2|ivec3>}
  8613. * @default null
  8614. */
  8615. this.offsetNode = null;
  8616. /**
  8617. * Whether texture values should be sampled or fetched.
  8618. *
  8619. * @type {boolean}
  8620. * @default true
  8621. */
  8622. this.sampler = true;
  8623. /**
  8624. * Whether the uv transformation matrix should be
  8625. * automatically updated or not. Use `setUpdateMatrix()`
  8626. * if you want to change the value of the property.
  8627. *
  8628. * @type {boolean}
  8629. * @default false
  8630. */
  8631. this.updateMatrix = false;
  8632. /**
  8633. * By default the `update()` method is not executed. Depending on
  8634. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8635. * is executed per object.
  8636. *
  8637. * @type {string}
  8638. * @default 'none'
  8639. */
  8640. this.updateType = NodeUpdateType.NONE;
  8641. /**
  8642. * The reference node.
  8643. *
  8644. * @type {?Node}
  8645. * @default null
  8646. */
  8647. this.referenceNode = null;
  8648. /**
  8649. * The texture value is stored in a private property.
  8650. *
  8651. * @private
  8652. * @type {Texture}
  8653. */
  8654. this._value = value;
  8655. /**
  8656. * The uniform node that represents the uv transformation matrix.
  8657. *
  8658. * @private
  8659. * @type {?UniformNode<mat3>}
  8660. * @default null
  8661. */
  8662. this._matrixUniform = null;
  8663. /**
  8664. * The uniform node that represents the y-flip. Only required for WebGL.
  8665. *
  8666. * @private
  8667. * @type {?UniformNode<bool>}
  8668. * @default null
  8669. */
  8670. this._flipYUniform = null;
  8671. this.setUpdateMatrix( uvNode === null );
  8672. }
  8673. set value( value ) {
  8674. if ( this.referenceNode ) {
  8675. this.referenceNode.value = value;
  8676. } else {
  8677. this._value = value;
  8678. }
  8679. }
  8680. /**
  8681. * The texture value.
  8682. *
  8683. * @type {Texture}
  8684. */
  8685. get value() {
  8686. return this.referenceNode ? this.referenceNode.value : this._value;
  8687. }
  8688. /**
  8689. * Overwritten since the uniform hash is defined by the texture's UUID.
  8690. *
  8691. * @param {NodeBuilder} builder - The current node builder.
  8692. * @return {string} The uniform hash.
  8693. */
  8694. getUniformHash( /*builder*/ ) {
  8695. return this.value.uuid;
  8696. }
  8697. /**
  8698. * Overwritten since the node type is inferred from the texture type.
  8699. *
  8700. * @param {NodeBuilder} builder - The current node builder.
  8701. * @return {string} The node type.
  8702. */
  8703. generateNodeType( /*builder*/ ) {
  8704. if ( this.value.isDepthTexture === true ) return 'float';
  8705. if ( this.value.type === UnsignedIntType ) {
  8706. return 'uvec4';
  8707. } else if ( this.value.type === IntType ) {
  8708. return 'ivec4';
  8709. }
  8710. return 'vec4';
  8711. }
  8712. /**
  8713. * Overwrites the default implementation to return a fixed value `'texture'`.
  8714. *
  8715. * @param {NodeBuilder} builder - The current node builder.
  8716. * @return {string} The input type.
  8717. */
  8718. getInputType( /*builder*/ ) {
  8719. return 'texture';
  8720. }
  8721. /**
  8722. * Returns a default uvs based on the current texture's channel.
  8723. *
  8724. * @return {AttributeNode<vec2>} The default uvs.
  8725. */
  8726. getDefaultUV() {
  8727. return uv$1( this.value.channel );
  8728. }
  8729. /**
  8730. * Overwritten to always return the texture reference of the node.
  8731. *
  8732. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8733. * @return {Texture} The texture reference.
  8734. */
  8735. updateReference( /*state*/ ) {
  8736. return this.value;
  8737. }
  8738. /**
  8739. * Transforms the given uv node with the texture transformation matrix.
  8740. *
  8741. * @param {Node} uvNode - The uv node to transform.
  8742. * @return {Node} The transformed uv node.
  8743. */
  8744. getTransformedUV( uvNode ) {
  8745. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8746. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8747. }
  8748. /**
  8749. * Defines whether the uv transformation matrix should automatically be updated or not.
  8750. *
  8751. * @param {boolean} value - The update toggle.
  8752. * @return {TextureNode} A reference to this node.
  8753. */
  8754. setUpdateMatrix( value ) {
  8755. this.updateMatrix = value;
  8756. return this;
  8757. }
  8758. /**
  8759. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8760. * to modify the uv node for correct sampling.
  8761. *
  8762. * @param {NodeBuilder} builder - The current node builder.
  8763. * @param {Node} uvNode - The uv node to setup.
  8764. * @return {Node} The updated uv node.
  8765. */
  8766. setupUV( builder, uvNode ) {
  8767. if ( builder.isFlipY() ) {
  8768. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8769. uvNode = uvNode.toVar();
  8770. if ( this.sampler ) {
  8771. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8772. } else {
  8773. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8774. }
  8775. }
  8776. return uvNode;
  8777. }
  8778. /**
  8779. * Setups texture node by preparing the internal nodes for code generation.
  8780. *
  8781. * @param {NodeBuilder} builder - The current node builder.
  8782. */
  8783. setup( builder ) {
  8784. const properties = builder.getNodeProperties( this );
  8785. properties.referenceNode = this.referenceNode;
  8786. //
  8787. const texture = this.value;
  8788. if ( ! texture || texture.isTexture !== true ) {
  8789. throw new NodeError( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().', this.stackTrace );
  8790. }
  8791. //
  8792. const uvNode = Fn( () => {
  8793. let uvNode = this.uvNode;
  8794. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8795. uvNode = builder.context.getUV( this, builder );
  8796. }
  8797. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8798. if ( this.updateMatrix === true ) {
  8799. uvNode = this.getTransformedUV( uvNode );
  8800. }
  8801. uvNode = this.setupUV( builder, uvNode );
  8802. //
  8803. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8804. //
  8805. return uvNode;
  8806. } )();
  8807. //
  8808. let levelNode = this.levelNode;
  8809. if ( levelNode === null && builder.context.getTextureLevel ) {
  8810. levelNode = builder.context.getTextureLevel( this );
  8811. }
  8812. //
  8813. let compareNode = null;
  8814. let compareStepNode = null;
  8815. if ( this.compareNode !== null ) {
  8816. if ( builder.renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  8817. compareNode = this.compareNode;
  8818. } else {
  8819. const compareFunction = texture.compareFunction;
  8820. if ( compareFunction === null || compareFunction === LessCompare || compareFunction === LessEqualCompare || compareFunction === GreaterCompare || compareFunction === GreaterEqualCompare ) {
  8821. compareStepNode = this.compareNode;
  8822. } else {
  8823. compareNode = this.compareNode;
  8824. warnOnce( 'TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.' );
  8825. }
  8826. }
  8827. }
  8828. properties.uvNode = uvNode;
  8829. properties.levelNode = levelNode;
  8830. properties.biasNode = this.biasNode;
  8831. properties.compareNode = compareNode;
  8832. properties.compareStepNode = compareStepNode;
  8833. properties.gradNode = this.gradNode;
  8834. properties.depthNode = this.depthNode;
  8835. properties.offsetNode = this.offsetNode;
  8836. }
  8837. /**
  8838. * Generates the uv code snippet.
  8839. *
  8840. * @param {NodeBuilder} builder - The current node builder.
  8841. * @param {Node} uvNode - The uv node to generate code for.
  8842. * @return {string} The generated code snippet.
  8843. */
  8844. generateUV( builder, uvNode ) {
  8845. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8846. }
  8847. /**
  8848. * Generates the offset code snippet.
  8849. *
  8850. * @param {NodeBuilder} builder - The current node builder.
  8851. * @param {Node} offsetNode - The offset node to generate code for.
  8852. * @return {string} The generated code snippet.
  8853. */
  8854. generateOffset( builder, offsetNode ) {
  8855. return offsetNode.build( builder, 'ivec2' );
  8856. }
  8857. /**
  8858. * Generates the snippet for the texture sampling.
  8859. *
  8860. * @param {NodeBuilder} builder - The current node builder.
  8861. * @param {string} textureProperty - The texture property.
  8862. * @param {string} uvSnippet - The uv snippet.
  8863. * @param {?string} levelSnippet - The level snippet.
  8864. * @param {?string} biasSnippet - The bias snippet.
  8865. * @param {?string} depthSnippet - The depth snippet.
  8866. * @param {?string} compareSnippet - The compare snippet.
  8867. * @param {?Array<string>} gradSnippet - The grad snippet.
  8868. * @param {?string} offsetSnippet - The offset snippet.
  8869. * @return {string} The generated code snippet.
  8870. */
  8871. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8872. const texture = this.value;
  8873. let snippet;
  8874. if ( biasSnippet ) {
  8875. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8876. } else if ( gradSnippet ) {
  8877. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8878. } else if ( compareSnippet ) {
  8879. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8880. } else if ( this.sampler === false ) {
  8881. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8882. } else if ( levelSnippet ) {
  8883. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8884. } else {
  8885. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8886. }
  8887. return snippet;
  8888. }
  8889. /**
  8890. * Generates the code snippet of the texture node.
  8891. *
  8892. * @param {NodeBuilder} builder - The current node builder.
  8893. * @param {string} output - The current output.
  8894. * @return {string} The generated code snippet.
  8895. */
  8896. generate( builder, output ) {
  8897. const texture = this.value;
  8898. const properties = builder.getNodeProperties( this );
  8899. const textureProperty = super.generate( builder, 'property' );
  8900. if ( /^sampler/.test( output ) ) {
  8901. return textureProperty + '_sampler';
  8902. } else if ( builder.isReference( output ) ) {
  8903. return textureProperty;
  8904. } else {
  8905. const nodeData = builder.getDataFromNode( this );
  8906. const nodeType = this.getNodeType( builder );
  8907. let propertyName = nodeData.propertyName;
  8908. if ( propertyName === undefined ) {
  8909. const { uvNode, levelNode, biasNode, compareNode, compareStepNode, depthNode, gradNode, offsetNode } = properties;
  8910. const uvSnippet = this.generateUV( builder, uvNode );
  8911. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8912. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8913. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8914. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8915. const compareStepSnippet = compareStepNode ? compareStepNode.build( builder, 'float' ) : null;
  8916. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8917. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8918. let finalDepthSnippet = depthSnippet;
  8919. if ( finalDepthSnippet === null && texture.isArrayTexture && this.isTexture3DNode !== true ) {
  8920. finalDepthSnippet = '0';
  8921. }
  8922. const nodeVar = builder.getVarFromNode( this );
  8923. propertyName = builder.getPropertyName( nodeVar );
  8924. let snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, finalDepthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8925. if ( compareStepSnippet !== null ) {
  8926. const compareFunction = texture.compareFunction;
  8927. if ( compareFunction === GreaterCompare || compareFunction === GreaterEqualCompare ) {
  8928. snippet = step( expression( snippet, nodeType ), expression( compareStepSnippet, 'float' ) ).build( builder, nodeType );
  8929. } else {
  8930. snippet = step( expression( compareStepSnippet, 'float' ), expression( snippet, nodeType ) ).build( builder, nodeType );
  8931. }
  8932. }
  8933. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8934. nodeData.snippet = snippet;
  8935. nodeData.propertyName = propertyName;
  8936. }
  8937. let snippet = propertyName;
  8938. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8939. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8940. }
  8941. return builder.format( snippet, nodeType, output );
  8942. }
  8943. }
  8944. /**
  8945. * Sets the sampler value.
  8946. *
  8947. * @param {boolean} value - The sampler value to set.
  8948. * @return {TextureNode} A reference to this texture node.
  8949. */
  8950. setSampler( value ) {
  8951. this.sampler = value;
  8952. return this;
  8953. }
  8954. /**
  8955. * Returns the sampler value.
  8956. *
  8957. * @return {boolean} The sampler value.
  8958. */
  8959. getSampler() {
  8960. return this.sampler;
  8961. }
  8962. // @TODO: Move to TSL
  8963. /**
  8964. * Samples the texture with the given uv node.
  8965. *
  8966. * @param {Node} uvNode - The uv node.
  8967. * @return {TextureNode} A texture node representing the texture sample.
  8968. */
  8969. sample( uvNode ) {
  8970. const textureNode = this.clone();
  8971. textureNode.uvNode = nodeObject( uvNode );
  8972. textureNode.referenceNode = this.getBase();
  8973. return nodeObject( textureNode );
  8974. }
  8975. /**
  8976. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8977. *
  8978. * @param {Node<uvec2>} uvNode - The uv node.
  8979. * @returns {TextureNode} A texture node representing the texture load.
  8980. */
  8981. load( uvNode ) {
  8982. return this.sample( uvNode ).setSampler( false );
  8983. }
  8984. /**
  8985. * Samples a blurred version of the texture by defining an internal bias.
  8986. *
  8987. * @param {Node<float>} amountNode - How blurred the texture should be.
  8988. * @return {TextureNode} A texture node representing the texture sample.
  8989. */
  8990. blur( amountNode ) {
  8991. const textureNode = this.clone();
  8992. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8993. textureNode.referenceNode = this.getBase();
  8994. const map = textureNode.value;
  8995. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8996. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8997. textureNode.biasNode = null;
  8998. }
  8999. return nodeObject( textureNode );
  9000. }
  9001. /**
  9002. * Samples a specific mip of the texture.
  9003. *
  9004. * @param {Node<int>} levelNode - The mip level to sample.
  9005. * @return {TextureNode} A texture node representing the texture sample.
  9006. */
  9007. level( levelNode ) {
  9008. const textureNode = this.clone();
  9009. textureNode.levelNode = nodeObject( levelNode );
  9010. textureNode.referenceNode = this.getBase();
  9011. return nodeObject( textureNode );
  9012. }
  9013. /**
  9014. * Returns the texture size of the requested level.
  9015. *
  9016. * @param {Node<int>} levelNode - The level to compute the size for.
  9017. * @return {TextureSizeNode} The texture size.
  9018. */
  9019. size( levelNode ) {
  9020. return textureSize( this, levelNode );
  9021. }
  9022. /**
  9023. * Samples the texture with the given bias.
  9024. *
  9025. * @param {Node<float>} biasNode - The bias node.
  9026. * @return {TextureNode} A texture node representing the texture sample.
  9027. */
  9028. bias( biasNode ) {
  9029. const textureNode = this.clone();
  9030. textureNode.biasNode = nodeObject( biasNode );
  9031. textureNode.referenceNode = this.getBase();
  9032. return nodeObject( textureNode );
  9033. }
  9034. /**
  9035. * Returns the base texture of this node.
  9036. * @return {TextureNode} The base texture node.
  9037. */
  9038. getBase() {
  9039. return this.referenceNode ? this.referenceNode.getBase() : this;
  9040. }
  9041. /**
  9042. * Samples the texture by executing a compare operation.
  9043. *
  9044. * @param {Node<float>} compareNode - The node that defines the compare value.
  9045. * @return {TextureNode} A texture node representing the texture sample.
  9046. */
  9047. compare( compareNode ) {
  9048. const textureNode = this.clone();
  9049. textureNode.compareNode = nodeObject( compareNode );
  9050. textureNode.referenceNode = this.getBase();
  9051. return nodeObject( textureNode );
  9052. }
  9053. /**
  9054. * Samples the texture using an explicit gradient.
  9055. *
  9056. * @param {Node<vec2>} gradNodeX - The gradX node.
  9057. * @param {Node<vec2>} gradNodeY - The gradY node.
  9058. * @return {TextureNode} A texture node representing the texture sample.
  9059. */
  9060. grad( gradNodeX, gradNodeY ) {
  9061. const textureNode = this.clone();
  9062. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  9063. textureNode.referenceNode = this.getBase();
  9064. return nodeObject( textureNode );
  9065. }
  9066. /**
  9067. * Samples the texture by defining a depth node.
  9068. *
  9069. * @param {Node<int>} depthNode - The depth node.
  9070. * @return {TextureNode} A texture node representing the texture sample.
  9071. */
  9072. depth( depthNode ) {
  9073. const textureNode = this.clone();
  9074. textureNode.depthNode = nodeObject( depthNode );
  9075. textureNode.referenceNode = this.getBase();
  9076. return nodeObject( textureNode );
  9077. }
  9078. /**
  9079. * Samples the texture by defining an offset node.
  9080. *
  9081. * @param {Node<ivec2>} offsetNode - The offset node.
  9082. * @return {TextureNode} A texture node representing the texture sample.
  9083. */
  9084. offset( offsetNode ) {
  9085. const textureNode = this.clone();
  9086. textureNode.offsetNode = nodeObject( offsetNode );
  9087. textureNode.referenceNode = this.getBase();
  9088. return nodeObject( textureNode );
  9089. }
  9090. // --
  9091. serialize( data ) {
  9092. super.serialize( data );
  9093. data.value = this.value.toJSON( data.meta ).uuid;
  9094. data.sampler = this.sampler;
  9095. data.updateMatrix = this.updateMatrix;
  9096. data.updateType = this.updateType;
  9097. }
  9098. deserialize( data ) {
  9099. super.deserialize( data );
  9100. this.value = data.meta.textures[ data.value ];
  9101. this.sampler = data.sampler;
  9102. this.updateMatrix = data.updateMatrix;
  9103. this.updateType = data.updateType;
  9104. }
  9105. /**
  9106. * The update is used to implement the update of the uv transformation matrix.
  9107. */
  9108. update() {
  9109. const texture = this.value;
  9110. const matrixUniform = this._matrixUniform;
  9111. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  9112. if ( texture.matrixAutoUpdate === true ) {
  9113. texture.updateMatrix();
  9114. }
  9115. //
  9116. const flipYUniform = this._flipYUniform;
  9117. if ( flipYUniform !== null ) {
  9118. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  9119. }
  9120. }
  9121. /**
  9122. * Clones the texture node.
  9123. *
  9124. * @return {TextureNode} The cloned texture node.
  9125. */
  9126. clone() {
  9127. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  9128. newNode.sampler = this.sampler;
  9129. newNode.depthNode = this.depthNode;
  9130. newNode.compareNode = this.compareNode;
  9131. newNode.gradNode = this.gradNode;
  9132. newNode.offsetNode = this.offsetNode;
  9133. return newNode;
  9134. }
  9135. }
  9136. /**
  9137. * TSL function for creating a texture node.
  9138. *
  9139. * @tsl
  9140. * @function
  9141. * @param {?Texture} value - The texture.
  9142. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  9143. * @param {?Node<int>} [levelNode=null] - The level node.
  9144. * @param {?Node<float>} [biasNode=null] - The bias node.
  9145. * @returns {TextureNode}
  9146. */
  9147. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  9148. /**
  9149. * TSL function for creating a texture node or sample a texture node already existing.
  9150. *
  9151. * @tsl
  9152. * @function
  9153. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  9154. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  9155. * @param {?Node<int>} [levelNode=null] - The level node.
  9156. * @param {?Node<float>} [biasNode=null] - The bias node.
  9157. * @returns {TextureNode}
  9158. */
  9159. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  9160. let textureNode;
  9161. if ( value && value.isTextureNode === true ) {
  9162. textureNode = nodeObject( value.clone() );
  9163. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  9164. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  9165. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  9166. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  9167. } else {
  9168. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  9169. }
  9170. return textureNode;
  9171. };
  9172. /**
  9173. * TSL function for creating a uniform texture node.
  9174. *
  9175. * @tsl
  9176. * @function
  9177. * @param {?Texture} value - The texture.
  9178. * @returns {TextureNode}
  9179. */
  9180. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  9181. /**
  9182. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  9183. *
  9184. * @tsl
  9185. * @function
  9186. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  9187. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  9188. * @param {?Node<int>} [levelNode=null] - The level node.
  9189. * @param {?Node<float>} [biasNode=null] - The bias node.
  9190. * @returns {TextureNode}
  9191. */
  9192. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  9193. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  9194. /**
  9195. * Converts a texture or texture node to a sampler.
  9196. *
  9197. * @tsl
  9198. * @function
  9199. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  9200. * @returns {Node}
  9201. */
  9202. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  9203. /**
  9204. * Converts a texture or texture node to a sampler comparison.
  9205. *
  9206. * @tsl
  9207. * @function
  9208. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  9209. * @returns {Node}
  9210. */
  9211. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  9212. /**
  9213. * A special type of uniform node which represents array-like data
  9214. * as uniform buffers. The access usually happens via `element()`
  9215. * which returns an instance of {@link ArrayElementNode}. For example:
  9216. *
  9217. * ```js
  9218. * const bufferNode = buffer( array, 'mat4', count );
  9219. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  9220. * ```
  9221. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  9222. * since it handles more input types and automatically cares about buffer paddings.
  9223. *
  9224. * @augments UniformNode
  9225. */
  9226. class BufferNode extends UniformNode {
  9227. static get type() {
  9228. return 'BufferNode';
  9229. }
  9230. /**
  9231. * Constructs a new buffer node.
  9232. *
  9233. * @param {Array<number>} value - Array-like buffer data.
  9234. * @param {string} bufferType - The data type of the buffer.
  9235. * @param {number} [bufferCount=0] - The count of buffer elements.
  9236. */
  9237. constructor( value, bufferType, bufferCount = 0 ) {
  9238. super( value, bufferType );
  9239. /**
  9240. * This flag can be used for type testing.
  9241. *
  9242. * @type {boolean}
  9243. * @readonly
  9244. * @default true
  9245. */
  9246. this.isBufferNode = true;
  9247. /**
  9248. * The data type of the buffer.
  9249. *
  9250. * @type {string}
  9251. */
  9252. this.bufferType = bufferType;
  9253. /**
  9254. * The uniform node that holds the value of the reference node.
  9255. *
  9256. * @type {number}
  9257. * @default 0
  9258. */
  9259. this.bufferCount = bufferCount;
  9260. /**
  9261. * An array of update ranges.
  9262. *
  9263. * @type {Array<{start: number, count: number}>}
  9264. */
  9265. this.updateRanges = [];
  9266. }
  9267. /**
  9268. * Adds a range of data in the data array to be updated on the GPU.
  9269. *
  9270. * @param {number} start - Position at which to start update.
  9271. * @param {number} count - The number of components to update.
  9272. */
  9273. addUpdateRange( start, count ) {
  9274. this.updateRanges.push( { start, count } );
  9275. }
  9276. /**
  9277. * Clears the update ranges.
  9278. */
  9279. clearUpdateRanges() {
  9280. this.updateRanges.length = 0;
  9281. }
  9282. /**
  9283. * The data type of the buffer elements.
  9284. *
  9285. * @param {NodeBuilder} builder - The current node builder.
  9286. * @return {string} The element type.
  9287. */
  9288. getElementType( builder ) {
  9289. return this.getNodeType( builder );
  9290. }
  9291. /**
  9292. * Overwrites the default implementation to return a fixed value `'buffer'`.
  9293. *
  9294. * @param {NodeBuilder} builder - The current node builder.
  9295. * @return {string} The input type.
  9296. */
  9297. getInputType( /*builder*/ ) {
  9298. return 'buffer';
  9299. }
  9300. }
  9301. /**
  9302. * TSL function for creating a buffer node.
  9303. *
  9304. * @tsl
  9305. * @function
  9306. * @param {Array<number>} value - Array-like buffer data.
  9307. * @param {string} type - The data type of a buffer element.
  9308. * @param {number} count - The count of buffer elements.
  9309. * @returns {BufferNode}
  9310. */
  9311. const buffer = ( value, type, count ) => new BufferNode( value, type, count );
  9312. /**
  9313. * Represents the element access on uniform array nodes.
  9314. *
  9315. * @augments ArrayElementNode
  9316. */
  9317. class UniformArrayElementNode extends ArrayElementNode {
  9318. static get type() {
  9319. return 'UniformArrayElementNode';
  9320. }
  9321. /**
  9322. * Constructs a new buffer node.
  9323. *
  9324. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  9325. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  9326. */
  9327. constructor( uniformArrayNode, indexNode ) {
  9328. super( uniformArrayNode, indexNode );
  9329. /**
  9330. * This flag can be used for type testing.
  9331. *
  9332. * @type {boolean}
  9333. * @readonly
  9334. * @default true
  9335. */
  9336. this.isArrayBufferElementNode = true;
  9337. }
  9338. generate( builder ) {
  9339. const snippet = super.generate( builder );
  9340. const type = this.getNodeType( builder );
  9341. const paddedType = this.node.getPaddedType();
  9342. return builder.format( snippet, paddedType, type );
  9343. }
  9344. }
  9345. /**
  9346. * Similar to {@link BufferNode} this module represents array-like data as
  9347. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  9348. * data types in the array (e.g `three.js` primitives) and automatically
  9349. * manage buffer padding. It should be the first choice when working with
  9350. * uniforms buffers.
  9351. * ```js
  9352. * const tintColors = uniformArray( [
  9353. * new Color( 1, 0, 0 ),
  9354. * new Color( 0, 1, 0 ),
  9355. * new Color( 0, 0, 1 )
  9356. * ], 'color' );
  9357. *
  9358. * const redColor = tintColors.element( 0 );
  9359. *
  9360. * @augments BufferNode
  9361. */
  9362. class UniformArrayNode extends BufferNode {
  9363. static get type() {
  9364. return 'UniformArrayNode';
  9365. }
  9366. /**
  9367. * Constructs a new uniform array node.
  9368. *
  9369. * @param {Array<any>} value - Array holding the buffer data.
  9370. * @param {?string} [elementType=null] - The data type of a buffer element.
  9371. */
  9372. constructor( value, elementType = null ) {
  9373. super( null );
  9374. /**
  9375. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  9376. * hold number primitives as well as three.js objects like vectors, matrices
  9377. * or colors.
  9378. *
  9379. * @type {Array<any>}
  9380. */
  9381. this.array = value;
  9382. /**
  9383. * The data type of an array element.
  9384. *
  9385. * @type {string}
  9386. */
  9387. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  9388. /**
  9389. * The padded type. Uniform buffers must conform to a certain buffer layout
  9390. * so a separate type is computed to ensure correct buffer size.
  9391. *
  9392. * @type {string}
  9393. */
  9394. this.paddedType = this.getPaddedType();
  9395. /**
  9396. * Overwritten since uniform array nodes are updated per render.
  9397. *
  9398. * @type {string}
  9399. * @default 'render'
  9400. */
  9401. this.updateType = NodeUpdateType.RENDER;
  9402. /**
  9403. * This flag can be used for type testing.
  9404. *
  9405. * @type {boolean}
  9406. * @readonly
  9407. * @default true
  9408. */
  9409. this.isArrayBufferNode = true;
  9410. }
  9411. /**
  9412. * This method is overwritten since the node type is inferred from the
  9413. * {@link UniformArrayNode#paddedType}.
  9414. *
  9415. * @param {NodeBuilder} builder - The current node builder.
  9416. * @return {string} The node type.
  9417. */
  9418. generateNodeType( /*builder*/ ) {
  9419. return this.paddedType;
  9420. }
  9421. /**
  9422. * The data type of the array elements.
  9423. *
  9424. * @param {NodeBuilder} builder - The current node builder.
  9425. * @return {string} The element type.
  9426. */
  9427. getElementType() {
  9428. return this.elementType;
  9429. }
  9430. /**
  9431. * Returns the padded type based on the element type.
  9432. *
  9433. * @return {string} The padded type.
  9434. */
  9435. getPaddedType() {
  9436. const elementType = this.elementType;
  9437. let paddedType = 'vec4';
  9438. if ( elementType === 'mat2' ) {
  9439. paddedType = 'mat2';
  9440. } else if ( /mat/.test( elementType ) === true ) {
  9441. paddedType = 'mat4';
  9442. } else if ( elementType.charAt( 0 ) === 'i' ) {
  9443. paddedType = 'ivec4';
  9444. } else if ( elementType.charAt( 0 ) === 'u' ) {
  9445. paddedType = 'uvec4';
  9446. }
  9447. return paddedType;
  9448. }
  9449. /**
  9450. * The update makes sure to correctly transfer the data from the (complex) objects
  9451. * in the array to the internal, correctly padded value buffer.
  9452. *
  9453. * @param {NodeFrame} frame - A reference to the current node frame.
  9454. */
  9455. update( /*frame*/ ) {
  9456. const { array, value } = this;
  9457. const elementType = this.elementType;
  9458. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  9459. for ( let i = 0; i < array.length; i ++ ) {
  9460. const index = i * 4;
  9461. value[ index ] = array[ i ];
  9462. }
  9463. } else if ( elementType === 'color' ) {
  9464. for ( let i = 0; i < array.length; i ++ ) {
  9465. const index = i * 4;
  9466. const vector = array[ i ];
  9467. value[ index ] = vector.r;
  9468. value[ index + 1 ] = vector.g;
  9469. value[ index + 2 ] = vector.b || 0;
  9470. //value[ index + 3 ] = vector.a || 0;
  9471. }
  9472. } else if ( elementType === 'mat2' ) {
  9473. for ( let i = 0; i < array.length; i ++ ) {
  9474. const index = i * 4;
  9475. const matrix = array[ i ];
  9476. value[ index ] = matrix.elements[ 0 ];
  9477. value[ index + 1 ] = matrix.elements[ 1 ];
  9478. value[ index + 2 ] = matrix.elements[ 2 ];
  9479. value[ index + 3 ] = matrix.elements[ 3 ];
  9480. }
  9481. } else if ( elementType === 'mat3' ) {
  9482. for ( let i = 0; i < array.length; i ++ ) {
  9483. const index = i * 16;
  9484. const matrix = array[ i ];
  9485. value[ index ] = matrix.elements[ 0 ];
  9486. value[ index + 1 ] = matrix.elements[ 1 ];
  9487. value[ index + 2 ] = matrix.elements[ 2 ];
  9488. value[ index + 4 ] = matrix.elements[ 3 ];
  9489. value[ index + 5 ] = matrix.elements[ 4 ];
  9490. value[ index + 6 ] = matrix.elements[ 5 ];
  9491. value[ index + 8 ] = matrix.elements[ 6 ];
  9492. value[ index + 9 ] = matrix.elements[ 7 ];
  9493. value[ index + 10 ] = matrix.elements[ 8 ];
  9494. value[ index + 15 ] = 1;
  9495. }
  9496. } else if ( elementType === 'mat4' ) {
  9497. for ( let i = 0; i < array.length; i ++ ) {
  9498. const index = i * 16;
  9499. const matrix = array[ i ];
  9500. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  9501. value[ index + i ] = matrix.elements[ i ];
  9502. }
  9503. }
  9504. } else {
  9505. for ( let i = 0; i < array.length; i ++ ) {
  9506. const index = i * 4;
  9507. const vector = array[ i ];
  9508. value[ index ] = vector.x;
  9509. value[ index + 1 ] = vector.y;
  9510. value[ index + 2 ] = vector.z || 0;
  9511. value[ index + 3 ] = vector.w || 0;
  9512. }
  9513. }
  9514. }
  9515. /**
  9516. * Implement the value buffer creation based on the array data.
  9517. *
  9518. * @param {NodeBuilder} builder - A reference to the current node builder.
  9519. * @return {null}
  9520. */
  9521. setup( builder ) {
  9522. const length = this.array.length;
  9523. const elementType = this.elementType;
  9524. let arrayType = Float32Array;
  9525. const paddedType = this.paddedType;
  9526. const paddedElementLength = builder.getTypeLength( paddedType );
  9527. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  9528. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  9529. this.value = new arrayType( length * paddedElementLength );
  9530. this.bufferCount = length;
  9531. this.bufferType = paddedType;
  9532. this.update(); // initialize the buffer values
  9533. return super.setup( builder );
  9534. }
  9535. /**
  9536. * Overwrites the default `element()` method to provide element access
  9537. * based on {@link UniformArrayNode}.
  9538. *
  9539. * @param {IndexNode} indexNode - The index node.
  9540. * @return {UniformArrayElementNode}
  9541. */
  9542. element( indexNode ) {
  9543. return new UniformArrayElementNode( this, nodeObject( indexNode ) );
  9544. }
  9545. }
  9546. /**
  9547. * TSL function for creating an uniform array node.
  9548. *
  9549. * @tsl
  9550. * @function
  9551. * @param {Array<any>} values - Array-like data.
  9552. * @param {?string} [nodeType] - The data type of the array elements.
  9553. * @returns {UniformArrayNode}
  9554. */
  9555. const uniformArray = ( values, nodeType ) => new UniformArrayNode( values, nodeType );
  9556. /**
  9557. * The node allows to set values for built-in shader variables. That is
  9558. * required for features like hardware-accelerated vertex clipping.
  9559. *
  9560. * @augments Node
  9561. */
  9562. class BuiltinNode extends Node {
  9563. /**
  9564. * Constructs a new builtin node.
  9565. *
  9566. * @param {string} name - The name of the built-in shader variable.
  9567. */
  9568. constructor( name ) {
  9569. super( 'float' );
  9570. /**
  9571. * The name of the built-in shader variable.
  9572. *
  9573. * @type {string}
  9574. */
  9575. this.name = name;
  9576. /**
  9577. * This flag can be used for type testing.
  9578. *
  9579. * @type {boolean}
  9580. * @readonly
  9581. * @default true
  9582. */
  9583. this.isBuiltinNode = true;
  9584. }
  9585. /**
  9586. * Generates the code snippet of the builtin node.
  9587. *
  9588. * @param {NodeBuilder} builder - The current node builder.
  9589. * @return {string} The generated code snippet.
  9590. */
  9591. generate( /* builder */ ) {
  9592. return this.name;
  9593. }
  9594. }
  9595. /**
  9596. * TSL function for creating a builtin node.
  9597. *
  9598. * @tsl
  9599. * @function
  9600. * @param {string} name - The name of the built-in shader variable.
  9601. * @returns {BuiltinNode}
  9602. */
  9603. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  9604. let _screenSizeVec, _viewportVec;
  9605. /**
  9606. * This node provides a collection of screen related metrics.
  9607. * Depending on {@link ScreenNode#scope}, the nodes can represent
  9608. * resolution or viewport data as well as fragment or uv coordinates.
  9609. *
  9610. * @augments Node
  9611. */
  9612. class ScreenNode extends Node {
  9613. static get type() {
  9614. return 'ScreenNode';
  9615. }
  9616. /**
  9617. * Constructs a new screen node.
  9618. *
  9619. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  9620. */
  9621. constructor( scope ) {
  9622. super();
  9623. /**
  9624. * The node represents different metric depending on which scope is selected.
  9625. *
  9626. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9627. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9628. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9629. * - `ScreenNode.UV`: Normalized coordinates.
  9630. * - `ScreenNode.DPR`: Device pixel ratio.
  9631. *
  9632. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9633. */
  9634. this.scope = scope;
  9635. /**
  9636. * This output node.
  9637. *
  9638. * @private
  9639. * @type {?Node}
  9640. * @default null
  9641. */
  9642. this._output = null;
  9643. /**
  9644. * This flag can be used for type testing.
  9645. *
  9646. * @type {boolean}
  9647. * @readonly
  9648. * @default true
  9649. */
  9650. this.isViewportNode = true;
  9651. }
  9652. /**
  9653. * This method is overwritten since the node type depends on the selected scope.
  9654. *
  9655. * @return {('float'|'vec2'|'vec4')} The node type.
  9656. */
  9657. generateNodeType() {
  9658. if ( this.scope === ScreenNode.DPR ) return 'float';
  9659. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9660. else return 'vec2';
  9661. }
  9662. /**
  9663. * This method is overwritten since the node's update type depends on the selected scope.
  9664. *
  9665. * @return {NodeUpdateType} The update type.
  9666. */
  9667. getUpdateType() {
  9668. let updateType = NodeUpdateType.NONE;
  9669. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9670. updateType = NodeUpdateType.RENDER;
  9671. }
  9672. this.updateType = updateType;
  9673. return updateType;
  9674. }
  9675. /**
  9676. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9677. * from the current renderer.
  9678. *
  9679. * @param {NodeFrame} frame - A reference to the current node frame.
  9680. */
  9681. update( { renderer } ) {
  9682. const renderTarget = renderer.getRenderTarget();
  9683. if ( this.scope === ScreenNode.VIEWPORT ) {
  9684. if ( renderTarget !== null ) {
  9685. _viewportVec.copy( renderTarget.viewport );
  9686. } else {
  9687. renderer.getViewport( _viewportVec );
  9688. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9689. }
  9690. } else if ( this.scope === ScreenNode.DPR ) {
  9691. this._output.value = renderer.getPixelRatio();
  9692. } else {
  9693. if ( renderTarget !== null ) {
  9694. _screenSizeVec.width = renderTarget.width;
  9695. _screenSizeVec.height = renderTarget.height;
  9696. } else {
  9697. renderer.getDrawingBufferSize( _screenSizeVec );
  9698. }
  9699. }
  9700. }
  9701. setup( /*builder*/ ) {
  9702. const scope = this.scope;
  9703. let output = null;
  9704. if ( scope === ScreenNode.SIZE ) {
  9705. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9706. } else if ( scope === ScreenNode.VIEWPORT ) {
  9707. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9708. } else if ( scope === ScreenNode.DPR ) {
  9709. output = uniform( 1 );
  9710. } else {
  9711. output = vec2( screenCoordinate.div( screenSize ) );
  9712. }
  9713. this._output = output;
  9714. return output;
  9715. }
  9716. generate( builder ) {
  9717. if ( this.scope === ScreenNode.COORDINATE ) {
  9718. let coord = builder.getFragCoord();
  9719. if ( builder.isFlipY() ) {
  9720. // follow webgpu standards
  9721. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9722. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9723. }
  9724. return coord;
  9725. }
  9726. return super.generate( builder );
  9727. }
  9728. }
  9729. ScreenNode.COORDINATE = 'coordinate';
  9730. ScreenNode.VIEWPORT = 'viewport';
  9731. ScreenNode.SIZE = 'size';
  9732. ScreenNode.UV = 'uv';
  9733. ScreenNode.DPR = 'dpr';
  9734. // Screen
  9735. /**
  9736. * TSL object that represents the current DPR.
  9737. *
  9738. * @tsl
  9739. * @type {ScreenNode<float>}
  9740. */
  9741. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9742. /**
  9743. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9744. *
  9745. * @tsl
  9746. * @type {ScreenNode<vec2>}
  9747. */
  9748. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9749. /**
  9750. * TSL object that represents the screen resolution in physical pixel units.
  9751. *
  9752. * @tsl
  9753. * @type {ScreenNode<vec2>}
  9754. */
  9755. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9756. /**
  9757. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9758. *
  9759. * @tsl
  9760. * @type {ScreenNode<vec2>}
  9761. */
  9762. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9763. // Viewport
  9764. /**
  9765. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9766. *
  9767. * @tsl
  9768. * @type {ScreenNode<vec4>}
  9769. */
  9770. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9771. /**
  9772. * TSL object that represents the viewport resolution in physical pixel units.
  9773. *
  9774. * @tsl
  9775. * @type {ScreenNode<vec2>}
  9776. */
  9777. const viewportSize = viewport.zw;
  9778. /**
  9779. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9780. *
  9781. * @tsl
  9782. * @type {ScreenNode<vec2>}
  9783. */
  9784. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9785. /**
  9786. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9787. *
  9788. * @tsl
  9789. * @type {ScreenNode<vec2>}
  9790. */
  9791. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9792. // Deprecated
  9793. /**
  9794. * @deprecated since r169. Use {@link screenSize} instead.
  9795. */
  9796. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9797. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.', new StackTrace() );
  9798. return screenSize;
  9799. }, 'vec2' ).once() )();
  9800. // Cache node uniforms
  9801. let _cameraProjectionMatrixBase = null;
  9802. let _cameraProjectionMatrixArray = null;
  9803. let _cameraProjectionMatrixInverseBase = null;
  9804. let _cameraProjectionMatrixInverseArray = null;
  9805. let _cameraViewMatrixBase = null;
  9806. let _cameraViewMatrixArray = null;
  9807. let _cameraWorldMatrixBase = null;
  9808. let _cameraWorldMatrixArray = null;
  9809. let _cameraNormalMatrixBase = null;
  9810. let _cameraNormalMatrixArray = null;
  9811. let _cameraPositionBase = null;
  9812. let _cameraPositionArray = null;
  9813. let _cameraViewportBase = null;
  9814. let _cameraViewportArray = null;
  9815. /**
  9816. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9817. *
  9818. * @tsl
  9819. * @type {UniformNode<uint>}
  9820. */
  9821. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9822. /**
  9823. * TSL object that represents the `near` value of the camera used for the current render.
  9824. *
  9825. * @tsl
  9826. * @type {UniformNode<float>}
  9827. */
  9828. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9829. /**
  9830. * TSL object that represents the `far` value of the camera used for the current render.
  9831. *
  9832. * @tsl
  9833. * @type {UniformNode<float>}
  9834. */
  9835. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9836. /**
  9837. * TSL object that represents the projection matrix of the camera used for the current render.
  9838. *
  9839. * @tsl
  9840. * @type {UniformNode<mat4>}
  9841. */
  9842. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9843. let cameraProjectionMatrix;
  9844. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9845. const matrices = [];
  9846. for ( const subCamera of camera.cameras ) {
  9847. matrices.push( subCamera.projectionMatrix );
  9848. }
  9849. if ( _cameraProjectionMatrixArray === null ) {
  9850. _cameraProjectionMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9851. } else {
  9852. _cameraProjectionMatrixArray.array = matrices;
  9853. }
  9854. cameraProjectionMatrix = _cameraProjectionMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9855. } else {
  9856. if ( _cameraProjectionMatrixBase === null ) {
  9857. _cameraProjectionMatrixBase = uniform( camera.projectionMatrix ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9858. }
  9859. cameraProjectionMatrix = _cameraProjectionMatrixBase;
  9860. }
  9861. return cameraProjectionMatrix;
  9862. } ).once() )();
  9863. /**
  9864. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9865. *
  9866. * @tsl
  9867. * @type {UniformNode<mat4>}
  9868. */
  9869. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9870. let cameraProjectionMatrixInverse;
  9871. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9872. const matrices = [];
  9873. for ( const subCamera of camera.cameras ) {
  9874. matrices.push( subCamera.projectionMatrixInverse );
  9875. }
  9876. if ( _cameraProjectionMatrixInverseArray === null ) {
  9877. _cameraProjectionMatrixInverseArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9878. } else {
  9879. _cameraProjectionMatrixInverseArray.array = matrices;
  9880. }
  9881. cameraProjectionMatrixInverse = _cameraProjectionMatrixInverseArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9882. } else {
  9883. if ( _cameraProjectionMatrixInverseBase === null ) {
  9884. _cameraProjectionMatrixInverseBase = uniform( camera.projectionMatrixInverse ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9885. }
  9886. cameraProjectionMatrixInverse = _cameraProjectionMatrixInverseBase;
  9887. }
  9888. return cameraProjectionMatrixInverse;
  9889. } ).once() )();
  9890. /**
  9891. * TSL object that represents the view matrix of the camera used for the current render.
  9892. *
  9893. * @tsl
  9894. * @type {UniformNode<mat4>}
  9895. */
  9896. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9897. let cameraViewMatrix;
  9898. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9899. const matrices = [];
  9900. for ( const subCamera of camera.cameras ) {
  9901. matrices.push( subCamera.matrixWorldInverse );
  9902. }
  9903. if ( _cameraViewMatrixArray === null ) {
  9904. _cameraViewMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9905. } else {
  9906. _cameraViewMatrixArray.array = matrices;
  9907. }
  9908. cameraViewMatrix = _cameraViewMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9909. } else {
  9910. if ( _cameraViewMatrixBase === null ) {
  9911. _cameraViewMatrixBase = uniform( camera.matrixWorldInverse ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9912. }
  9913. cameraViewMatrix = _cameraViewMatrixBase;
  9914. }
  9915. return cameraViewMatrix;
  9916. } ).once() )();
  9917. /**
  9918. * TSL object that represents the world matrix of the camera used for the current render.
  9919. *
  9920. * @tsl
  9921. * @type {UniformNode<mat4>}
  9922. */
  9923. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9924. let cameraWorldMatrix;
  9925. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9926. const matrices = [];
  9927. for ( const subCamera of camera.cameras ) {
  9928. matrices.push( subCamera.matrixWorld );
  9929. }
  9930. if ( _cameraWorldMatrixArray === null ) {
  9931. _cameraWorldMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9932. } else {
  9933. _cameraWorldMatrixArray.array = matrices;
  9934. }
  9935. cameraWorldMatrix = _cameraWorldMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9936. } else {
  9937. if ( _cameraWorldMatrixBase === null ) {
  9938. _cameraWorldMatrixBase = uniform( camera.matrixWorld ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9939. }
  9940. cameraWorldMatrix = _cameraWorldMatrixBase;
  9941. }
  9942. return cameraWorldMatrix;
  9943. } ).once() )();
  9944. /**
  9945. * TSL object that represents the normal matrix of the camera used for the current render.
  9946. *
  9947. * @tsl
  9948. * @type {UniformNode<mat3>}
  9949. */
  9950. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9951. let cameraNormalMatrix;
  9952. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9953. const matrices = [];
  9954. for ( const subCamera of camera.cameras ) {
  9955. matrices.push( subCamera.normalMatrix );
  9956. }
  9957. if ( _cameraNormalMatrixArray === null ) {
  9958. _cameraNormalMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9959. } else {
  9960. _cameraNormalMatrixArray.array = matrices;
  9961. }
  9962. cameraNormalMatrix = _cameraNormalMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9963. } else {
  9964. if ( _cameraNormalMatrixBase === null ) {
  9965. _cameraNormalMatrixBase = uniform( camera.normalMatrix ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9966. }
  9967. cameraNormalMatrix = _cameraNormalMatrixBase;
  9968. }
  9969. return cameraNormalMatrix;
  9970. } ).once() )();
  9971. /**
  9972. * TSL object that represents the position in world space of the camera used for the current render.
  9973. *
  9974. * @tsl
  9975. * @type {UniformNode<vec3>}
  9976. */
  9977. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9978. let cameraPosition;
  9979. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9980. const positions = [];
  9981. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9982. positions.push( new Vector3() );
  9983. }
  9984. if ( _cameraPositionArray === null ) {
  9985. _cameraPositionArray = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9986. const subCameras = camera.cameras;
  9987. const array = self.array;
  9988. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9989. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9990. }
  9991. } );
  9992. } else {
  9993. _cameraPositionArray.array = positions;
  9994. }
  9995. cameraPosition = _cameraPositionArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9996. } else {
  9997. if ( _cameraPositionBase === null ) {
  9998. _cameraPositionBase = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9999. }
  10000. cameraPosition = _cameraPositionBase;
  10001. }
  10002. return cameraPosition;
  10003. } ).once() )();
  10004. /**
  10005. * TSL object that represents the viewport of the camera used for the current render.
  10006. *
  10007. * @tsl
  10008. * @type {UniformNode<vec4>}
  10009. */
  10010. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  10011. let cameraViewport;
  10012. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  10013. const viewports = [];
  10014. for ( const subCamera of camera.cameras ) {
  10015. viewports.push( subCamera.viewport );
  10016. }
  10017. if ( _cameraViewportArray === null ) {
  10018. _cameraViewportArray = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  10019. } else {
  10020. _cameraViewportArray.array = viewports;
  10021. }
  10022. cameraViewport = _cameraViewportArray.element( cameraIndex ).toConst( 'cameraViewport' );
  10023. } else {
  10024. if ( _cameraViewportBase === null ) {
  10025. // Fallback for single camera
  10026. _cameraViewportBase = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  10027. }
  10028. cameraViewport = _cameraViewportBase;
  10029. }
  10030. return cameraViewport;
  10031. } ).once() )();
  10032. const _sphere = /*@__PURE__*/ new Sphere();
  10033. /**
  10034. * This node can be used to access transformation related metrics of 3D objects.
  10035. * Depending on the selected scope, a different metric is represented as a uniform
  10036. * in the shader. The following scopes are supported:
  10037. *
  10038. * - `POSITION`: The object's position in world space.
  10039. * - `VIEW_POSITION`: The object's position in view/camera space.
  10040. * - `DIRECTION`: The object's direction in world space.
  10041. * - `SCALE`: The object's scale in world space.
  10042. * - `WORLD_MATRIX`: The object's matrix in world space.
  10043. *
  10044. * @augments Node
  10045. */
  10046. class Object3DNode extends Node {
  10047. static get type() {
  10048. return 'Object3DNode';
  10049. }
  10050. /**
  10051. * Constructs a new object 3D node.
  10052. *
  10053. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  10054. * @param {?Object3D} [object3d=null] - The 3D object.
  10055. */
  10056. constructor( scope, object3d = null ) {
  10057. super();
  10058. /**
  10059. * The node reports a different type of transformation depending on the scope.
  10060. *
  10061. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  10062. */
  10063. this.scope = scope;
  10064. /**
  10065. * The 3D object.
  10066. *
  10067. * @type {?Object3D}
  10068. * @default null
  10069. */
  10070. this.object3d = object3d;
  10071. /**
  10072. * Overwritten since this type of node is updated per object.
  10073. *
  10074. * @type {string}
  10075. * @default 'object'
  10076. */
  10077. this.updateType = NodeUpdateType.OBJECT;
  10078. /**
  10079. * Holds the value of the node as a uniform.
  10080. *
  10081. * @type {UniformNode}
  10082. */
  10083. this.uniformNode = new UniformNode( null );
  10084. }
  10085. /**
  10086. * Overwritten since the node type is inferred from the scope.
  10087. *
  10088. * @return {('mat4'|'vec3'|'float')} The node type.
  10089. */
  10090. generateNodeType() {
  10091. const scope = this.scope;
  10092. if ( scope === Object3DNode.WORLD_MATRIX ) {
  10093. return 'mat4';
  10094. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  10095. return 'vec3';
  10096. } else if ( scope === Object3DNode.RADIUS ) {
  10097. return 'float';
  10098. }
  10099. }
  10100. /**
  10101. * Updates the uniform value depending on the scope.
  10102. *
  10103. * @param {NodeFrame} frame - The current node frame.
  10104. */
  10105. update( frame ) {
  10106. const object = this.object3d;
  10107. const uniformNode = this.uniformNode;
  10108. const scope = this.scope;
  10109. if ( scope === Object3DNode.WORLD_MATRIX ) {
  10110. uniformNode.value = object.matrixWorld;
  10111. } else if ( scope === Object3DNode.POSITION ) {
  10112. uniformNode.value = uniformNode.value || new Vector3();
  10113. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  10114. } else if ( scope === Object3DNode.SCALE ) {
  10115. uniformNode.value = uniformNode.value || new Vector3();
  10116. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  10117. } else if ( scope === Object3DNode.DIRECTION ) {
  10118. uniformNode.value = uniformNode.value || new Vector3();
  10119. object.getWorldDirection( uniformNode.value );
  10120. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  10121. const camera = frame.camera;
  10122. uniformNode.value = uniformNode.value || new Vector3();
  10123. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  10124. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  10125. } else if ( scope === Object3DNode.RADIUS ) {
  10126. const geometry = frame.object.geometry;
  10127. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10128. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  10129. uniformNode.value = _sphere.radius;
  10130. }
  10131. }
  10132. /**
  10133. * Generates the code snippet of the uniform node. The node type of the uniform
  10134. * node also depends on the selected scope.
  10135. *
  10136. * @param {NodeBuilder} builder - The current node builder.
  10137. * @return {string} The generated code snippet.
  10138. */
  10139. generate( builder ) {
  10140. const scope = this.scope;
  10141. if ( scope === Object3DNode.WORLD_MATRIX ) {
  10142. this.uniformNode.nodeType = 'mat4';
  10143. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  10144. this.uniformNode.nodeType = 'vec3';
  10145. } else if ( scope === Object3DNode.RADIUS ) {
  10146. this.uniformNode.nodeType = 'float';
  10147. }
  10148. return this.uniformNode.build( builder );
  10149. }
  10150. serialize( data ) {
  10151. super.serialize( data );
  10152. data.scope = this.scope;
  10153. }
  10154. deserialize( data ) {
  10155. super.deserialize( data );
  10156. this.scope = data.scope;
  10157. }
  10158. }
  10159. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  10160. Object3DNode.POSITION = 'position';
  10161. Object3DNode.SCALE = 'scale';
  10162. Object3DNode.VIEW_POSITION = 'viewPosition';
  10163. Object3DNode.DIRECTION = 'direction';
  10164. Object3DNode.RADIUS = 'radius';
  10165. /**
  10166. * TSL function for creating an object 3D node that represents the object's direction in world space.
  10167. *
  10168. * @tsl
  10169. * @function
  10170. * @param {?Object3D} [object3d] - The 3D object.
  10171. * @returns {Object3DNode<vec3>}
  10172. */
  10173. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  10174. /**
  10175. * TSL function for creating an object 3D node that represents the object's world matrix.
  10176. *
  10177. * @tsl
  10178. * @function
  10179. * @param {?Object3D} [object3d] - The 3D object.
  10180. * @returns {Object3DNode<mat4>}
  10181. */
  10182. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  10183. /**
  10184. * TSL function for creating an object 3D node that represents the object's position in world space.
  10185. *
  10186. * @tsl
  10187. * @function
  10188. * @param {?Object3D} [object3d] - The 3D object.
  10189. * @returns {Object3DNode<vec3>}
  10190. */
  10191. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  10192. /**
  10193. * TSL function for creating an object 3D node that represents the object's scale in world space.
  10194. *
  10195. * @tsl
  10196. * @function
  10197. * @param {?Object3D} [object3d] - The 3D object.
  10198. * @returns {Object3DNode<vec3>}
  10199. */
  10200. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  10201. /**
  10202. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  10203. *
  10204. * @tsl
  10205. * @function
  10206. * @param {?Object3D} [object3d] - The 3D object.
  10207. * @returns {Object3DNode<vec3>}
  10208. */
  10209. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  10210. /**
  10211. * TSL function for creating an object 3D node that represents the object's radius.
  10212. *
  10213. * @tsl
  10214. * @function
  10215. * @param {?Object3D} [object3d] - The 3D object.
  10216. * @returns {Object3DNode<float>}
  10217. */
  10218. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  10219. /**
  10220. * This type of node is a specialized version of `Object3DNode`
  10221. * with larger set of model related metrics. Unlike `Object3DNode`,
  10222. * `ModelNode` extracts the reference to the 3D object from the
  10223. * current node frame state.
  10224. *
  10225. * @augments Object3DNode
  10226. */
  10227. class ModelNode extends Object3DNode {
  10228. static get type() {
  10229. return 'ModelNode';
  10230. }
  10231. /**
  10232. * Constructs a new object model node.
  10233. *
  10234. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  10235. */
  10236. constructor( scope ) {
  10237. super( scope );
  10238. }
  10239. /**
  10240. * Extracts the model reference from the frame state and then
  10241. * updates the uniform value depending on the scope.
  10242. *
  10243. * @param {NodeFrame} frame - The current node frame.
  10244. */
  10245. update( frame ) {
  10246. this.object3d = frame.object;
  10247. super.update( frame );
  10248. }
  10249. }
  10250. /**
  10251. * TSL object that represents the object's direction in world space.
  10252. *
  10253. * @tsl
  10254. * @type {ModelNode<vec3>}
  10255. */
  10256. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  10257. /**
  10258. * TSL object that represents the object's world matrix.
  10259. *
  10260. * @tsl
  10261. * @type {ModelNode<mat4>}
  10262. */
  10263. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  10264. /**
  10265. * TSL object that represents the object's position in world space.
  10266. *
  10267. * @tsl
  10268. * @type {ModelNode<vec3>}
  10269. */
  10270. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  10271. /**
  10272. * TSL object that represents the object's scale in world space.
  10273. *
  10274. * @tsl
  10275. * @type {ModelNode<vec3>}
  10276. */
  10277. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  10278. /**
  10279. * TSL object that represents the object's position in view/camera space.
  10280. *
  10281. * @tsl
  10282. * @type {ModelNode<vec3>}
  10283. */
  10284. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  10285. /**
  10286. * TSL object that represents the object's radius.
  10287. *
  10288. * @tsl
  10289. * @type {ModelNode<float>}
  10290. */
  10291. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  10292. /**
  10293. * TSL object that represents the object's normal matrix.
  10294. *
  10295. * @tsl
  10296. * @type {UniformNode<mat3>}
  10297. */
  10298. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  10299. /**
  10300. * TSL object that represents the object's inverse world matrix.
  10301. *
  10302. * @tsl
  10303. * @type {UniformNode<mat4>}
  10304. */
  10305. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  10306. /**
  10307. * TSL object that represents the object's model view matrix.
  10308. *
  10309. * @tsl
  10310. * @type {Node<mat4>}
  10311. */
  10312. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10313. return builder.context.modelViewMatrix || mediumpModelViewMatrix;
  10314. } ).once() )().toVar( 'modelViewMatrix' );
  10315. // GPU Precision
  10316. /**
  10317. * TSL object that represents the object's model view in `mediump` precision.
  10318. *
  10319. * @tsl
  10320. * @type {Node<mat4>}
  10321. */
  10322. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  10323. // CPU Precision
  10324. /**
  10325. * TSL object that represents the object's model view in `highp` precision
  10326. * which is achieved by computing the matrix in JS and not in the shader.
  10327. *
  10328. * @tsl
  10329. * @type {Node<mat4>}
  10330. */
  10331. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10332. builder.context.isHighPrecisionModelViewMatrix = true;
  10333. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  10334. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  10335. } );
  10336. } ).once() )().toVar( 'highpModelViewMatrix' );
  10337. /**
  10338. * TSL object that represents the object's model normal view in `highp` precision
  10339. * which is achieved by computing the matrix in JS and not in the shader.
  10340. *
  10341. * @tsl
  10342. * @type {Node<mat3>}
  10343. */
  10344. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10345. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  10346. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  10347. if ( isHighPrecisionModelViewMatrix !== true ) {
  10348. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  10349. }
  10350. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  10351. } );
  10352. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  10353. /**
  10354. * TSL object that represents the clip space position of the current rendered object.
  10355. *
  10356. * @tsl
  10357. * @type {VaryingNode<vec4>}
  10358. */
  10359. const clipSpace = /*@__PURE__*/ ( Fn( ( builder ) => {
  10360. if ( builder.shaderStage !== 'fragment' ) {
  10361. warnOnce( 'TSL: `clipSpace` is only available in fragment stage.' );
  10362. return vec4();
  10363. }
  10364. return builder.context.clipSpace.toVarying( 'v_clipSpace' );
  10365. } ).once() )();
  10366. /**
  10367. * TSL object that represents the position attribute of the current rendered object.
  10368. *
  10369. * @tsl
  10370. * @type {AttributeNode<vec3>}
  10371. */
  10372. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  10373. /**
  10374. * TSL object that represents the vertex position in local space of the current rendered object.
  10375. *
  10376. * @tsl
  10377. * @type {AttributeNode<vec3>}
  10378. */
  10379. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  10380. /**
  10381. * TSL object that represents the previous vertex position in local space of the current rendered object.
  10382. * Used in context of {@link VelocityNode} for rendering motion vectors.
  10383. *
  10384. * @tsl
  10385. * @type {AttributeNode<vec3>}
  10386. */
  10387. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  10388. /**
  10389. * TSL object that represents the vertex position in world space of the current rendered object.
  10390. *
  10391. * @tsl
  10392. * @type {VaryingNode<vec3>}
  10393. */
  10394. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  10395. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  10396. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10397. /**
  10398. * TSL object that represents the position world direction of the current rendered object.
  10399. *
  10400. * @tsl
  10401. * @type {Node<vec3>}
  10402. */
  10403. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  10404. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  10405. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  10406. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10407. /**
  10408. * TSL object that represents the vertex position in view space of the current rendered object.
  10409. *
  10410. * @tsl
  10411. * @type {VaryingNode<vec3>}
  10412. */
  10413. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  10414. if ( builder.shaderStage === 'fragment' && builder.material.vertexNode ) {
  10415. // reconstruct view position from clip space
  10416. const viewPos = cameraProjectionMatrixInverse.mul( clipSpace );
  10417. return viewPos.xyz.div( viewPos.w ).toVar( 'positionView' );
  10418. }
  10419. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  10420. }, 'vec3' ).once( [ 'POSITION', 'VERTEX' ] ) )();
  10421. /**
  10422. * TSL object that represents the position view direction of the current rendered object.
  10423. *
  10424. * @tsl
  10425. * @type {VaryingNode<vec3>}
  10426. */
  10427. const positionViewDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10428. let output;
  10429. if ( builder.camera.isOrthographicCamera ) {
  10430. output = vec3( 0, 0, 1 );
  10431. } else {
  10432. output = positionView.negate().toVarying( 'v_positionViewDirection' ).normalize();
  10433. }
  10434. return output.toVar( 'positionViewDirection' );
  10435. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10436. /**
  10437. * This node can be used to evaluate whether a primitive is front or back facing.
  10438. *
  10439. * @augments Node
  10440. */
  10441. class FrontFacingNode extends Node {
  10442. static get type() {
  10443. return 'FrontFacingNode';
  10444. }
  10445. /**
  10446. * Constructs a new front facing node.
  10447. */
  10448. constructor() {
  10449. super( 'bool' );
  10450. /**
  10451. * This flag can be used for type testing.
  10452. *
  10453. * @type {boolean}
  10454. * @readonly
  10455. * @default true
  10456. */
  10457. this.isFrontFacingNode = true;
  10458. }
  10459. generate( builder ) {
  10460. if ( builder.shaderStage !== 'fragment' ) return 'true';
  10461. //
  10462. const { material } = builder;
  10463. if ( material.side === BackSide ) {
  10464. return 'false';
  10465. }
  10466. return builder.getFrontFacing();
  10467. }
  10468. }
  10469. /**
  10470. * TSL object that represents whether a primitive is front or back facing
  10471. *
  10472. * @tsl
  10473. * @type {FrontFacingNode<bool>}
  10474. */
  10475. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  10476. /**
  10477. * TSL object that represents the front facing status as a number instead of a bool.
  10478. * `1` means front facing, `-1` means back facing.
  10479. *
  10480. * @tsl
  10481. * @type {Node<float>}
  10482. */
  10483. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  10484. /**
  10485. * Converts a direction vector to a face direction vector based on the material's side.
  10486. *
  10487. * If the material is set to `BackSide`, the direction is inverted.
  10488. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  10489. *
  10490. * @tsl
  10491. * @param {Node<vec3>} direction - The direction vector to convert.
  10492. * @returns {Node<vec3>} The converted direction vector.
  10493. */
  10494. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  10495. const side = material.side;
  10496. if ( side === BackSide ) {
  10497. direction = direction.mul( -1 );
  10498. } else if ( side === DoubleSide ) {
  10499. direction = direction.mul( faceDirection );
  10500. }
  10501. return direction;
  10502. } );
  10503. /**
  10504. * TSL object that represents the normal attribute of the current rendered object in local space.
  10505. *
  10506. * @tsl
  10507. * @type {Node<vec3>}
  10508. */
  10509. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  10510. /**
  10511. * TSL object that represents the vertex normal of the current rendered object in local space.
  10512. *
  10513. * @tsl
  10514. * @type {Node<vec3>}
  10515. */
  10516. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  10517. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  10518. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  10519. return vec3( 0, 1, 0 );
  10520. }
  10521. return normalGeometry;
  10522. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  10523. /**
  10524. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  10525. *
  10526. * @tsl
  10527. * @type {Node<vec3>}
  10528. */
  10529. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  10530. /**
  10531. * TSL object that represents the vertex normal of the current rendered object in view space.
  10532. *
  10533. * @tsl
  10534. * @type {Node<vec3>}
  10535. */
  10536. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10537. let node;
  10538. if ( builder.isFlatShading() ) {
  10539. node = normalFlat;
  10540. } else {
  10541. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  10542. }
  10543. return node;
  10544. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  10545. /**
  10546. * TSL object that represents the vertex normal of the current rendered object in world space.
  10547. *
  10548. * @tsl
  10549. * @type {Node<vec3>}
  10550. */
  10551. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10552. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  10553. if ( builder.isFlatShading() !== true ) {
  10554. normal = normal.toVarying( 'v_normalWorldGeometry' );
  10555. }
  10556. return normal.normalize().toVar( 'normalWorldGeometry' );
  10557. }, 'vec3' ).once() )();
  10558. /**
  10559. * TSL object that represents the vertex normal of the current rendered object in view space.
  10560. *
  10561. * @tsl
  10562. * @type {Node<vec3>}
  10563. */
  10564. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  10565. let node;
  10566. if ( builder.subBuildFn === 'NORMAL' || builder.subBuildFn === 'VERTEX' ) {
  10567. node = normalViewGeometry;
  10568. if ( builder.isFlatShading() !== true ) {
  10569. node = directionToFaceDirection( node );
  10570. }
  10571. } else {
  10572. // Use custom context to avoid side effects from nodes overwriting getUV, getTextureLevel in the context (e.g. EnvironmentNode)
  10573. node = builder.context.setupNormal().context( { getUV: null, getTextureLevel: null } );
  10574. }
  10575. return node;
  10576. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  10577. /**
  10578. * TSL object that represents the vertex normal of the current rendered object in world space.
  10579. *
  10580. * @tsl
  10581. * @type {Node<vec3>}
  10582. */
  10583. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  10584. /**
  10585. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  10586. *
  10587. * @tsl
  10588. * @type {Node<vec3>}
  10589. */
  10590. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  10591. let node;
  10592. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10593. node = normalView;
  10594. } else {
  10595. // Use custom context to avoid side effects from nodes overwriting getUV, getTextureLevel in the context (e.g. EnvironmentNode)
  10596. node = context.setupClearcoatNormal().context( { getUV: null, getTextureLevel: null } );
  10597. }
  10598. return node;
  10599. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  10600. /**
  10601. * Transforms the normal with the given matrix.
  10602. *
  10603. * @tsl
  10604. * @function
  10605. * @param {Node<vec3>} normal - The normal.
  10606. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  10607. * @return {Node<vec3>} The transformed normal.
  10608. */
  10609. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  10610. const m = mat3( matrix );
  10611. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  10612. return m.mul( transformedNormal ).xyz;
  10613. } );
  10614. /**
  10615. * Transforms the given normal from local to view space.
  10616. *
  10617. * @tsl
  10618. * @function
  10619. * @param {Node<vec3>} normal - The normal.
  10620. * @param {NodeBuilder} builder - The current node builder.
  10621. * @return {Node<vec3>} The transformed normal.
  10622. */
  10623. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  10624. const modelNormalViewMatrix = builder.context.modelNormalViewMatrix;
  10625. if ( modelNormalViewMatrix ) {
  10626. return modelNormalViewMatrix.transformDirection( normal );
  10627. }
  10628. //
  10629. const transformedNormal = modelNormalMatrix.mul( normal );
  10630. return cameraViewMatrix.transformDirection( transformedNormal );
  10631. } );
  10632. // Deprecated
  10633. /**
  10634. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  10635. *
  10636. * @tsl
  10637. * @type {Node<vec3>}
  10638. * @deprecated since r178. Use `normalView` instead.
  10639. */
  10640. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  10641. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  10642. return normalView;
  10643. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10644. /**
  10645. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  10646. *
  10647. * @tsl
  10648. * @type {Node<vec3>}
  10649. * @deprecated since r178. Use `normalWorld` instead.
  10650. */
  10651. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  10652. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  10653. return normalWorld;
  10654. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10655. /**
  10656. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  10657. *
  10658. * @tsl
  10659. * @type {Node<vec3>}
  10660. * @deprecated since r178. Use `clearcoatNormalView` instead.
  10661. */
  10662. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  10663. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  10664. return clearcoatNormalView;
  10665. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10666. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10667. /**
  10668. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  10669. *
  10670. * @tsl
  10671. * @type {UniformNode<float>}
  10672. */
  10673. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  10674. /**
  10675. * TSL object that represents the intensity of environment maps of PBR materials.
  10676. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  10677. *
  10678. * @tsl
  10679. * @type {Node<float>}
  10680. */
  10681. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  10682. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  10683. } );
  10684. /**
  10685. * TSL object that represents the rotation of environment maps.
  10686. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  10687. * rotation of `scene.environment` instead.
  10688. *
  10689. * @tsl
  10690. * @type {Node<mat4>}
  10691. */
  10692. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  10693. return frame.material;
  10694. } ).onObjectUpdate( function ( { material, scene } ) {
  10695. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10696. if ( rotation ) {
  10697. // note: since the matrix is orthonormal, we can use the more-efficient transpose() in lieu of invert()
  10698. _m1$1.makeRotationFromEuler( rotation ).transpose();
  10699. } else {
  10700. _m1$1.identity();
  10701. }
  10702. return _m1$1;
  10703. } );
  10704. /**
  10705. * The reflect vector in view space.
  10706. *
  10707. * @tsl
  10708. * @type {Node<vec3>}
  10709. */
  10710. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  10711. /**
  10712. * The refract vector in view space.
  10713. *
  10714. * @tsl
  10715. * @type {Node<vec3>}
  10716. */
  10717. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10718. /**
  10719. * Used for sampling cube maps when using cube reflection mapping.
  10720. *
  10721. * @tsl
  10722. * @type {Node<vec3>}
  10723. */
  10724. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10725. /**
  10726. * Used for sampling cube maps when using cube refraction mapping.
  10727. *
  10728. * @tsl
  10729. * @type {Node<vec3>}
  10730. */
  10731. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10732. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  10733. /**
  10734. * This type of uniform node represents a cube texture.
  10735. *
  10736. * @augments TextureNode
  10737. */
  10738. class CubeTextureNode extends TextureNode {
  10739. static get type() {
  10740. return 'CubeTextureNode';
  10741. }
  10742. /**
  10743. * Constructs a new cube texture node.
  10744. *
  10745. * @param {CubeTexture} value - The cube texture.
  10746. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10747. * @param {?Node<int>} [levelNode=null] - The level node.
  10748. * @param {?Node<float>} [biasNode=null] - The bias node.
  10749. */
  10750. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10751. super( value, uvNode, levelNode, biasNode );
  10752. /**
  10753. * This flag can be used for type testing.
  10754. *
  10755. * @type {boolean}
  10756. * @readonly
  10757. * @default true
  10758. */
  10759. this.isCubeTextureNode = true;
  10760. }
  10761. /**
  10762. * Overwrites the default implementation to return the appropriate cube texture type.
  10763. *
  10764. * @param {NodeBuilder} builder - The current node builder.
  10765. * @return {string} The input type.
  10766. */
  10767. getInputType( /*builder*/ ) {
  10768. if ( this.value.isDepthTexture === true ) {
  10769. return 'cubeDepthTexture';
  10770. }
  10771. return 'cubeTexture';
  10772. }
  10773. /**
  10774. * Returns a default uvs based on the mapping type of the cube texture.
  10775. *
  10776. * @return {Node<vec3>} The default uv attribute.
  10777. */
  10778. getDefaultUV() {
  10779. const texture = this.value;
  10780. if ( texture.mapping === CubeReflectionMapping ) {
  10781. return reflectVector;
  10782. } else if ( texture.mapping === CubeRefractionMapping ) {
  10783. return refractVector;
  10784. } else {
  10785. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10786. return vec3( 0, 0, 0 );
  10787. }
  10788. }
  10789. /**
  10790. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10791. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10792. *
  10793. * @param {boolean} value - The update toggle.
  10794. */
  10795. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10796. /**
  10797. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10798. * to modify the uv node for correct sampling.
  10799. *
  10800. * @param {NodeBuilder} builder - The current node builder.
  10801. * @param {Node} uvNode - The uv node to setup.
  10802. * @return {Node} The updated uv node.
  10803. */
  10804. setupUV( builder, uvNode ) {
  10805. const texture = this.value;
  10806. // Depth textures (shadow maps) - no environment rotation, Y flip for WebGPU
  10807. if ( texture.isDepthTexture === true ) {
  10808. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  10809. return vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  10810. }
  10811. return uvNode;
  10812. }
  10813. // rotate first
  10814. uvNode = materialEnvRotation.mul( uvNode );
  10815. // flip
  10816. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10817. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10818. }
  10819. return uvNode;
  10820. }
  10821. /**
  10822. * Generates the uv code snippet.
  10823. *
  10824. * @param {NodeBuilder} builder - The current node builder.
  10825. * @param {Node} cubeUV - The uv node to generate code for.
  10826. * @return {string} The generated code snippet.
  10827. */
  10828. generateUV( builder, cubeUV ) {
  10829. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10830. }
  10831. }
  10832. /**
  10833. * TSL function for creating a cube texture node.
  10834. *
  10835. * @tsl
  10836. * @function
  10837. * @param {CubeTexture} value - The cube texture.
  10838. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10839. * @param {?Node<int>} [levelNode=null] - The level node.
  10840. * @param {?Node<float>} [biasNode=null] - The bias node.
  10841. * @returns {CubeTextureNode}
  10842. */
  10843. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10844. /**
  10845. * TSL function for creating a cube texture uniform node.
  10846. *
  10847. * @tsl
  10848. * @function
  10849. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10850. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10851. * @param {?Node<int>} [levelNode=null] - The level node.
  10852. * @param {?Node<float>} [biasNode=null] - The bias node.
  10853. * @returns {CubeTextureNode}
  10854. */
  10855. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10856. let textureNode;
  10857. if ( value && value.isCubeTextureNode === true ) {
  10858. textureNode = nodeObject( value.clone() );
  10859. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10860. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10861. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10862. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10863. } else {
  10864. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10865. }
  10866. return textureNode;
  10867. };
  10868. /**
  10869. * TSL function for creating a uniform cube texture node.
  10870. *
  10871. * @tsl
  10872. * @function
  10873. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10874. * @returns {CubeTextureNode}
  10875. */
  10876. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10877. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  10878. /**
  10879. * This class is only relevant if the referenced property is array-like.
  10880. * In this case, `ReferenceElementNode` allows to refer to a specific
  10881. * element inside the data structure via an index.
  10882. *
  10883. * @augments ArrayElementNode
  10884. */
  10885. class ReferenceElementNode extends ArrayElementNode {
  10886. static get type() {
  10887. return 'ReferenceElementNode';
  10888. }
  10889. /**
  10890. * Constructs a new reference element node.
  10891. *
  10892. * @param {?ReferenceNode} referenceNode - The reference node.
  10893. * @param {Node} indexNode - The index node that defines the element access.
  10894. */
  10895. constructor( referenceNode, indexNode ) {
  10896. super( referenceNode, indexNode );
  10897. /**
  10898. * Similar to {@link ReferenceNode#reference}, an additional
  10899. * property references to the current node.
  10900. *
  10901. * @type {?ReferenceNode}
  10902. * @default null
  10903. */
  10904. this.referenceNode = referenceNode;
  10905. /**
  10906. * This flag can be used for type testing.
  10907. *
  10908. * @type {boolean}
  10909. * @readonly
  10910. * @default true
  10911. */
  10912. this.isReferenceElementNode = true;
  10913. }
  10914. /**
  10915. * This method is overwritten since the node type is inferred from
  10916. * the uniform type of the reference node.
  10917. *
  10918. * @return {string} The node type.
  10919. */
  10920. generateNodeType() {
  10921. return this.referenceNode.uniformType;
  10922. }
  10923. generate( builder ) {
  10924. const snippet = super.generate( builder );
  10925. const arrayType = this.referenceNode.getNodeType( builder );
  10926. const elementType = this.getNodeType( builder );
  10927. return builder.format( snippet, arrayType, elementType );
  10928. }
  10929. }
  10930. /**
  10931. * This type of node establishes a reference to a property of another object.
  10932. * In this way, the value of the node is automatically linked to the value of
  10933. * referenced object. Reference nodes internally represent the linked value
  10934. * as a uniform.
  10935. *
  10936. * @augments Node
  10937. */
  10938. class ReferenceNode extends Node {
  10939. static get type() {
  10940. return 'ReferenceNode';
  10941. }
  10942. /**
  10943. * Constructs a new reference node.
  10944. *
  10945. * @param {string} property - The name of the property the node refers to.
  10946. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10947. * @param {?Object} [object=null] - The object the property belongs to.
  10948. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10949. */
  10950. constructor( property, uniformType, object = null, count = null ) {
  10951. super();
  10952. /**
  10953. * The name of the property the node refers to.
  10954. *
  10955. * @type {string}
  10956. */
  10957. this.property = property;
  10958. /**
  10959. * The uniform type that should be used to represent the property value.
  10960. *
  10961. * @type {string}
  10962. */
  10963. this.uniformType = uniformType;
  10964. /**
  10965. * The object the property belongs to.
  10966. *
  10967. * @type {?Object}
  10968. * @default null
  10969. */
  10970. this.object = object;
  10971. /**
  10972. * When the linked property is an array, this parameter defines its length.
  10973. *
  10974. * @type {?number}
  10975. * @default null
  10976. */
  10977. this.count = count;
  10978. /**
  10979. * The property name might have dots so nested properties can be referred.
  10980. * The hierarchy of the names is stored inside this array.
  10981. *
  10982. * @type {Array<string>}
  10983. */
  10984. this.properties = property.split( '.' );
  10985. /**
  10986. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10987. * since the final reference might be updated from calling code.
  10988. *
  10989. * @type {?Object}
  10990. * @default null
  10991. */
  10992. this.reference = object;
  10993. /**
  10994. * The uniform node that holds the value of the reference node.
  10995. *
  10996. * @type {UniformNode}
  10997. * @default null
  10998. */
  10999. this.node = null;
  11000. /**
  11001. * The uniform group of the internal uniform.
  11002. *
  11003. * @type {UniformGroupNode}
  11004. * @default null
  11005. */
  11006. this.group = null;
  11007. /**
  11008. * An optional label of the internal uniform node.
  11009. *
  11010. * @type {?string}
  11011. * @default null
  11012. */
  11013. this.name = null;
  11014. /**
  11015. * Overwritten since reference nodes are updated per object.
  11016. *
  11017. * @type {string}
  11018. * @default 'object'
  11019. */
  11020. this.updateType = NodeUpdateType.OBJECT;
  11021. }
  11022. /**
  11023. * When the referred property is array-like, this method can be used
  11024. * to access elements via an index node.
  11025. *
  11026. * @param {IndexNode} indexNode - indexNode.
  11027. * @return {ReferenceElementNode} A reference to an element.
  11028. */
  11029. element( indexNode ) {
  11030. return new ReferenceElementNode( this, nodeObject( indexNode ) );
  11031. }
  11032. /**
  11033. * Sets the uniform group for this reference node.
  11034. *
  11035. * @param {UniformGroupNode} group - The uniform group to set.
  11036. * @return {ReferenceNode} A reference to this node.
  11037. */
  11038. setGroup( group ) {
  11039. this.group = group;
  11040. return this;
  11041. }
  11042. /**
  11043. * Sets the name for the internal uniform.
  11044. *
  11045. * @param {string} name - The label to set.
  11046. * @return {ReferenceNode} A reference to this node.
  11047. */
  11048. setName( name ) {
  11049. this.name = name;
  11050. return this;
  11051. }
  11052. /**
  11053. * Sets the label for the internal uniform.
  11054. *
  11055. * @deprecated
  11056. * @param {string} name - The label to set.
  11057. * @return {ReferenceNode} A reference to this node.
  11058. */
  11059. label( name ) {
  11060. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  11061. return this.setName( name );
  11062. }
  11063. /**
  11064. * Sets the node type which automatically defines the internal
  11065. * uniform type.
  11066. *
  11067. * @param {string} uniformType - The type to set.
  11068. */
  11069. setNodeType( uniformType ) {
  11070. let node = null;
  11071. if ( this.count !== null ) {
  11072. node = buffer( null, uniformType, this.count );
  11073. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  11074. node = uniformArray( null, uniformType );
  11075. } else if ( uniformType === 'texture' ) {
  11076. node = texture( null );
  11077. } else if ( uniformType === 'cubeTexture' ) {
  11078. node = cubeTexture( null );
  11079. } else {
  11080. node = uniform( null, uniformType );
  11081. }
  11082. if ( this.group !== null ) {
  11083. node.setGroup( this.group );
  11084. }
  11085. if ( this.name !== null ) node.setName( this.name );
  11086. this.node = node;
  11087. }
  11088. /**
  11089. * This method is overwritten since the node type is inferred from
  11090. * the type of the reference node.
  11091. *
  11092. * @param {NodeBuilder} builder - The current node builder.
  11093. * @return {string} The node type.
  11094. */
  11095. generateNodeType( builder ) {
  11096. if ( this.node === null ) {
  11097. this.updateReference( builder );
  11098. this.updateValue();
  11099. }
  11100. return this.node.getNodeType( builder );
  11101. }
  11102. /**
  11103. * Returns the property value from the given referred object.
  11104. *
  11105. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  11106. * @return {any} The value.
  11107. */
  11108. getValueFromReference( object = this.reference ) {
  11109. const { properties } = this;
  11110. let value = object[ properties[ 0 ] ];
  11111. for ( let i = 1; i < properties.length; i ++ ) {
  11112. value = value[ properties[ i ] ];
  11113. }
  11114. return value;
  11115. }
  11116. /**
  11117. * Allows to update the reference based on the given state. The state is only
  11118. * evaluated {@link ReferenceNode#object} is not set.
  11119. *
  11120. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  11121. * @return {Object} The updated reference.
  11122. */
  11123. updateReference( state ) {
  11124. this.reference = this.object !== null ? this.object : state.object;
  11125. return this.reference;
  11126. }
  11127. /**
  11128. * The output of the reference node is the internal uniform node.
  11129. *
  11130. * @param {NodeBuilder} builder - The current node builder.
  11131. * @return {UniformNode} The output node.
  11132. */
  11133. setup( /* builder */ ) {
  11134. this.updateValue();
  11135. return this.node;
  11136. }
  11137. /**
  11138. * Overwritten to update the internal uniform value.
  11139. *
  11140. * @param {NodeFrame} frame - A reference to the current node frame.
  11141. */
  11142. update( /*frame*/ ) {
  11143. this.updateValue();
  11144. }
  11145. /**
  11146. * Retrieves the value from the referred object property and uses it
  11147. * to updated the internal uniform.
  11148. */
  11149. updateValue() {
  11150. if ( this.node === null ) this.setNodeType( this.uniformType );
  11151. const value = this.getValueFromReference();
  11152. if ( Array.isArray( value ) ) {
  11153. this.node.array = value;
  11154. } else {
  11155. this.node.value = value;
  11156. }
  11157. }
  11158. }
  11159. /**
  11160. * TSL function for creating a reference node.
  11161. *
  11162. * @tsl
  11163. * @function
  11164. * @param {string} name - The name of the property the node refers to.
  11165. * @param {string} type - The uniform type that should be used to represent the property value.
  11166. * @param {?Object} [object] - The object the property belongs to.
  11167. * @returns {ReferenceNode}
  11168. */
  11169. const reference = ( name, type, object ) => new ReferenceNode( name, type, object );
  11170. /**
  11171. * TSL function for creating a reference node. Use this function if you want need a reference
  11172. * to an array-like property that should be represented as a uniform buffer.
  11173. *
  11174. * @tsl
  11175. * @function
  11176. * @param {string} name - The name of the property the node refers to.
  11177. * @param {string} type - The uniform type that should be used to represent the property value.
  11178. * @param {number} count - The number of value inside the array-like object.
  11179. * @param {Object} object - An array-like object the property belongs to.
  11180. * @returns {ReferenceNode}
  11181. */
  11182. const referenceBuffer = ( name, type, count, object ) => new ReferenceNode( name, type, object, count );
  11183. /**
  11184. * This node is a special type of reference node which is intended
  11185. * for linking material properties with node values.
  11186. * ```js
  11187. * const opacityNode = materialReference( 'opacity', 'float', material );
  11188. * ```
  11189. * When changing `material.opacity`, the node value of `opacityNode` will
  11190. * automatically be updated.
  11191. *
  11192. * @augments ReferenceNode
  11193. */
  11194. class MaterialReferenceNode extends ReferenceNode {
  11195. static get type() {
  11196. return 'MaterialReferenceNode';
  11197. }
  11198. /**
  11199. * Constructs a new material reference node.
  11200. *
  11201. * @param {string} property - The name of the property the node refers to.
  11202. * @param {string} inputType - The uniform type that should be used to represent the property value.
  11203. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  11204. * the node refers to the material of the current rendered object.
  11205. */
  11206. constructor( property, inputType, material = null ) {
  11207. super( property, inputType, material );
  11208. /**
  11209. * The material the property belongs to. When no material is set,
  11210. * the node refers to the material of the current rendered object.
  11211. *
  11212. * @type {?Material}
  11213. * @default null
  11214. */
  11215. this.material = material;
  11216. /**
  11217. * This flag can be used for type testing.
  11218. *
  11219. * @type {boolean}
  11220. * @readonly
  11221. * @default true
  11222. */
  11223. this.isMaterialReferenceNode = true;
  11224. }
  11225. /**
  11226. * Updates the reference based on the given state. The state is only evaluated
  11227. * {@link MaterialReferenceNode#material} is not set.
  11228. *
  11229. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  11230. * @return {Object} The updated reference.
  11231. */
  11232. updateReference( state ) {
  11233. this.reference = this.material !== null ? this.material : state.material;
  11234. return this.reference;
  11235. }
  11236. }
  11237. /**
  11238. * TSL function for creating a material reference node.
  11239. *
  11240. * @tsl
  11241. * @function
  11242. * @param {string} name - The name of the property the node refers to.
  11243. * @param {string} type - The uniform type that should be used to represent the property value.
  11244. * @param {?Material} [material=null] - The material the property belongs to.
  11245. * When no material is set, the node refers to the material of the current rendered object.
  11246. * @returns {MaterialReferenceNode}
  11247. */
  11248. const materialReference = ( name, type, material = null ) => new MaterialReferenceNode( name, type, material );
  11249. // Normal Mapping Without Precomputed Tangents
  11250. // http://www.thetenthplanet.de/archives/1180
  11251. const uv = uv$1();
  11252. const q0 = positionView.dFdx();
  11253. const q1 = positionView.dFdy();
  11254. const st0 = uv.dFdx();
  11255. const st1 = uv.dFdy();
  11256. const N = normalView;
  11257. const q1perp = q1.cross( N );
  11258. const q0perp = N.cross( q0 );
  11259. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  11260. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  11261. const det = T.dot( T ).max( B.dot( B ) );
  11262. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  11263. /**
  11264. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  11265. * Useful for normal mapping without precomputed tangents.
  11266. *
  11267. * Reference: http://www.thetenthplanet.de/archives/1180
  11268. *
  11269. * @tsl
  11270. * @type {Node<vec3>}
  11271. */
  11272. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  11273. /**
  11274. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  11275. * Complements the tangentViewFrame for constructing the tangent space basis.
  11276. *
  11277. * Reference: http://www.thetenthplanet.de/archives/1180
  11278. *
  11279. * @tsl
  11280. * @type {Node<vec3>}
  11281. */
  11282. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  11283. /**
  11284. * TSL object that represents the tangent attribute of the current rendered object.
  11285. *
  11286. * @tsl
  11287. * @type {Node<vec4>}
  11288. */
  11289. const tangentGeometry = /*@__PURE__*/ attribute( 'tangent', 'vec4' );
  11290. /**
  11291. * TSL object that represents the vertex tangent in local space of the current rendered object.
  11292. *
  11293. * @tsl
  11294. * @type {Node<vec3>}
  11295. */
  11296. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  11297. /**
  11298. * TSL object that represents the vertex tangent in view space of the current rendered object.
  11299. *
  11300. * @tsl
  11301. * @type {Node<vec3>}
  11302. */
  11303. const tangentView = /*@__PURE__*/ ( Fn( ( builder ) => {
  11304. let node;
  11305. if ( builder.subBuildFn === 'VERTEX' || builder.geometry.hasAttribute( 'tangent' ) ) {
  11306. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  11307. } else {
  11308. node = tangentViewFrame;
  11309. }
  11310. if ( builder.isFlatShading() !== true ) {
  11311. node = directionToFaceDirection( node );
  11312. }
  11313. return node;
  11314. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  11315. /**
  11316. * TSL object that represents the vertex tangent in world space of the current rendered object.
  11317. *
  11318. * @tsl
  11319. * @type {Node<vec3>}
  11320. */
  11321. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  11322. /**
  11323. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  11324. *
  11325. * @tsl
  11326. * @private
  11327. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  11328. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  11329. * @returns {Node<vec3>} The bitangent node.
  11330. */
  11331. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], builder ) => {
  11332. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  11333. if ( builder.subBuildFn === 'NORMAL' && builder.isFlatShading() !== true ) {
  11334. bitangent = bitangent.toVarying( varyingName );
  11335. }
  11336. return bitangent;
  11337. } ).once( [ 'NORMAL' ] );
  11338. /**
  11339. * TSL object that represents the bitangent attribute of the current rendered object.
  11340. *
  11341. * @tsl
  11342. * @type {Node<vec3>}
  11343. */
  11344. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  11345. /**
  11346. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  11347. *
  11348. * @tsl
  11349. * @type {Node<vec3>}
  11350. */
  11351. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  11352. /**
  11353. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  11354. *
  11355. * @tsl
  11356. * @type {Node<vec3>}
  11357. */
  11358. const bitangentView = /*@__PURE__*/ ( Fn( ( builder ) => {
  11359. let node;
  11360. if ( builder.subBuildFn === 'VERTEX' || builder.geometry.hasAttribute( 'tangent' ) ) {
  11361. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  11362. } else {
  11363. node = bitangentViewFrame;
  11364. }
  11365. if ( builder.isFlatShading() !== true ) {
  11366. node = directionToFaceDirection( node );
  11367. }
  11368. return node;
  11369. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  11370. /**
  11371. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  11372. *
  11373. * @tsl
  11374. * @type {Node<vec3>}
  11375. */
  11376. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  11377. /**
  11378. * TSL object that represents the TBN matrix in view space.
  11379. *
  11380. * @tsl
  11381. * @type {Node<mat3>}
  11382. */
  11383. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  11384. /**
  11385. * TSL object that represents the parallax direction.
  11386. *
  11387. * @tsl
  11388. * @type {Node<mat3>}
  11389. */
  11390. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  11391. /**
  11392. * TSL function for computing parallax uv coordinates.
  11393. *
  11394. * @tsl
  11395. * @function
  11396. * @param {Node<vec2>} uv - A uv node.
  11397. * @param {Node<vec2>} scale - A scale node.
  11398. * @returns {Node<vec2>} Parallax uv coordinates.
  11399. */
  11400. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  11401. /**
  11402. * TSL function for computing bent normals.
  11403. *
  11404. * @tsl
  11405. * @function
  11406. * @returns {Node<vec3>} Bent normals.
  11407. */
  11408. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  11409. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  11410. let bentNormal = anisotropyB.cross( positionViewDirection );
  11411. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  11412. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  11413. return bentNormal;
  11414. } ).once() )();
  11415. /**
  11416. * Packs a direction vector into a color value.
  11417. *
  11418. * @tsl
  11419. * @function
  11420. * @param {Node<vec3>} node - The direction to pack.
  11421. * @return {Node<vec3>} The color.
  11422. */
  11423. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  11424. /**
  11425. * Unpacks a color value into a direction vector.
  11426. *
  11427. * @tsl
  11428. * @function
  11429. * @param {Node<vec3>} node - The color to unpack.
  11430. * @return {Node<vec3>} The direction.
  11431. */
  11432. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  11433. /**
  11434. * Unpacks a tangent space normal, reconstructing the Z component by projecting the X,Y coordinates onto the hemisphere.
  11435. * The X,Y coordinates are expected to be in the [-1, 1] range.
  11436. *
  11437. * @tsl
  11438. * @function
  11439. * @param {Node<vec2>} xy - The X,Y coordinates of the normal.
  11440. * @return {Node<vec3>} The resulting normal.
  11441. */
  11442. const unpackNormal = ( xy ) => vec3( xy, sqrt( saturate( float( 1.0 ).sub( dot( xy, xy ) ) ) ) );
  11443. /**
  11444. * This class can be used for applying normals maps to materials.
  11445. *
  11446. * ```js
  11447. * material.normalNode = normalMap( texture( normalTex ) );
  11448. * ```
  11449. *
  11450. * @augments TempNode
  11451. */
  11452. class NormalMapNode extends TempNode {
  11453. static get type() {
  11454. return 'NormalMapNode';
  11455. }
  11456. /**
  11457. * Constructs a new normal map node.
  11458. *
  11459. * @param {Node<vec3>} node - Represents the normal map data.
  11460. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11461. */
  11462. constructor( node, scaleNode = null ) {
  11463. super( 'vec3' );
  11464. /**
  11465. * Represents the normal map data.
  11466. *
  11467. * @type {Node<vec3>}
  11468. */
  11469. this.node = node;
  11470. /**
  11471. * Controls the intensity of the effect.
  11472. *
  11473. * @type {?Node<vec2>}
  11474. * @default null
  11475. */
  11476. this.scaleNode = scaleNode;
  11477. /**
  11478. * The normal map type.
  11479. *
  11480. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  11481. * @default TangentSpaceNormalMap
  11482. */
  11483. this.normalMapType = TangentSpaceNormalMap;
  11484. /**
  11485. * Controls how to unpack the sampled normal map values.
  11486. *
  11487. * @type {string}
  11488. * @default NoNormalPacking
  11489. */
  11490. this.unpackNormalMode = NoNormalPacking;
  11491. }
  11492. setup( builder ) {
  11493. const { normalMapType, scaleNode, unpackNormalMode } = this;
  11494. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  11495. if ( normalMapType === TangentSpaceNormalMap ) {
  11496. if ( unpackNormalMode === NormalRGPacking ) {
  11497. normalMap = unpackNormal( normalMap.xy );
  11498. } else if ( unpackNormalMode === NormalGAPacking ) {
  11499. normalMap = unpackNormal( normalMap.yw );
  11500. } else if ( unpackNormalMode !== NoNormalPacking ) {
  11501. error( `THREE.NodeMaterial: Unexpected unpack normal mode: ${ unpackNormalMode }` );
  11502. }
  11503. } else {
  11504. if ( unpackNormalMode !== NoNormalPacking ) {
  11505. error( `THREE.NodeMaterial: Normal map type '${ normalMapType }' is not compatible with unpack normal mode '${ unpackNormalMode }'` );
  11506. }
  11507. }
  11508. if ( scaleNode !== null ) {
  11509. let scale = scaleNode;
  11510. if ( builder.isFlatShading() === true ) {
  11511. scale = directionToFaceDirection( scale );
  11512. }
  11513. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  11514. }
  11515. let output = null;
  11516. if ( normalMapType === ObjectSpaceNormalMap ) {
  11517. output = transformNormalToView( normalMap );
  11518. } else if ( normalMapType === TangentSpaceNormalMap ) {
  11519. output = TBNViewMatrix.mul( normalMap ).normalize();
  11520. } else {
  11521. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  11522. output = normalView; // Fallback to default normal view
  11523. }
  11524. return output;
  11525. }
  11526. }
  11527. /**
  11528. * TSL function for creating a normal map node.
  11529. *
  11530. * @tsl
  11531. * @function
  11532. * @param {Node<vec3>} node - Represents the normal map data.
  11533. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11534. * @returns {NormalMapNode}
  11535. */
  11536. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  11537. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  11538. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  11539. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  11540. // It's used to preserve the same TextureNode instance
  11541. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  11542. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  11543. return vec2(
  11544. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  11545. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  11546. ).mul( bumpScale );
  11547. } );
  11548. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  11549. const perturbNormalArb = Fn( ( inputs ) => {
  11550. const { surf_pos, surf_norm, dHdxy } = inputs;
  11551. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  11552. const vSigmaX = surf_pos.dFdx().normalize();
  11553. const vSigmaY = surf_pos.dFdy().normalize();
  11554. const vN = surf_norm; // normalized
  11555. const R1 = vSigmaY.cross( vN );
  11556. const R2 = vN.cross( vSigmaX );
  11557. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  11558. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  11559. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  11560. } );
  11561. /**
  11562. * This class can be used for applying bump maps to materials.
  11563. *
  11564. * ```js
  11565. * material.normalNode = bumpMap( texture( bumpTex ) );
  11566. * ```
  11567. *
  11568. * @augments TempNode
  11569. */
  11570. class BumpMapNode extends TempNode {
  11571. static get type() {
  11572. return 'BumpMapNode';
  11573. }
  11574. /**
  11575. * Constructs a new bump map node.
  11576. *
  11577. * @param {Node<float>} textureNode - Represents the bump map data.
  11578. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11579. */
  11580. constructor( textureNode, scaleNode = null ) {
  11581. super( 'vec3' );
  11582. /**
  11583. * Represents the bump map data.
  11584. *
  11585. * @type {Node<float>}
  11586. */
  11587. this.textureNode = textureNode;
  11588. /**
  11589. * Controls the intensity of the bump effect.
  11590. *
  11591. * @type {?Node<float>}
  11592. * @default null
  11593. */
  11594. this.scaleNode = scaleNode;
  11595. }
  11596. setup() {
  11597. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  11598. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  11599. return perturbNormalArb( {
  11600. surf_pos: positionView,
  11601. surf_norm: normalView,
  11602. dHdxy
  11603. } );
  11604. }
  11605. }
  11606. /**
  11607. * TSL function for creating a bump map node.
  11608. *
  11609. * @tsl
  11610. * @function
  11611. * @param {Node<float>} textureNode - Represents the bump map data.
  11612. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11613. * @returns {BumpMapNode}
  11614. */
  11615. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  11616. const _propertyCache = new Map();
  11617. /**
  11618. * This class should simplify the node access to material properties.
  11619. * It internal uses reference nodes to make sure changes to material
  11620. * properties are automatically reflected to predefined TSL objects
  11621. * like e.g. `materialColor`.
  11622. *
  11623. * @augments Node
  11624. */
  11625. class MaterialNode extends Node {
  11626. static get type() {
  11627. return 'MaterialNode';
  11628. }
  11629. /**
  11630. * Constructs a new material node.
  11631. *
  11632. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  11633. */
  11634. constructor( scope ) {
  11635. super();
  11636. /**
  11637. * The scope defines what material property is referred by the node.
  11638. *
  11639. * @type {string}
  11640. */
  11641. this.scope = scope;
  11642. }
  11643. /**
  11644. * Returns a cached reference node for the given property and type.
  11645. *
  11646. * @param {string} property - The name of the material property.
  11647. * @param {string} type - The uniform type of the property.
  11648. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11649. */
  11650. getCache( property, type ) {
  11651. let node = _propertyCache.get( property );
  11652. if ( node === undefined ) {
  11653. node = materialReference( property, type );
  11654. _propertyCache.set( property, node );
  11655. }
  11656. return node;
  11657. }
  11658. /**
  11659. * Returns a float-typed material reference node for the given property name.
  11660. *
  11661. * @param {string} property - The name of the material property.
  11662. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  11663. */
  11664. getFloat( property ) {
  11665. return this.getCache( property, 'float' );
  11666. }
  11667. /**
  11668. * Returns a color-typed material reference node for the given property name.
  11669. *
  11670. * @param {string} property - The name of the material property.
  11671. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  11672. */
  11673. getColor( property ) {
  11674. return this.getCache( property, 'color' );
  11675. }
  11676. /**
  11677. * Returns a texture-typed material reference node for the given property name.
  11678. *
  11679. * @param {string} property - The name of the material property.
  11680. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11681. */
  11682. getTexture( property ) {
  11683. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  11684. }
  11685. /**
  11686. * The node setup is done depending on the selected scope. Multiple material properties
  11687. * might be grouped into a single node composition if they logically belong together.
  11688. *
  11689. * @param {NodeBuilder} builder - The current node builder.
  11690. * @return {Node} The node representing the selected scope.
  11691. */
  11692. setup( builder ) {
  11693. const material = builder.context.material;
  11694. const scope = this.scope;
  11695. let node = null;
  11696. if ( scope === MaterialNode.COLOR ) {
  11697. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  11698. if ( material.map && material.map.isTexture === true ) {
  11699. node = colorNode.mul( this.getTexture( 'map' ) );
  11700. } else {
  11701. node = colorNode;
  11702. }
  11703. } else if ( scope === MaterialNode.OPACITY ) {
  11704. const opacityNode = this.getFloat( scope );
  11705. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  11706. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  11707. } else {
  11708. node = opacityNode;
  11709. }
  11710. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  11711. if ( material.specularMap && material.specularMap.isTexture === true ) {
  11712. node = this.getTexture( 'specular' ).r;
  11713. } else {
  11714. node = float( 1 );
  11715. }
  11716. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  11717. const specularIntensityNode = this.getFloat( scope );
  11718. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  11719. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  11720. } else {
  11721. node = specularIntensityNode;
  11722. }
  11723. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  11724. const specularColorNode = this.getColor( scope );
  11725. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  11726. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  11727. } else {
  11728. node = specularColorNode;
  11729. }
  11730. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  11731. const roughnessNode = this.getFloat( scope );
  11732. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  11733. node = roughnessNode.mul( this.getTexture( scope ).g );
  11734. } else {
  11735. node = roughnessNode;
  11736. }
  11737. } else if ( scope === MaterialNode.METALNESS ) {
  11738. const metalnessNode = this.getFloat( scope );
  11739. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  11740. node = metalnessNode.mul( this.getTexture( scope ).b );
  11741. } else {
  11742. node = metalnessNode;
  11743. }
  11744. } else if ( scope === MaterialNode.EMISSIVE ) {
  11745. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  11746. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  11747. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  11748. node = emissiveNode.mul( this.getTexture( scope ) );
  11749. } else {
  11750. node = emissiveNode;
  11751. }
  11752. } else if ( scope === MaterialNode.NORMAL ) {
  11753. if ( material.normalMap ) {
  11754. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  11755. node.normalMapType = material.normalMapType;
  11756. if ( material.normalMap.format == RGFormat || material.normalMap.format == RED_GREEN_RGTC2_Format || material.normalMap.format == RG11_EAC_Format ) {
  11757. node.unpackNormalMode = NormalRGPacking;
  11758. }
  11759. } else if ( material.bumpMap ) {
  11760. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  11761. } else {
  11762. node = normalView;
  11763. }
  11764. } else if ( scope === MaterialNode.CLEARCOAT ) {
  11765. const clearcoatNode = this.getFloat( scope );
  11766. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  11767. node = clearcoatNode.mul( this.getTexture( scope ).r );
  11768. } else {
  11769. node = clearcoatNode;
  11770. }
  11771. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  11772. const clearcoatRoughnessNode = this.getFloat( scope );
  11773. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  11774. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  11775. } else {
  11776. node = clearcoatRoughnessNode;
  11777. }
  11778. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  11779. if ( material.clearcoatNormalMap ) {
  11780. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  11781. } else {
  11782. node = normalView;
  11783. }
  11784. } else if ( scope === MaterialNode.SHEEN ) {
  11785. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  11786. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  11787. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  11788. } else {
  11789. node = sheenNode;
  11790. }
  11791. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  11792. const sheenRoughnessNode = this.getFloat( scope );
  11793. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  11794. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  11795. } else {
  11796. node = sheenRoughnessNode;
  11797. }
  11798. node = node.clamp( 0.0001, 1.0 );
  11799. } else if ( scope === MaterialNode.ANISOTROPY ) {
  11800. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  11801. const anisotropyPolar = this.getTexture( scope );
  11802. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  11803. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  11804. } else {
  11805. node = materialAnisotropyVector;
  11806. }
  11807. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  11808. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  11809. if ( material.iridescenceThicknessMap ) {
  11810. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  11811. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  11812. } else {
  11813. node = iridescenceThicknessMaximum;
  11814. }
  11815. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11816. const transmissionNode = this.getFloat( scope );
  11817. if ( material.transmissionMap ) {
  11818. node = transmissionNode.mul( this.getTexture( scope ).r );
  11819. } else {
  11820. node = transmissionNode;
  11821. }
  11822. } else if ( scope === MaterialNode.THICKNESS ) {
  11823. const thicknessNode = this.getFloat( scope );
  11824. if ( material.thicknessMap ) {
  11825. node = thicknessNode.mul( this.getTexture( scope ).g );
  11826. } else {
  11827. node = thicknessNode;
  11828. }
  11829. } else if ( scope === MaterialNode.IOR ) {
  11830. node = this.getFloat( scope );
  11831. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11832. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11833. } else if ( scope === MaterialNode.AO ) {
  11834. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11835. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11836. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11837. } else {
  11838. const outputType = this.getNodeType( builder );
  11839. node = this.getCache( scope, outputType );
  11840. }
  11841. return node;
  11842. }
  11843. }
  11844. MaterialNode.ALPHA_TEST = 'alphaTest';
  11845. MaterialNode.COLOR = 'color';
  11846. MaterialNode.OPACITY = 'opacity';
  11847. MaterialNode.SHININESS = 'shininess';
  11848. MaterialNode.SPECULAR = 'specular';
  11849. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11850. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11851. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11852. MaterialNode.REFLECTIVITY = 'reflectivity';
  11853. MaterialNode.ROUGHNESS = 'roughness';
  11854. MaterialNode.METALNESS = 'metalness';
  11855. MaterialNode.NORMAL = 'normal';
  11856. MaterialNode.CLEARCOAT = 'clearcoat';
  11857. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11858. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11859. MaterialNode.EMISSIVE = 'emissive';
  11860. MaterialNode.ROTATION = 'rotation';
  11861. MaterialNode.SHEEN = 'sheen';
  11862. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11863. MaterialNode.ANISOTROPY = 'anisotropy';
  11864. MaterialNode.IRIDESCENCE = 'iridescence';
  11865. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11866. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11867. MaterialNode.IOR = 'ior';
  11868. MaterialNode.TRANSMISSION = 'transmission';
  11869. MaterialNode.THICKNESS = 'thickness';
  11870. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11871. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11872. MaterialNode.LINE_SCALE = 'scale';
  11873. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11874. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11875. MaterialNode.LINE_WIDTH = 'linewidth';
  11876. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11877. MaterialNode.POINT_SIZE = 'size';
  11878. MaterialNode.DISPERSION = 'dispersion';
  11879. MaterialNode.LIGHT_MAP = 'light';
  11880. MaterialNode.AO = 'ao';
  11881. /**
  11882. * TSL object that represents alpha test of the current material.
  11883. *
  11884. * @tsl
  11885. * @type {Node<float>}
  11886. */
  11887. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11888. /**
  11889. * TSL object that represents the diffuse color of the current material.
  11890. * The value is composed via `color` * `map`.
  11891. *
  11892. * @tsl
  11893. * @type {Node<vec3>}
  11894. */
  11895. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11896. /**
  11897. * TSL object that represents the shininess of the current material.
  11898. *
  11899. * @tsl
  11900. * @type {Node<float>}
  11901. */
  11902. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11903. /**
  11904. * TSL object that represents the emissive color of the current material.
  11905. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11906. *
  11907. * @tsl
  11908. * @type {Node<vec3>}
  11909. */
  11910. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  11911. /**
  11912. * TSL object that represents the opacity of the current material.
  11913. * The value is composed via `opacity` * `alphaMap`.
  11914. *
  11915. * @tsl
  11916. * @type {Node<float>}
  11917. */
  11918. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  11919. /**
  11920. * TSL object that represents the specular of the current material.
  11921. *
  11922. * @tsl
  11923. * @type {Node<vec3>}
  11924. */
  11925. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  11926. /**
  11927. * TSL object that represents the specular intensity of the current material.
  11928. * The value is composed via `specularIntensity` * `specularMap.a`.
  11929. *
  11930. * @tsl
  11931. * @type {Node<float>}
  11932. */
  11933. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  11934. /**
  11935. * TSL object that represents the specular color of the current material.
  11936. * The value is composed via `specularColor` * `specularMap.rgb`.
  11937. *
  11938. * @tsl
  11939. * @type {Node<vec3>}
  11940. */
  11941. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  11942. /**
  11943. * TSL object that represents the specular strength of the current material.
  11944. * The value is composed via `specularMap.r`.
  11945. *
  11946. * @tsl
  11947. * @type {Node<float>}
  11948. */
  11949. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  11950. /**
  11951. * TSL object that represents the reflectivity of the current material.
  11952. *
  11953. * @tsl
  11954. * @type {Node<float>}
  11955. */
  11956. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  11957. /**
  11958. * TSL object that represents the roughness of the current material.
  11959. * The value is composed via `roughness` * `roughnessMap.g`.
  11960. *
  11961. * @tsl
  11962. * @type {Node<float>}
  11963. */
  11964. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  11965. /**
  11966. * TSL object that represents the metalness of the current material.
  11967. * The value is composed via `metalness` * `metalnessMap.b`.
  11968. *
  11969. * @tsl
  11970. * @type {Node<float>}
  11971. */
  11972. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  11973. /**
  11974. * TSL object that represents the normal of the current material.
  11975. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  11976. *
  11977. * @tsl
  11978. * @type {Node<vec3>}
  11979. */
  11980. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11981. /**
  11982. * TSL object that represents the clearcoat of the current material.
  11983. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11984. *
  11985. * @tsl
  11986. * @type {Node<float>}
  11987. */
  11988. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11989. /**
  11990. * TSL object that represents the clearcoat roughness of the current material.
  11991. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11992. *
  11993. * @tsl
  11994. * @type {Node<float>}
  11995. */
  11996. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11997. /**
  11998. * TSL object that represents the clearcoat normal of the current material.
  11999. * The value will be either `clearcoatNormalMap` or `normalView`.
  12000. *
  12001. * @tsl
  12002. * @type {Node<vec3>}
  12003. */
  12004. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  12005. /**
  12006. * TSL object that represents the rotation of the current sprite material.
  12007. *
  12008. * @tsl
  12009. * @type {Node<float>}
  12010. */
  12011. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  12012. /**
  12013. * TSL object that represents the sheen color of the current material.
  12014. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  12015. *
  12016. * @tsl
  12017. * @type {Node<vec3>}
  12018. */
  12019. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  12020. /**
  12021. * TSL object that represents the sheen roughness of the current material.
  12022. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  12023. *
  12024. * @tsl
  12025. * @type {Node<float>}
  12026. */
  12027. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  12028. /**
  12029. * TSL object that represents the anisotropy of the current material.
  12030. *
  12031. * @tsl
  12032. * @type {Node<vec2>}
  12033. */
  12034. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  12035. /**
  12036. * TSL object that represents the iridescence of the current material.
  12037. *
  12038. * @tsl
  12039. * @type {Node<float>}
  12040. */
  12041. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  12042. /**
  12043. * TSL object that represents the iridescence IOR of the current material.
  12044. *
  12045. * @tsl
  12046. * @type {Node<float>}
  12047. */
  12048. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  12049. /**
  12050. * TSL object that represents the iridescence thickness of the current material.
  12051. *
  12052. * @tsl
  12053. * @type {Node<float>}
  12054. */
  12055. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  12056. /**
  12057. * TSL object that represents the transmission of the current material.
  12058. * The value is composed via `transmission` * `transmissionMap.r`.
  12059. *
  12060. * @tsl
  12061. * @type {Node<float>}
  12062. */
  12063. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  12064. /**
  12065. * TSL object that represents the thickness of the current material.
  12066. * The value is composed via `thickness` * `thicknessMap.g`.
  12067. *
  12068. * @tsl
  12069. * @type {Node<float>}
  12070. */
  12071. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  12072. /**
  12073. * TSL object that represents the IOR of the current material.
  12074. *
  12075. * @tsl
  12076. * @type {Node<float>}
  12077. */
  12078. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  12079. /**
  12080. * TSL object that represents the attenuation distance of the current material.
  12081. *
  12082. * @tsl
  12083. * @type {Node<float>}
  12084. */
  12085. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  12086. /**
  12087. * TSL object that represents the attenuation color of the current material.
  12088. *
  12089. * @tsl
  12090. * @type {Node<vec3>}
  12091. */
  12092. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  12093. /**
  12094. * TSL object that represents the scale of the current dashed line material.
  12095. *
  12096. * @tsl
  12097. * @type {Node<float>}
  12098. */
  12099. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  12100. /**
  12101. * TSL object that represents the dash size of the current dashed line material.
  12102. *
  12103. * @tsl
  12104. * @type {Node<float>}
  12105. */
  12106. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  12107. /**
  12108. * TSL object that represents the gap size of the current dashed line material.
  12109. *
  12110. * @tsl
  12111. * @type {Node<float>}
  12112. */
  12113. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  12114. /**
  12115. * TSL object that represents the line width of the current line material.
  12116. *
  12117. * @tsl
  12118. * @type {Node<float>}
  12119. */
  12120. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  12121. /**
  12122. * TSL object that represents the dash offset of the current line material.
  12123. *
  12124. * @tsl
  12125. * @type {Node<float>}
  12126. */
  12127. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  12128. /**
  12129. * TSL object that represents the point size of the current points material.
  12130. *
  12131. * @tsl
  12132. * @type {Node<float>}
  12133. */
  12134. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  12135. /**
  12136. * TSL object that represents the dispersion of the current material.
  12137. *
  12138. * @tsl
  12139. * @type {Node<float>}
  12140. */
  12141. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  12142. /**
  12143. * TSL object that represents the light map of the current material.
  12144. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  12145. *
  12146. * @tsl
  12147. * @type {Node<vec3>}
  12148. */
  12149. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  12150. /**
  12151. * TSL object that represents the ambient occlusion map of the current material.
  12152. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  12153. *
  12154. * @tsl
  12155. * @type {Node<float>}
  12156. */
  12157. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  12158. /**
  12159. * TSL object that represents the anisotropy vector of the current material.
  12160. *
  12161. * @tsl
  12162. * @type {Node<vec2>}
  12163. */
  12164. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  12165. return frame.material;
  12166. } ).onRenderUpdate( function ( { material } ) {
  12167. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  12168. } );
  12169. /**
  12170. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  12171. *
  12172. * @tsl
  12173. * @type {VaryingNode<vec4>}
  12174. */
  12175. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  12176. return builder.context.setupModelViewProjection();
  12177. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  12178. /**
  12179. * This class enables element access on instances of {@link StorageBufferNode}.
  12180. * In most cases, it is indirectly used when accessing elements with the
  12181. * {@link StorageBufferNode#element} method.
  12182. *
  12183. * ```js
  12184. * const position = positionStorage.element( instanceIndex );
  12185. * ```
  12186. *
  12187. * @augments ArrayElementNode
  12188. */
  12189. class StorageArrayElementNode extends ArrayElementNode {
  12190. static get type() {
  12191. return 'StorageArrayElementNode';
  12192. }
  12193. /**
  12194. * Constructs storage buffer element node.
  12195. *
  12196. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  12197. * @param {Node} indexNode - The index node that defines the element access.
  12198. */
  12199. constructor( storageBufferNode, indexNode ) {
  12200. super( storageBufferNode, indexNode );
  12201. /**
  12202. * This flag can be used for type testing.
  12203. *
  12204. * @type {boolean}
  12205. * @readonly
  12206. * @default true
  12207. */
  12208. this.isStorageArrayElementNode = true;
  12209. }
  12210. /**
  12211. * The storage buffer node.
  12212. *
  12213. * @param {Node} value
  12214. * @type {StorageBufferNode}
  12215. */
  12216. set storageBufferNode( value ) {
  12217. this.node = value;
  12218. }
  12219. get storageBufferNode() {
  12220. return this.node;
  12221. }
  12222. getMemberType( builder, name ) {
  12223. const structTypeNode = this.storageBufferNode.structTypeNode;
  12224. if ( structTypeNode ) {
  12225. return structTypeNode.getMemberType( builder, name );
  12226. }
  12227. return 'void';
  12228. }
  12229. setup( builder ) {
  12230. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  12231. if ( this.node.isPBO === true ) {
  12232. builder.setupPBO( this.node );
  12233. }
  12234. }
  12235. return super.setup( builder );
  12236. }
  12237. generate( builder, output ) {
  12238. let snippet;
  12239. const isAssignContext = builder.context.assign;
  12240. //
  12241. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  12242. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  12243. snippet = builder.generatePBO( this );
  12244. } else {
  12245. snippet = this.node.build( builder );
  12246. }
  12247. } else {
  12248. snippet = super.generate( builder );
  12249. }
  12250. if ( isAssignContext !== true ) {
  12251. const type = this.getNodeType( builder );
  12252. snippet = builder.format( snippet, type, output );
  12253. }
  12254. return snippet;
  12255. }
  12256. }
  12257. /**
  12258. * TSL function for creating a storage element node.
  12259. *
  12260. * @tsl
  12261. * @function
  12262. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  12263. * @param {Node} indexNode - The index node that defines the element access.
  12264. * @returns {StorageArrayElementNode}
  12265. */
  12266. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  12267. /**
  12268. * This node is used in context of compute shaders and allows to define a
  12269. * storage buffer for data. A typical workflow is to create instances of
  12270. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  12271. * setup up a compute shader that writes into the buffers and then convert
  12272. * the storage buffers to attribute nodes for rendering.
  12273. *
  12274. * ```js
  12275. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  12276. *
  12277. * const computeInit = Fn( () => { // the compute shader
  12278. *
  12279. * const position = positionBuffer.element( instanceIndex );
  12280. *
  12281. * // compute position data
  12282. *
  12283. * position.x = 1;
  12284. * position.y = 1;
  12285. * position.z = 1;
  12286. *
  12287. * } )().compute( particleCount );
  12288. *
  12289. * const particleMaterial = new THREE.SpriteNodeMaterial();
  12290. * particleMaterial.positionNode = positionBuffer.toAttribute();
  12291. *
  12292. * renderer.computeAsync( computeInit );
  12293. *
  12294. * ```
  12295. *
  12296. * @augments BufferNode
  12297. */
  12298. class StorageBufferNode extends BufferNode {
  12299. static get type() {
  12300. return 'StorageBufferNode';
  12301. }
  12302. /**
  12303. * Constructs a new storage buffer node.
  12304. *
  12305. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12306. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  12307. * @param {number} [bufferCount=0] - The buffer count.
  12308. */
  12309. constructor( value, bufferType = null, bufferCount = 0 ) {
  12310. let nodeType, structTypeNode = null;
  12311. if ( bufferType && bufferType.isStruct ) {
  12312. nodeType = 'struct';
  12313. structTypeNode = bufferType.layout;
  12314. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  12315. bufferCount = value.count;
  12316. }
  12317. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  12318. nodeType = getTypeFromLength( value.itemSize );
  12319. bufferCount = value.count;
  12320. } else {
  12321. nodeType = bufferType;
  12322. }
  12323. super( value, nodeType, bufferCount );
  12324. /**
  12325. * This flag can be used for type testing.
  12326. *
  12327. * @type {boolean}
  12328. * @readonly
  12329. * @default true
  12330. */
  12331. this.isStorageBufferNode = true;
  12332. /**
  12333. * The buffer struct type.
  12334. *
  12335. * @type {?StructTypeNode}
  12336. * @default null
  12337. */
  12338. this.structTypeNode = structTypeNode;
  12339. /**
  12340. * The access type of the texture node.
  12341. *
  12342. * @type {string}
  12343. * @default 'readWrite'
  12344. */
  12345. this.access = NodeAccess.READ_WRITE;
  12346. /**
  12347. * Whether the node is atomic or not.
  12348. *
  12349. * @type {boolean}
  12350. * @default false
  12351. */
  12352. this.isAtomic = false;
  12353. /**
  12354. * Whether the node represents a PBO or not.
  12355. * Only relevant for WebGL.
  12356. *
  12357. * @type {boolean}
  12358. * @default false
  12359. */
  12360. this.isPBO = false;
  12361. /**
  12362. * A reference to the internal buffer attribute node.
  12363. *
  12364. * @private
  12365. * @type {?BufferAttributeNode}
  12366. * @default null
  12367. */
  12368. this._attribute = null;
  12369. /**
  12370. * A reference to the internal varying node.
  12371. *
  12372. * @private
  12373. * @type {?VaryingNode}
  12374. * @default null
  12375. */
  12376. this._varying = null;
  12377. /**
  12378. * `StorageBufferNode` sets this property to `true` by default.
  12379. *
  12380. * @type {boolean}
  12381. * @default true
  12382. */
  12383. this.global = true;
  12384. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  12385. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  12386. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  12387. else value.isStorageBufferAttribute = true;
  12388. }
  12389. }
  12390. /**
  12391. * This method is overwritten since the buffer data might be shared
  12392. * and thus the hash should be shared as well.
  12393. *
  12394. * @param {NodeBuilder} builder - The current node builder.
  12395. * @return {string} The hash.
  12396. */
  12397. getHash( builder ) {
  12398. let id;
  12399. if ( this.bufferCount === 0 ) {
  12400. let bufferData = builder.globalCache.getData( this.value );
  12401. if ( bufferData === undefined ) {
  12402. bufferData = {
  12403. node: this
  12404. };
  12405. builder.globalCache.setData( this.value, bufferData );
  12406. }
  12407. id = bufferData.node.id;
  12408. } else {
  12409. id = this.id;
  12410. }
  12411. return String( id );
  12412. }
  12413. /**
  12414. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  12415. *
  12416. * @param {NodeBuilder} builder - The current node builder.
  12417. * @return {string} The input type.
  12418. */
  12419. getInputType( /*builder*/ ) {
  12420. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  12421. }
  12422. /**
  12423. * Enables element access with the given index node.
  12424. *
  12425. * @param {IndexNode} indexNode - The index node.
  12426. * @return {StorageArrayElementNode} A node representing the element access.
  12427. */
  12428. element( indexNode ) {
  12429. return storageElement( this, indexNode );
  12430. }
  12431. /**
  12432. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  12433. *
  12434. * @param {boolean} value - The value so set.
  12435. * @return {StorageBufferNode} A reference to this node.
  12436. */
  12437. setPBO( value ) {
  12438. this.isPBO = value;
  12439. return this;
  12440. }
  12441. /**
  12442. * Returns the `isPBO` value.
  12443. *
  12444. * @return {boolean} Whether the node represents a PBO or not.
  12445. */
  12446. getPBO() {
  12447. return this.isPBO;
  12448. }
  12449. /**
  12450. * Defines the node access.
  12451. *
  12452. * @param {string} value - The node access.
  12453. * @return {StorageBufferNode} A reference to this node.
  12454. */
  12455. setAccess( value ) {
  12456. this.access = value;
  12457. return this;
  12458. }
  12459. /**
  12460. * Convenience method for configuring a read-only node access.
  12461. *
  12462. * @return {StorageBufferNode} A reference to this node.
  12463. */
  12464. toReadOnly() {
  12465. return this.setAccess( NodeAccess.READ_ONLY );
  12466. }
  12467. /**
  12468. * Defines whether the node is atomic or not.
  12469. *
  12470. * @param {boolean} value - The atomic flag.
  12471. * @return {StorageBufferNode} A reference to this node.
  12472. */
  12473. setAtomic( value ) {
  12474. this.isAtomic = value;
  12475. return this;
  12476. }
  12477. /**
  12478. * Convenience method for making this node atomic.
  12479. *
  12480. * @return {StorageBufferNode} A reference to this node.
  12481. */
  12482. toAtomic() {
  12483. return this.setAtomic( true );
  12484. }
  12485. /**
  12486. * Returns attribute data for this storage buffer node.
  12487. *
  12488. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  12489. */
  12490. getAttributeData() {
  12491. if ( this._attribute === null ) {
  12492. this._attribute = bufferAttribute( this.value );
  12493. this._varying = varying( this._attribute );
  12494. }
  12495. return {
  12496. attribute: this._attribute,
  12497. varying: this._varying
  12498. };
  12499. }
  12500. /**
  12501. * This method is overwritten since the node type from the availability of storage buffers
  12502. * and the attribute data.
  12503. *
  12504. * @param {NodeBuilder} builder - The current node builder.
  12505. * @return {string} The node type.
  12506. */
  12507. generateNodeType( builder ) {
  12508. if ( this.structTypeNode !== null ) {
  12509. return this.structTypeNode.getNodeType( builder );
  12510. }
  12511. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12512. return super.generateNodeType( builder );
  12513. }
  12514. const { attribute } = this.getAttributeData();
  12515. return attribute.getNodeType( builder );
  12516. }
  12517. /**
  12518. * Returns the type of a member of the struct.
  12519. *
  12520. * @param {NodeBuilder} builder - The current node builder.
  12521. * @param {string} name - The name of the member.
  12522. * @return {string} The type of the member.
  12523. */
  12524. getMemberType( builder, name ) {
  12525. if ( this.structTypeNode !== null ) {
  12526. return this.structTypeNode.getMemberType( builder, name );
  12527. }
  12528. return 'void';
  12529. }
  12530. /**
  12531. * Generates the code snippet of the storage buffer node.
  12532. *
  12533. * @param {NodeBuilder} builder - The current node builder.
  12534. * @return {string} The generated code snippet.
  12535. */
  12536. generate( builder ) {
  12537. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12538. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12539. return super.generate( builder );
  12540. }
  12541. const { attribute, varying } = this.getAttributeData();
  12542. const output = varying.build( builder );
  12543. builder.registerTransform( output, attribute );
  12544. return output;
  12545. }
  12546. }
  12547. /**
  12548. * TSL function for creating a storage buffer node.
  12549. *
  12550. * @tsl
  12551. * @function
  12552. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12553. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12554. * @param {number} [count=0] - The buffer count.
  12555. * @returns {StorageBufferNode}
  12556. */
  12557. const storage = ( value, type = null, count = 0 ) => new StorageBufferNode( value, type, count );
  12558. /**
  12559. * This node implements the vertex shader logic which is required
  12560. * when rendering 3D objects via instancing. The code makes sure
  12561. * vertex positions, normals and colors can be modified via instanced
  12562. * data.
  12563. *
  12564. * @augments Node
  12565. */
  12566. class InstanceNode extends Node {
  12567. static get type() {
  12568. return 'InstanceNode';
  12569. }
  12570. /**
  12571. * Constructs a new instance node.
  12572. *
  12573. * @param {number} count - The number of instances.
  12574. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12575. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12576. */
  12577. constructor( count, instanceMatrix, instanceColor = null ) {
  12578. super( 'void' );
  12579. /**
  12580. * The number of instances.
  12581. *
  12582. * @type {number}
  12583. */
  12584. this.count = count;
  12585. /**
  12586. * Instanced buffer attribute representing the transformation of instances.
  12587. *
  12588. * @type {InstancedBufferAttribute}
  12589. */
  12590. this.instanceMatrix = instanceMatrix;
  12591. /**
  12592. * Instanced buffer attribute representing the color of instances.
  12593. *
  12594. * @type {InstancedBufferAttribute}
  12595. */
  12596. this.instanceColor = instanceColor;
  12597. /**
  12598. * The node that represents the instance matrix data.
  12599. *
  12600. * @type {?Node}
  12601. */
  12602. this.instanceMatrixNode = null;
  12603. /**
  12604. * The node that represents the instance color data.
  12605. *
  12606. * @type {?Node}
  12607. * @default null
  12608. */
  12609. this.instanceColorNode = null;
  12610. /**
  12611. * The update type is set to `frame` since an update
  12612. * of instanced buffer data must be checked per frame.
  12613. *
  12614. * @type {string}
  12615. * @default 'frame'
  12616. */
  12617. this.updateType = NodeUpdateType.FRAME;
  12618. /**
  12619. * A reference to a buffer that is used by `instanceMatrixNode`.
  12620. *
  12621. * @type {?InstancedInterleavedBuffer}
  12622. */
  12623. this.buffer = null;
  12624. /**
  12625. * A reference to a buffer that is used by `instanceColorNode`.
  12626. *
  12627. * @type {?InstancedBufferAttribute}
  12628. */
  12629. this.bufferColor = null;
  12630. /**
  12631. * The previous instance matrices. Required for computing motion vectors.
  12632. *
  12633. * @type {?Node}
  12634. * @default null
  12635. */
  12636. this.previousInstanceMatrixNode = null;
  12637. }
  12638. /**
  12639. * Tracks whether the matrix data is provided via a storage buffer.
  12640. *
  12641. * @type {boolean}
  12642. */
  12643. get isStorageMatrix() {
  12644. const { instanceMatrix } = this;
  12645. return instanceMatrix && instanceMatrix.isStorageInstancedBufferAttribute === true;
  12646. }
  12647. /**
  12648. * Tracks whether the color data is provided via a storage buffer.
  12649. *
  12650. * @type {boolean}
  12651. */
  12652. get isStorageColor() {
  12653. const { instanceColor } = this;
  12654. return instanceColor && instanceColor.isStorageInstancedBufferAttribute === true;
  12655. }
  12656. /**
  12657. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12658. * to predefined node variables for accumulation. That follows the same patterns
  12659. * like with morph and skinning nodes.
  12660. *
  12661. * @param {NodeBuilder} builder - The current node builder.
  12662. */
  12663. setup( builder ) {
  12664. let { instanceMatrixNode, instanceColorNode } = this;
  12665. // instance matrix
  12666. if ( instanceMatrixNode === null ) {
  12667. instanceMatrixNode = this._createInstanceMatrixNode( true, builder );
  12668. this.instanceMatrixNode = instanceMatrixNode;
  12669. }
  12670. // instance color
  12671. const { instanceColor, isStorageColor } = this;
  12672. if ( instanceColor && instanceColorNode === null ) {
  12673. if ( isStorageColor ) {
  12674. instanceColorNode = storage( instanceColor, 'vec3', Math.max( instanceColor.count, 1 ) ).element( instanceIndex );
  12675. } else {
  12676. const bufferAttribute = new InstancedBufferAttribute( instanceColor.array, 3 );
  12677. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12678. this.bufferColor = bufferAttribute;
  12679. instanceColorNode = vec3( bufferFn( bufferAttribute, 'vec3', 3, 0 ) );
  12680. }
  12681. this.instanceColorNode = instanceColorNode;
  12682. }
  12683. // POSITION
  12684. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  12685. positionLocal.assign( instancePosition );
  12686. if ( builder.needsPreviousData() ) {
  12687. positionPrevious.assign( this.getPreviousInstancedPosition( builder ) );
  12688. }
  12689. // NORMAL
  12690. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12691. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  12692. // ASSIGNS
  12693. normalLocal.assign( instanceNormal );
  12694. }
  12695. // COLOR
  12696. if ( this.instanceColorNode !== null ) {
  12697. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  12698. }
  12699. }
  12700. /**
  12701. * Checks if the internal buffers require an update.
  12702. *
  12703. * @param {NodeFrame} frame - The current node frame.
  12704. */
  12705. update( frame ) {
  12706. if ( this.buffer !== null && this.isStorageMatrix !== true ) {
  12707. this.buffer.clearUpdateRanges();
  12708. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  12709. // update version if necessary
  12710. if ( this.instanceMatrix.version !== this.buffer.version ) {
  12711. this.buffer.version = this.instanceMatrix.version;
  12712. }
  12713. }
  12714. if ( this.instanceColor && this.bufferColor !== null && this.isStorageColor !== true ) {
  12715. this.bufferColor.clearUpdateRanges();
  12716. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  12717. if ( this.instanceColor.version !== this.bufferColor.version ) {
  12718. this.bufferColor.version = this.instanceColor.version;
  12719. }
  12720. }
  12721. if ( this.previousInstanceMatrixNode !== null ) {
  12722. frame.object.previousInstanceMatrix.array.set( this.instanceMatrix.array );
  12723. }
  12724. }
  12725. /**
  12726. * Computes the transformed/instanced vertex position of the previous frame.
  12727. *
  12728. * @param {NodeBuilder} builder - The current node builder.
  12729. * @return {Node<vec3>} The instanced position from the previous frame.
  12730. */
  12731. getPreviousInstancedPosition( builder ) {
  12732. const instancedMesh = builder.object;
  12733. if ( this.previousInstanceMatrixNode === null ) {
  12734. instancedMesh.previousInstanceMatrix = this.instanceMatrix.clone();
  12735. this.previousInstanceMatrixNode = this._createInstanceMatrixNode( false, builder );
  12736. }
  12737. return this.previousInstanceMatrixNode.mul( positionPrevious ).xyz;
  12738. }
  12739. /**
  12740. * Creates a node representing the instance matrix data.
  12741. *
  12742. * @private
  12743. * @param {boolean} assignBuffer - Whether the created interleaved buffer should be assigned to the `buffer` member or not.
  12744. * @param {NodeBuilder} builder - A reference to the current node builder.
  12745. * @return {Node} The instance matrix node.
  12746. */
  12747. _createInstanceMatrixNode( assignBuffer, builder ) {
  12748. let instanceMatrixNode;
  12749. const { instanceMatrix } = this;
  12750. const { count } = instanceMatrix;
  12751. if ( this.isStorageMatrix ) {
  12752. instanceMatrixNode = storage( instanceMatrix, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12753. } else {
  12754. const uniformBufferSize = count * 16 * 4; // count * 16 components * 4 bytes (float)
  12755. if ( uniformBufferSize <= builder.getUniformBufferLimit() ) {
  12756. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12757. } else {
  12758. const interleaved = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  12759. if ( assignBuffer === true ) this.buffer = interleaved;
  12760. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12761. const instanceBuffers = [
  12762. bufferFn( interleaved, 'vec4', 16, 0 ),
  12763. bufferFn( interleaved, 'vec4', 16, 4 ),
  12764. bufferFn( interleaved, 'vec4', 16, 8 ),
  12765. bufferFn( interleaved, 'vec4', 16, 12 )
  12766. ];
  12767. instanceMatrixNode = mat4( ...instanceBuffers );
  12768. }
  12769. }
  12770. return instanceMatrixNode;
  12771. }
  12772. }
  12773. /**
  12774. * TSL function for creating an instance node.
  12775. *
  12776. * @tsl
  12777. * @function
  12778. * @param {number} count - The number of instances.
  12779. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12780. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12781. * @returns {InstanceNode}
  12782. */
  12783. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  12784. /**
  12785. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  12786. * It allows an easier setup of the instance node.
  12787. *
  12788. * @augments InstanceNode
  12789. */
  12790. class InstancedMeshNode extends InstanceNode {
  12791. static get type() {
  12792. return 'InstancedMeshNode';
  12793. }
  12794. /**
  12795. * Constructs a new instanced mesh node.
  12796. *
  12797. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  12798. */
  12799. constructor( instancedMesh ) {
  12800. const { count, instanceMatrix, instanceColor } = instancedMesh;
  12801. super( count, instanceMatrix, instanceColor );
  12802. /**
  12803. * A reference to the instanced mesh.
  12804. *
  12805. * @type {InstancedMesh}
  12806. */
  12807. this.instancedMesh = instancedMesh;
  12808. }
  12809. }
  12810. /**
  12811. * TSL function for creating an instanced mesh node.
  12812. *
  12813. * @tsl
  12814. * @function
  12815. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  12816. * @returns {InstancedMeshNode}
  12817. */
  12818. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  12819. /**
  12820. * This node implements the vertex shader logic which is required
  12821. * when rendering 3D objects via batching. `BatchNode` must be used
  12822. * with instances of {@link BatchedMesh}.
  12823. *
  12824. * @augments Node
  12825. */
  12826. class BatchNode extends Node {
  12827. static get type() {
  12828. return 'BatchNode';
  12829. }
  12830. /**
  12831. * Constructs a new batch node.
  12832. *
  12833. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12834. */
  12835. constructor( batchMesh ) {
  12836. super( 'void' );
  12837. /**
  12838. * A reference to batched mesh.
  12839. *
  12840. * @type {BatchedMesh}
  12841. */
  12842. this.batchMesh = batchMesh;
  12843. /**
  12844. * The batching index node.
  12845. *
  12846. * @type {?IndexNode}
  12847. * @default null
  12848. */
  12849. this.batchingIdNode = null;
  12850. }
  12851. /**
  12852. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12853. * to predefined node variables for accumulation. That follows the same patterns
  12854. * like with morph and skinning nodes.
  12855. *
  12856. * @param {NodeBuilder} builder - The current node builder.
  12857. */
  12858. setup( builder ) {
  12859. if ( this.batchingIdNode === null ) {
  12860. if ( builder.getDrawIndex() === null ) {
  12861. this.batchingIdNode = instanceIndex;
  12862. } else {
  12863. this.batchingIdNode = drawIndex;
  12864. }
  12865. }
  12866. const getIndirectIndex = Fn( ( [ id ] ) => {
  12867. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x ).toConst();
  12868. const x = int( id ).mod( size ).toConst();
  12869. const y = int( id ).div( size ).toConst();
  12870. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  12871. } ).setLayout( {
  12872. name: 'getIndirectIndex',
  12873. type: 'uint',
  12874. inputs: [
  12875. { name: 'id', type: 'int' }
  12876. ]
  12877. } );
  12878. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  12879. const matricesTexture = this.batchMesh._matricesTexture;
  12880. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x ).toConst();
  12881. const j = float( indirectId ).mul( 4 ).toInt().toConst();
  12882. const x = j.mod( size ).toConst();
  12883. const y = j.div( size ).toConst();
  12884. const batchingMatrix = mat4(
  12885. textureLoad( matricesTexture, ivec2( x, y ) ),
  12886. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  12887. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  12888. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  12889. );
  12890. const colorsTexture = this.batchMesh._colorsTexture;
  12891. if ( colorsTexture !== null ) {
  12892. const getBatchingColor = Fn( ( [ id ] ) => {
  12893. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x ).toConst();
  12894. const j = id;
  12895. const x = j.mod( size ).toConst();
  12896. const y = j.div( size ).toConst();
  12897. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  12898. } ).setLayout( {
  12899. name: 'getBatchingColor',
  12900. type: 'vec3',
  12901. inputs: [
  12902. { name: 'id', type: 'int' }
  12903. ]
  12904. } );
  12905. const color = getBatchingColor( indirectId );
  12906. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  12907. }
  12908. const bm = mat3( batchingMatrix );
  12909. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  12910. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  12911. const batchingNormal = bm.mul( transformedNormal ).xyz;
  12912. normalLocal.assign( batchingNormal );
  12913. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12914. tangentLocal.mulAssign( bm );
  12915. }
  12916. }
  12917. }
  12918. /**
  12919. * TSL function for creating a batch node.
  12920. *
  12921. * @tsl
  12922. * @function
  12923. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12924. * @returns {BatchNode}
  12925. */
  12926. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  12927. const _frameId = new WeakMap();
  12928. /**
  12929. * This node implements the vertex transformation shader logic which is required
  12930. * for skinning/skeletal animation.
  12931. *
  12932. * @augments Node
  12933. */
  12934. class SkinningNode extends Node {
  12935. static get type() {
  12936. return 'SkinningNode';
  12937. }
  12938. /**
  12939. * Constructs a new skinning node.
  12940. *
  12941. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12942. */
  12943. constructor( skinnedMesh ) {
  12944. super( 'void' );
  12945. /**
  12946. * The skinned mesh.
  12947. *
  12948. * @type {SkinnedMesh}
  12949. */
  12950. this.skinnedMesh = skinnedMesh;
  12951. /**
  12952. * The update type overwritten since skinning nodes are updated per object.
  12953. *
  12954. * @type {string}
  12955. */
  12956. this.updateType = NodeUpdateType.OBJECT;
  12957. //
  12958. /**
  12959. * The skin index attribute.
  12960. *
  12961. * @type {AttributeNode}
  12962. */
  12963. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12964. /**
  12965. * The skin weight attribute.
  12966. *
  12967. * @type {AttributeNode}
  12968. */
  12969. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12970. /**
  12971. * The bind matrix node.
  12972. *
  12973. * @type {Node<mat4>}
  12974. */
  12975. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12976. /**
  12977. * The bind matrix inverse node.
  12978. *
  12979. * @type {Node<mat4>}
  12980. */
  12981. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12982. /**
  12983. * The bind matrices as a uniform buffer node.
  12984. *
  12985. * @type {Node}
  12986. */
  12987. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12988. /**
  12989. * The current vertex position in local space.
  12990. *
  12991. * @type {Node<vec3>}
  12992. */
  12993. this.positionNode = positionLocal;
  12994. /**
  12995. * The result of vertex position in local space.
  12996. *
  12997. * @type {Node<vec3>}
  12998. */
  12999. this.toPositionNode = positionLocal;
  13000. /**
  13001. * The previous bind matrices as a uniform buffer node.
  13002. * Required for computing motion vectors.
  13003. *
  13004. * @type {?Node}
  13005. * @default null
  13006. */
  13007. this.previousBoneMatricesNode = null;
  13008. }
  13009. /**
  13010. * Transforms the given vertex position via skinning.
  13011. *
  13012. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  13013. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  13014. * @return {Node<vec3>} The transformed vertex position.
  13015. */
  13016. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  13017. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  13018. const boneMatX = boneMatrices.element( skinIndexNode.x );
  13019. const boneMatY = boneMatrices.element( skinIndexNode.y );
  13020. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  13021. const boneMatW = boneMatrices.element( skinIndexNode.w );
  13022. // POSITION
  13023. const skinVertex = bindMatrixNode.mul( position );
  13024. const skinned = add(
  13025. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  13026. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  13027. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  13028. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  13029. );
  13030. return bindMatrixInverseNode.mul( skinned ).xyz;
  13031. }
  13032. /**
  13033. * Transforms the given vertex normal and tangent via skinning.
  13034. *
  13035. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  13036. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  13037. * @param {Node<vec3>} [tangent=tangentLocal] - The vertex tangent in local space.
  13038. * @return {{skinNormal: Node<vec3>, skinTangent:Node<vec3>}} The transformed vertex normal and tangent.
  13039. */
  13040. getSkinnedNormalAndTangent( boneMatrices = this.boneMatricesNode, normal = normalLocal, tangent = tangentLocal ) {
  13041. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  13042. const boneMatX = boneMatrices.element( skinIndexNode.x );
  13043. const boneMatY = boneMatrices.element( skinIndexNode.y );
  13044. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  13045. const boneMatW = boneMatrices.element( skinIndexNode.w );
  13046. // NORMAL and TANGENT
  13047. let skinMatrix = add(
  13048. skinWeightNode.x.mul( boneMatX ),
  13049. skinWeightNode.y.mul( boneMatY ),
  13050. skinWeightNode.z.mul( boneMatZ ),
  13051. skinWeightNode.w.mul( boneMatW )
  13052. );
  13053. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  13054. const skinNormal = skinMatrix.transformDirection( normal ).xyz;
  13055. const skinTangent = skinMatrix.transformDirection( tangent ).xyz;
  13056. return { skinNormal, skinTangent };
  13057. }
  13058. /**
  13059. * Computes the transformed/skinned vertex position of the previous frame.
  13060. *
  13061. * @param {NodeBuilder} builder - The current node builder.
  13062. * @return {Node<vec3>} The skinned position from the previous frame.
  13063. */
  13064. getPreviousSkinnedPosition( builder ) {
  13065. const skinnedMesh = builder.object;
  13066. if ( this.previousBoneMatricesNode === null ) {
  13067. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  13068. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  13069. }
  13070. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  13071. }
  13072. /**
  13073. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  13074. *
  13075. * @param {NodeBuilder} builder - The current node builder.
  13076. * @return {Node<vec3>} The transformed vertex position.
  13077. */
  13078. setup( builder ) {
  13079. if ( builder.needsPreviousData() ) {
  13080. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  13081. }
  13082. const skinPosition = this.getSkinnedPosition();
  13083. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  13084. //
  13085. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  13086. const { skinNormal, skinTangent } = this.getSkinnedNormalAndTangent();
  13087. normalLocal.assign( skinNormal );
  13088. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  13089. tangentLocal.assign( skinTangent );
  13090. }
  13091. }
  13092. return skinPosition;
  13093. }
  13094. /**
  13095. * Generates the code snippet of the skinning node.
  13096. *
  13097. * @param {NodeBuilder} builder - The current node builder.
  13098. * @param {string} output - The current output.
  13099. * @return {string} The generated code snippet.
  13100. */
  13101. generate( builder, output ) {
  13102. if ( output !== 'void' ) {
  13103. return super.generate( builder, output );
  13104. }
  13105. }
  13106. /**
  13107. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  13108. *
  13109. * @param {NodeFrame} frame - The current node frame.
  13110. */
  13111. update( frame ) {
  13112. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  13113. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  13114. _frameId.set( skeleton, frame.frameId );
  13115. if ( this.previousBoneMatricesNode !== null ) {
  13116. if ( skeleton.previousBoneMatrices === null ) {
  13117. // cloned skeletons miss "previousBoneMatrices" in their first updated
  13118. skeleton.previousBoneMatrices = new Float32Array( skeleton.boneMatrices );
  13119. }
  13120. skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  13121. }
  13122. skeleton.update();
  13123. }
  13124. }
  13125. /**
  13126. * TSL function for creating a skinning node.
  13127. *
  13128. * @tsl
  13129. * @function
  13130. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  13131. * @returns {SkinningNode}
  13132. */
  13133. const skinning = ( skinnedMesh ) => new SkinningNode( skinnedMesh );
  13134. /**
  13135. * TSL function for computing skinning.
  13136. *
  13137. * @tsl
  13138. * @function
  13139. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  13140. * @param {Node<vec3>} [toPosition=null] - The target position.
  13141. * @returns {SkinningNode}
  13142. */
  13143. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  13144. const node = new SkinningNode( skinnedMesh );
  13145. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  13146. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  13147. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  13148. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  13149. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  13150. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  13151. node.toPositionNode = toPosition;
  13152. return nodeObject( node );
  13153. };
  13154. /**
  13155. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  13156. * ```js
  13157. * Loop( count, ( { i } ) => {
  13158. *
  13159. * } );
  13160. * ```
  13161. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  13162. * ```js
  13163. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  13164. *
  13165. * } );
  13166. *```
  13167. * Nested loops can be defined in a compacted form:
  13168. * ```js
  13169. * Loop( 10, 5, ( { i, j } ) => {
  13170. *
  13171. * } );
  13172. * ```
  13173. * Loops that should run backwards can be defined like so:
  13174. * ```js
  13175. * Loop( { start: 10 }, () => {} );
  13176. * ```
  13177. * It is possible to execute with boolean values, similar to the `while` syntax.
  13178. * ```js
  13179. * const value = float( 0 ).toVar();
  13180. *
  13181. * Loop( value.lessThan( 10 ), () => {
  13182. *
  13183. * value.addAssign( 1 );
  13184. *
  13185. * } );
  13186. * ```
  13187. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  13188. * @augments Node
  13189. */
  13190. class LoopNode extends Node {
  13191. static get type() {
  13192. return 'LoopNode';
  13193. }
  13194. /**
  13195. * Constructs a new loop node.
  13196. *
  13197. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  13198. */
  13199. constructor( params = [] ) {
  13200. super( 'void' );
  13201. this.params = params;
  13202. }
  13203. /**
  13204. * Returns a loop variable name based on an index. The pattern is
  13205. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  13206. *
  13207. * @param {number} index - The index.
  13208. * @return {string} The loop variable name.
  13209. */
  13210. getVarName( index ) {
  13211. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  13212. }
  13213. /**
  13214. * Returns properties about this node.
  13215. *
  13216. * @param {NodeBuilder} builder - The current node builder.
  13217. * @return {Object} The node properties.
  13218. */
  13219. getProperties( builder ) {
  13220. const properties = builder.getNodeProperties( this );
  13221. if ( properties.stackNode !== undefined ) return properties;
  13222. //
  13223. const inputs = {};
  13224. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  13225. const param = this.params[ i ];
  13226. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  13227. const type = ( param.isNode !== true && param.type ) || 'int';
  13228. inputs[ name ] = expression( name, type );
  13229. }
  13230. const stack = builder.addStack();
  13231. const fnCall = this.params[ this.params.length - 1 ]( inputs );
  13232. properties.returnsNode = fnCall.context( { nodeLoop: fnCall } );
  13233. properties.stackNode = stack;
  13234. const baseParam = this.params[ 0 ];
  13235. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  13236. const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs );
  13237. properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } );
  13238. }
  13239. builder.removeStack();
  13240. return properties;
  13241. }
  13242. setup( builder ) {
  13243. // setup properties
  13244. this.getProperties( builder );
  13245. if ( builder.fnCall ) {
  13246. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  13247. shaderNodeData.hasLoop = true;
  13248. }
  13249. }
  13250. generate( builder ) {
  13251. const properties = this.getProperties( builder );
  13252. const params = this.params;
  13253. const stackNode = properties.stackNode;
  13254. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  13255. const param = params[ i ];
  13256. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  13257. if ( param.isNode ) {
  13258. if ( param.getNodeType( builder ) === 'bool' ) {
  13259. isWhile = true;
  13260. type = 'bool';
  13261. end = param.build( builder, type );
  13262. } else {
  13263. type = 'int';
  13264. name = this.getVarName( i );
  13265. start = '0';
  13266. end = param.build( builder, type );
  13267. condition = '<';
  13268. }
  13269. } else {
  13270. type = param.type || 'int';
  13271. name = param.name || this.getVarName( i );
  13272. start = param.start;
  13273. end = param.end;
  13274. condition = param.condition;
  13275. update = param.update;
  13276. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  13277. else if ( start && start.isNode ) start = start.build( builder, type );
  13278. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  13279. else if ( end && end.isNode ) end = end.build( builder, type );
  13280. if ( start !== undefined && end === undefined ) {
  13281. start = start + ' - 1';
  13282. end = '0';
  13283. condition = '>=';
  13284. } else if ( end !== undefined && start === undefined ) {
  13285. start = '0';
  13286. condition = '<';
  13287. }
  13288. if ( condition === undefined ) {
  13289. if ( Number( start ) > Number( end ) ) {
  13290. condition = '>=';
  13291. } else {
  13292. condition = '<';
  13293. }
  13294. }
  13295. }
  13296. let loopSnippet;
  13297. if ( isWhile ) {
  13298. loopSnippet = `while ( ${ end } )`;
  13299. } else {
  13300. const internalParam = { start, end};
  13301. //
  13302. const startSnippet = internalParam.start;
  13303. const endSnippet = internalParam.end;
  13304. let updateSnippet;
  13305. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  13306. if ( update !== undefined && update !== null ) {
  13307. switch ( typeof update ) {
  13308. case 'function':
  13309. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  13310. const snippet = flow.code.replace( /\t|;/g, '' );
  13311. updateSnippet = snippet;
  13312. break;
  13313. case 'number':
  13314. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  13315. break;
  13316. case 'string':
  13317. updateSnippet = name + ' ' + update;
  13318. break;
  13319. default:
  13320. if ( update.isNode ) {
  13321. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  13322. } else {
  13323. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.', this.stackTrace );
  13324. updateSnippet = 'break /* invalid update */';
  13325. }
  13326. }
  13327. } else {
  13328. if ( type === 'int' || type === 'uint' ) {
  13329. update = condition.includes( '<' ) ? '++' : '--';
  13330. } else {
  13331. update = deltaOperator() + ' 1.';
  13332. }
  13333. updateSnippet = name + ' ' + update;
  13334. }
  13335. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  13336. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  13337. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  13338. }
  13339. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  13340. }
  13341. const stackSnippet = stackNode.build( builder, 'void' );
  13342. properties.returnsNode.build( builder, 'void' );
  13343. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  13344. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  13345. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  13346. }
  13347. builder.addFlowTab();
  13348. }
  13349. }
  13350. /**
  13351. * TSL function for creating a loop node.
  13352. *
  13353. * @tsl
  13354. * @function
  13355. * @param {...any} params - A list of parameters.
  13356. * @returns {LoopNode}
  13357. */
  13358. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  13359. /**
  13360. * TSL function for creating a `Continue()` expression.
  13361. *
  13362. * @tsl
  13363. * @function
  13364. * @returns {ExpressionNode}
  13365. */
  13366. const Continue = () => expression( 'continue' ).toStack();
  13367. /**
  13368. * TSL function for creating a `Break()` expression.
  13369. *
  13370. * @tsl
  13371. * @function
  13372. * @returns {ExpressionNode}
  13373. */
  13374. const Break = () => expression( 'break' ).toStack();
  13375. const _morphTextures = /*@__PURE__*/ new WeakMap();
  13376. const _morphVec4 = /*@__PURE__*/ new Vector4();
  13377. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  13378. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  13379. const y = texelIndex.div( width );
  13380. const x = texelIndex.sub( y.mul( width ) );
  13381. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  13382. return bufferAttrib.mul( influence );
  13383. } );
  13384. function getEntry( geometry ) {
  13385. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13386. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  13387. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  13388. // instead of using attributes, the WebGL 2 code path encodes morph targets
  13389. // into an array of data textures. Each layer represents a single morph target.
  13390. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13391. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13392. let entry = _morphTextures.get( geometry );
  13393. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  13394. if ( entry !== undefined ) entry.texture.dispose();
  13395. const morphTargets = geometry.morphAttributes.position || [];
  13396. const morphNormals = geometry.morphAttributes.normal || [];
  13397. const morphColors = geometry.morphAttributes.color || [];
  13398. let vertexDataCount = 0;
  13399. if ( hasMorphPosition === true ) vertexDataCount = 1;
  13400. if ( hasMorphNormals === true ) vertexDataCount = 2;
  13401. if ( hasMorphColors === true ) vertexDataCount = 3;
  13402. let width = geometry.attributes.position.count * vertexDataCount;
  13403. let height = 1;
  13404. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  13405. if ( width > maxTextureSize ) {
  13406. height = Math.ceil( width / maxTextureSize );
  13407. width = maxTextureSize;
  13408. }
  13409. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  13410. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  13411. bufferTexture.type = FloatType;
  13412. bufferTexture.needsUpdate = true;
  13413. // fill buffer
  13414. const vertexDataStride = vertexDataCount * 4;
  13415. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  13416. const morphTarget = morphTargets[ i ];
  13417. const morphNormal = morphNormals[ i ];
  13418. const morphColor = morphColors[ i ];
  13419. const offset = width * height * 4 * i;
  13420. for ( let j = 0; j < morphTarget.count; j ++ ) {
  13421. const stride = j * vertexDataStride;
  13422. if ( hasMorphPosition === true ) {
  13423. _morphVec4.fromBufferAttribute( morphTarget, j );
  13424. buffer[ offset + stride + 0 ] = _morphVec4.x;
  13425. buffer[ offset + stride + 1 ] = _morphVec4.y;
  13426. buffer[ offset + stride + 2 ] = _morphVec4.z;
  13427. buffer[ offset + stride + 3 ] = 0;
  13428. }
  13429. if ( hasMorphNormals === true ) {
  13430. _morphVec4.fromBufferAttribute( morphNormal, j );
  13431. buffer[ offset + stride + 4 ] = _morphVec4.x;
  13432. buffer[ offset + stride + 5 ] = _morphVec4.y;
  13433. buffer[ offset + stride + 6 ] = _morphVec4.z;
  13434. buffer[ offset + stride + 7 ] = 0;
  13435. }
  13436. if ( hasMorphColors === true ) {
  13437. _morphVec4.fromBufferAttribute( morphColor, j );
  13438. buffer[ offset + stride + 8 ] = _morphVec4.x;
  13439. buffer[ offset + stride + 9 ] = _morphVec4.y;
  13440. buffer[ offset + stride + 10 ] = _morphVec4.z;
  13441. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  13442. }
  13443. }
  13444. }
  13445. entry = {
  13446. count: morphTargetsCount,
  13447. texture: bufferTexture,
  13448. stride: vertexDataCount,
  13449. size: new Vector2( width, height )
  13450. };
  13451. _morphTextures.set( geometry, entry );
  13452. function disposeTexture() {
  13453. bufferTexture.dispose();
  13454. _morphTextures.delete( geometry );
  13455. geometry.removeEventListener( 'dispose', disposeTexture );
  13456. }
  13457. geometry.addEventListener( 'dispose', disposeTexture );
  13458. }
  13459. return entry;
  13460. }
  13461. /**
  13462. * This node implements the vertex transformation shader logic which is required
  13463. * for morph target animation.
  13464. *
  13465. * @augments Node
  13466. */
  13467. class MorphNode extends Node {
  13468. static get type() {
  13469. return 'MorphNode';
  13470. }
  13471. /**
  13472. * Constructs a new morph node.
  13473. *
  13474. * @param {Mesh} mesh - The mesh holding the morph targets.
  13475. */
  13476. constructor( mesh ) {
  13477. super( 'void' );
  13478. /**
  13479. * The mesh holding the morph targets.
  13480. *
  13481. * @type {Mesh}
  13482. */
  13483. this.mesh = mesh;
  13484. /**
  13485. * A uniform node which represents the morph base influence value.
  13486. *
  13487. * @type {UniformNode<float>}
  13488. */
  13489. this.morphBaseInfluence = uniform( 1 );
  13490. /**
  13491. * The update type overwritten since morph nodes are updated per object.
  13492. *
  13493. * @type {string}
  13494. */
  13495. this.updateType = NodeUpdateType.OBJECT;
  13496. }
  13497. /**
  13498. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  13499. *
  13500. * @param {NodeBuilder} builder - The current node builder.
  13501. */
  13502. setup( builder ) {
  13503. const { geometry } = builder;
  13504. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13505. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  13506. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13507. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13508. // nodes
  13509. const { texture: bufferMap, stride, size } = getEntry( geometry );
  13510. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  13511. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  13512. const width = int( size.width );
  13513. Loop( morphTargetsCount, ( { i } ) => {
  13514. const influence = float( 0 ).toVar();
  13515. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  13516. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  13517. } else {
  13518. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  13519. }
  13520. If( influence.notEqual( 0 ), () => {
  13521. if ( hasMorphPosition === true ) {
  13522. positionLocal.addAssign( getMorph( {
  13523. bufferMap,
  13524. influence,
  13525. stride,
  13526. width,
  13527. depth: i,
  13528. offset: int( 0 )
  13529. } ) );
  13530. }
  13531. if ( hasMorphNormals === true ) {
  13532. normalLocal.addAssign( getMorph( {
  13533. bufferMap,
  13534. influence,
  13535. stride,
  13536. width,
  13537. depth: i,
  13538. offset: int( 1 )
  13539. } ) );
  13540. }
  13541. } );
  13542. } );
  13543. }
  13544. /**
  13545. * Updates the state of the morphed mesh by updating the base influence.
  13546. *
  13547. * @param {NodeFrame} frame - The current node frame.
  13548. */
  13549. update( /*frame*/ ) {
  13550. const morphBaseInfluence = this.morphBaseInfluence;
  13551. if ( this.mesh.geometry.morphTargetsRelative ) {
  13552. morphBaseInfluence.value = 1;
  13553. } else {
  13554. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  13555. }
  13556. }
  13557. }
  13558. /**
  13559. * TSL function for creating a morph node.
  13560. *
  13561. * @tsl
  13562. * @function
  13563. * @param {Mesh} mesh - The mesh holding the morph targets.
  13564. * @returns {MorphNode}
  13565. */
  13566. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  13567. /**
  13568. * Base class for lighting nodes.
  13569. *
  13570. * @augments Node
  13571. */
  13572. class LightingNode extends Node {
  13573. static get type() {
  13574. return 'LightingNode';
  13575. }
  13576. /**
  13577. * Constructs a new lighting node.
  13578. */
  13579. constructor() {
  13580. super( 'vec3' );
  13581. /**
  13582. * This flag can be used for type testing.
  13583. *
  13584. * @type {boolean}
  13585. * @readonly
  13586. * @default true
  13587. */
  13588. this.isLightingNode = true;
  13589. }
  13590. }
  13591. /**
  13592. * A generic class that can be used by nodes which contribute
  13593. * ambient occlusion to the scene. E.g. an ambient occlusion map
  13594. * node can be used as input for this module. Used in {@link NodeMaterial}.
  13595. *
  13596. * @augments LightingNode
  13597. */
  13598. class AONode extends LightingNode {
  13599. static get type() {
  13600. return 'AONode';
  13601. }
  13602. /**
  13603. * Constructs a new AO node.
  13604. *
  13605. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  13606. */
  13607. constructor( aoNode = null ) {
  13608. super();
  13609. /**
  13610. * The ambient occlusion node.
  13611. *
  13612. * @type {?Node<float>}
  13613. * @default null
  13614. */
  13615. this.aoNode = aoNode;
  13616. }
  13617. setup( builder ) {
  13618. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  13619. }
  13620. }
  13621. /**
  13622. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  13623. * by adding lighting specific context data. It represents the runtime context of
  13624. * {@link LightsNode}.
  13625. *
  13626. * @augments ContextNode
  13627. */
  13628. class LightingContextNode extends ContextNode {
  13629. static get type() {
  13630. return 'LightingContextNode';
  13631. }
  13632. /**
  13633. * Constructs a new lighting context node.
  13634. *
  13635. * @param {LightsNode} lightsNode - The lights node.
  13636. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  13637. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  13638. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  13639. */
  13640. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  13641. super( lightsNode );
  13642. /**
  13643. * The current lighting model.
  13644. *
  13645. * @type {?LightingModel}
  13646. * @default null
  13647. */
  13648. this.lightingModel = lightingModel;
  13649. /**
  13650. * A backdrop node.
  13651. *
  13652. * @type {?Node<vec3>}
  13653. * @default null
  13654. */
  13655. this.backdropNode = backdropNode;
  13656. /**
  13657. * A backdrop alpha node.
  13658. *
  13659. * @type {?Node<float>}
  13660. * @default null
  13661. */
  13662. this.backdropAlphaNode = backdropAlphaNode;
  13663. this._value = null;
  13664. }
  13665. /**
  13666. * Returns a lighting context object.
  13667. *
  13668. * @return {{
  13669. * radiance: Node<vec3>,
  13670. * irradiance: Node<vec3>,
  13671. * iblIrradiance: Node<vec3>,
  13672. * ambientOcclusion: Node<float>,
  13673. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  13674. * backdrop: Node<vec3>,
  13675. * backdropAlpha: Node<float>
  13676. * }} The lighting context object.
  13677. */
  13678. getContext() {
  13679. const { backdropNode, backdropAlphaNode } = this;
  13680. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  13681. directSpecular = vec3().toVar( 'directSpecular' ),
  13682. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  13683. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  13684. const reflectedLight = {
  13685. directDiffuse,
  13686. directSpecular,
  13687. indirectDiffuse,
  13688. indirectSpecular
  13689. };
  13690. const context = {
  13691. radiance: vec3().toVar( 'radiance' ),
  13692. irradiance: vec3().toVar( 'irradiance' ),
  13693. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  13694. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  13695. reflectedLight,
  13696. backdrop: backdropNode,
  13697. backdropAlpha: backdropAlphaNode
  13698. };
  13699. return context;
  13700. }
  13701. setup( builder ) {
  13702. this.value = this._value || ( this._value = this.getContext() );
  13703. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13704. return super.setup( builder );
  13705. }
  13706. }
  13707. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13708. /**
  13709. * A generic class that can be used by nodes which contribute
  13710. * irradiance to the scene. E.g. a light map node can be used
  13711. * as input for this module. Used in {@link NodeMaterial}.
  13712. *
  13713. * @augments LightingNode
  13714. */
  13715. class IrradianceNode extends LightingNode {
  13716. static get type() {
  13717. return 'IrradianceNode';
  13718. }
  13719. /**
  13720. * Constructs a new irradiance node.
  13721. *
  13722. * @param {Node<vec3>} node - A node contributing irradiance.
  13723. */
  13724. constructor( node ) {
  13725. super();
  13726. /**
  13727. * A node contributing irradiance.
  13728. *
  13729. * @type {Node<vec3>}
  13730. */
  13731. this.node = node;
  13732. }
  13733. setup( builder ) {
  13734. builder.context.irradiance.addAssign( this.node );
  13735. }
  13736. }
  13737. const _size$5 = /*@__PURE__*/ new Vector2();
  13738. /**
  13739. * A special type of texture node which represents the data of the current viewport
  13740. * as a texture. The module extracts data from the current bound framebuffer with
  13741. * a copy operation so no extra render pass is required to produce the texture data
  13742. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13743. * variety of effects like refractive or transmissive materials.
  13744. *
  13745. * @augments TextureNode
  13746. */
  13747. class ViewportTextureNode extends TextureNode {
  13748. static get type() {
  13749. return 'ViewportTextureNode';
  13750. }
  13751. /**
  13752. * Constructs a new viewport texture node.
  13753. *
  13754. * @param {Node} [uvNode=screenUV] - The uv node.
  13755. * @param {?Node} [levelNode=null] - The level node.
  13756. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13757. */
  13758. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13759. let defaultFramebuffer = null;
  13760. if ( framebufferTexture === null ) {
  13761. defaultFramebuffer = new FramebufferTexture();
  13762. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13763. framebufferTexture = defaultFramebuffer;
  13764. } else {
  13765. defaultFramebuffer = framebufferTexture;
  13766. }
  13767. super( framebufferTexture, uvNode, levelNode );
  13768. /**
  13769. * Whether to generate mipmaps or not.
  13770. *
  13771. * @type {boolean}
  13772. * @default false
  13773. */
  13774. this.generateMipmaps = false;
  13775. /**
  13776. * The reference framebuffer texture. This is used to store the framebuffer texture
  13777. * for the current render target. If the render target changes, a new framebuffer texture
  13778. * is created automatically.
  13779. *
  13780. * @type {FramebufferTexture}
  13781. * @default null
  13782. */
  13783. this.defaultFramebuffer = defaultFramebuffer;
  13784. /**
  13785. * This flag can be used for type testing.
  13786. *
  13787. * @type {boolean}
  13788. * @readonly
  13789. * @default true
  13790. */
  13791. this.isOutputTextureNode = true;
  13792. /**
  13793. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node should extract
  13794. * the current contents of the bound framebuffer for each render call.
  13795. *
  13796. * @type {string}
  13797. * @default 'render'
  13798. */
  13799. this.updateBeforeType = NodeUpdateType.RENDER;
  13800. /**
  13801. * The framebuffer texture for the current renderer context.
  13802. *
  13803. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13804. * @private
  13805. */
  13806. this._cacheTextures = new WeakMap();
  13807. }
  13808. /**
  13809. * This methods returns a texture for the given render target or canvas target reference.
  13810. *
  13811. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13812. * for different render contexts.
  13813. *
  13814. * @param {?(RenderTarget|CanvasTarget)} [reference=null] - The render target or canvas target reference.
  13815. * @return {Texture} The framebuffer texture.
  13816. */
  13817. getTextureForReference( reference = null ) {
  13818. let defaultFramebuffer;
  13819. let cacheTextures;
  13820. if ( this.referenceNode ) {
  13821. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13822. cacheTextures = this.referenceNode._cacheTextures;
  13823. } else {
  13824. defaultFramebuffer = this.defaultFramebuffer;
  13825. cacheTextures = this._cacheTextures;
  13826. }
  13827. if ( reference === null ) {
  13828. return defaultFramebuffer;
  13829. }
  13830. if ( cacheTextures.has( reference ) === false ) {
  13831. const framebufferTexture = defaultFramebuffer.clone();
  13832. cacheTextures.set( reference, framebufferTexture );
  13833. }
  13834. return cacheTextures.get( reference );
  13835. }
  13836. updateReference( frame ) {
  13837. const renderer = frame.renderer;
  13838. const renderTarget = renderer.getRenderTarget();
  13839. const canvasTarget = renderer.getCanvasTarget();
  13840. const reference = renderTarget ? renderTarget : canvasTarget;
  13841. this.value = this.getTextureForReference( reference );
  13842. return this.value;
  13843. }
  13844. updateBefore( frame ) {
  13845. const renderer = frame.renderer;
  13846. const renderTarget = renderer.getRenderTarget();
  13847. const canvasTarget = renderer.getCanvasTarget();
  13848. const reference = renderTarget ? renderTarget : canvasTarget;
  13849. if ( reference === null ) {
  13850. renderer.getDrawingBufferSize( _size$5 );
  13851. } else if ( reference.getDrawingBufferSize ) {
  13852. reference.getDrawingBufferSize( _size$5 );
  13853. } else {
  13854. _size$5.set( reference.width, reference.height );
  13855. }
  13856. //
  13857. const framebufferTexture = this.getTextureForReference( reference );
  13858. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13859. framebufferTexture.image.width = _size$5.width;
  13860. framebufferTexture.image.height = _size$5.height;
  13861. framebufferTexture.needsUpdate = true;
  13862. }
  13863. //
  13864. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13865. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13866. renderer.copyFramebufferToTexture( framebufferTexture );
  13867. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13868. }
  13869. clone() {
  13870. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13871. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13872. return viewportTextureNode;
  13873. }
  13874. }
  13875. /**
  13876. * TSL function for creating a viewport texture node.
  13877. *
  13878. * @tsl
  13879. * @function
  13880. * @param {?Node} [uvNode=screenUV] - The uv node.
  13881. * @param {?Node} [levelNode=null] - The level node.
  13882. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13883. * @returns {ViewportTextureNode}
  13884. */
  13885. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13886. /**
  13887. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13888. *
  13889. * @tsl
  13890. * @function
  13891. * @param {?Node} [uvNode=screenUV] - The uv node.
  13892. * @param {?Node} [levelNode=null] - The level node.
  13893. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13894. * @returns {ViewportTextureNode}
  13895. */
  13896. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13897. // Singleton instances for common usage
  13898. const _singletonOpaqueViewportTextureNode = /*@__PURE__*/ viewportMipTexture();
  13899. /**
  13900. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13901. * The texture should only contain the opaque rendering objects.
  13902. *
  13903. * This should be used just in transparent or transmissive materials.
  13904. *
  13905. * @tsl
  13906. * @function
  13907. * @param {?Node} [uv=screenUV] - The uv node.
  13908. * @param {?Node} [level=null] - The level node.
  13909. * @returns {ViewportTextureNode}
  13910. */
  13911. const viewportOpaqueMipTexture = ( uv = screenUV, level = null ) => _singletonOpaqueViewportTextureNode.sample( uv, level ); // TODO: Use once() when sample() supports it
  13912. let _sharedDepthbuffer = null;
  13913. /**
  13914. * Represents the depth of the current viewport as a texture. This module
  13915. * can be used in combination with viewport texture to achieve effects
  13916. * that require depth evaluation.
  13917. *
  13918. * @augments ViewportTextureNode
  13919. */
  13920. class ViewportDepthTextureNode extends ViewportTextureNode {
  13921. static get type() {
  13922. return 'ViewportDepthTextureNode';
  13923. }
  13924. /**
  13925. * Constructs a new viewport depth texture node.
  13926. *
  13927. * @param {Node} [uvNode=screenUV] - The uv node.
  13928. * @param {?Node} [levelNode=null] - The level node.
  13929. * @param {?DepthTexture} [depthTexture=null] - A depth texture. If not provided, uses a shared depth texture.
  13930. */
  13931. constructor( uvNode = screenUV, levelNode = null, depthTexture = null ) {
  13932. if ( depthTexture === null ) {
  13933. if ( _sharedDepthbuffer === null ) {
  13934. _sharedDepthbuffer = new DepthTexture();
  13935. }
  13936. depthTexture = _sharedDepthbuffer;
  13937. }
  13938. super( uvNode, levelNode, depthTexture );
  13939. }
  13940. }
  13941. /**
  13942. * TSL function for a viewport depth texture node.
  13943. *
  13944. * @tsl
  13945. * @function
  13946. * @param {?Node} [uvNode=screenUV] - The uv node.
  13947. * @param {?Node} [levelNode=null] - The level node.
  13948. * @param {?DepthTexture} [depthTexture=null] - A depth texture. If not provided, a depth texture is created automatically.
  13949. * @returns {ViewportDepthTextureNode}
  13950. */
  13951. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 3 );
  13952. /**
  13953. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13954. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13955. * fragment or for depth evaluation purposes.
  13956. *
  13957. * @augments Node
  13958. */
  13959. class ViewportDepthNode extends Node {
  13960. static get type() {
  13961. return 'ViewportDepthNode';
  13962. }
  13963. /**
  13964. * Constructs a new viewport depth node.
  13965. *
  13966. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13967. * @param {?Node} [valueNode=null] - The value node.
  13968. */
  13969. constructor( scope, valueNode = null ) {
  13970. super( 'float' );
  13971. /**
  13972. * The node behaves differently depending on which scope is selected.
  13973. *
  13974. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13975. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13976. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13977. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13978. *
  13979. * @type {('depth'|'depthBase'|'linearDepth')}
  13980. */
  13981. this.scope = scope;
  13982. /**
  13983. * Can be used to define a custom depth value.
  13984. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13985. *
  13986. * @type {?Node}
  13987. * @default null
  13988. */
  13989. this.valueNode = valueNode;
  13990. /**
  13991. * This flag can be used for type testing.
  13992. *
  13993. * @type {boolean}
  13994. * @readonly
  13995. * @default true
  13996. */
  13997. this.isViewportDepthNode = true;
  13998. }
  13999. generate( builder ) {
  14000. const { scope } = this;
  14001. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  14002. return builder.getFragDepth();
  14003. }
  14004. return super.generate( builder );
  14005. }
  14006. setup( { camera } ) {
  14007. const { scope } = this;
  14008. const value = this.valueNode;
  14009. let node = null;
  14010. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  14011. if ( value !== null ) {
  14012. node = depthBase().assign( value );
  14013. }
  14014. } else if ( scope === ViewportDepthNode.DEPTH ) {
  14015. if ( camera.isPerspectiveCamera ) {
  14016. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  14017. } else {
  14018. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14019. }
  14020. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  14021. if ( value !== null ) {
  14022. if ( camera.isPerspectiveCamera ) {
  14023. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  14024. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  14025. } else {
  14026. node = value;
  14027. }
  14028. } else {
  14029. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14030. }
  14031. }
  14032. return node;
  14033. }
  14034. }
  14035. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  14036. ViewportDepthNode.DEPTH = 'depth';
  14037. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  14038. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  14039. /**
  14040. * TSL function for converting a viewZ value to an orthographic depth value.
  14041. *
  14042. * @tsl
  14043. * @function
  14044. * @param {Node<float>} viewZ - The viewZ node.
  14045. * @param {Node<float>} near - The camera's near value.
  14046. * @param {Node<float>} far - The camera's far value.
  14047. * @returns {Node<float>}
  14048. */
  14049. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  14050. /**
  14051. * TSL function for converting a viewZ value to a reversed orthographic depth value.
  14052. *
  14053. * @tsl
  14054. * @function
  14055. * @param {Node<float>} viewZ - The viewZ node.
  14056. * @param {Node<float>} near - The camera's near value.
  14057. * @param {Node<float>} far - The camera's far value.
  14058. * @returns {Node<float>}
  14059. */
  14060. const viewZToReversedOrthographicDepth = ( viewZ, near, far ) => viewZ.add( far ).div( far.sub( near ) );
  14061. /**
  14062. * TSL function for converting an orthographic depth value to a viewZ value.
  14063. *
  14064. * @tsl
  14065. * @function
  14066. * @param {Node<float>} depth - The orthographic depth.
  14067. * @param {Node<float>} near - The camera's near value.
  14068. * @param {Node<float>} far - The camera's far value.
  14069. * @returns {Node<float>}
  14070. */
  14071. const orthographicDepthToViewZ = /*@__PURE__*/ Fn( ( [ depth, near, far ], builder ) => {
  14072. if ( builder.renderer.reversedDepthBuffer === true ) {
  14073. return far.sub( near ).mul( depth ).sub( far );
  14074. } else {
  14075. return near.sub( far ).mul( depth ).sub( near );
  14076. }
  14077. } );
  14078. /**
  14079. * TSL function for converting a viewZ value to a perspective depth value.
  14080. *
  14081. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  14082. *
  14083. * @tsl
  14084. * @function
  14085. * @param {Node<float>} viewZ - The viewZ node.
  14086. * @param {Node<float>} near - The camera's near value.
  14087. * @param {Node<float>} far - The camera's far value.
  14088. * @returns {Node<float>}
  14089. */
  14090. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  14091. /**
  14092. * TSL function for converting a viewZ value to a reversed perspective depth value.
  14093. *
  14094. * @tsl
  14095. * @function
  14096. * @param {Node<float>} viewZ - The viewZ node.
  14097. * @param {Node<float>} near - The camera's near value.
  14098. * @param {Node<float>} far - The camera's far value.
  14099. * @returns {Node<float>}
  14100. */
  14101. const viewZToReversedPerspectiveDepth = ( viewZ, near, far ) => near.mul( viewZ.add( far ) ).div( viewZ.mul( near.sub( far ) ) );
  14102. /**
  14103. * TSL function for converting a perspective depth value to a viewZ value.
  14104. *
  14105. * @tsl
  14106. * @function
  14107. * @param {Node<float>} depth - The perspective depth.
  14108. * @param {Node<float>} near - The camera's near value.
  14109. * @param {Node<float>} far - The camera's far value.
  14110. * @returns {Node<float>}
  14111. */
  14112. const perspectiveDepthToViewZ = /*@__PURE__*/ Fn( ( [ depth, near, far ], builder ) => {
  14113. if ( builder.renderer.reversedDepthBuffer === true ) {
  14114. return near.mul( far ).div( near.sub( far ).mul( depth ).sub( near ) );
  14115. } else {
  14116. return near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  14117. }
  14118. } );
  14119. /**
  14120. * TSL function for converting a viewZ value to a logarithmic depth value.
  14121. *
  14122. * @tsl
  14123. * @function
  14124. * @param {Node<float>} viewZ - The viewZ node.
  14125. * @param {Node<float>} near - The camera's near value.
  14126. * @param {Node<float>} far - The camera's far value.
  14127. * @returns {Node<float>}
  14128. */
  14129. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  14130. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  14131. // The final logarithmic depth formula used here is adapted from one described in an
  14132. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  14133. // which was an improvement upon an earlier formula one described in an
  14134. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  14135. // Ulrich's formula is the following:
  14136. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  14137. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  14138. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  14139. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  14140. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  14141. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  14142. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  14143. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  14144. // be used, and ultimately Ulrich's "near plane" version was chosen.
  14145. // Outerra eventually made another improvement to their original "C-constant" variant,
  14146. // but it still does not incorporate the camera near plane (for this version,
  14147. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  14148. // Here we make 4 changes to Ulrich's formula:
  14149. // 1. Clamp the camera near plane so we don't divide by 0.
  14150. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  14151. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  14152. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  14153. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  14154. // so we do the same here, hence the 'viewZ.negate()' call.
  14155. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  14156. near = near.max( 1e-6 ).toVar();
  14157. const numerator = log2( viewZ.negate().div( near ) );
  14158. const denominator = log2( far.div( near ) );
  14159. return numerator.div( denominator );
  14160. };
  14161. /**
  14162. * TSL function for converting a logarithmic depth value to a viewZ value.
  14163. *
  14164. * @tsl
  14165. * @function
  14166. * @param {Node<float>} depth - The logarithmic depth.
  14167. * @param {Node<float>} near - The camera's near value.
  14168. * @param {Node<float>} far - The camera's far value.
  14169. * @returns {Node<float>}
  14170. */
  14171. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  14172. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  14173. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  14174. // a negative viewZ).
  14175. const exponent = depth.mul( log( far.div( near ) ) );
  14176. return float( Math.E ).pow( exponent ).mul( near ).negate();
  14177. };
  14178. /**
  14179. * TSL function for defining a value for the current fragment's depth.
  14180. *
  14181. * @tsl
  14182. * @function
  14183. * @param {Node<float>} value - The depth value to set.
  14184. * @returns {ViewportDepthNode<float>}
  14185. */
  14186. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  14187. /**
  14188. * TSL object that represents the depth value for the current fragment.
  14189. *
  14190. * @tsl
  14191. * @type {ViewportDepthNode}
  14192. */
  14193. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  14194. /**
  14195. * TSL function for converting a perspective depth value to linear depth.
  14196. *
  14197. * @tsl
  14198. * @function
  14199. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  14200. * @returns {ViewportDepthNode<float>}
  14201. */
  14202. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  14203. /**
  14204. * TSL object that represents the linear (orthographic) depth value of the current fragment
  14205. *
  14206. * @tsl
  14207. * @type {ViewportDepthNode}
  14208. */
  14209. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  14210. depth.assign = ( value ) => depthBase( value );
  14211. /**
  14212. * This node is used in {@link NodeMaterial} to setup the clipping
  14213. * which can happen hardware-accelerated (if supported) and optionally
  14214. * use alpha-to-coverage for anti-aliasing clipped edges.
  14215. *
  14216. * @augments Node
  14217. */
  14218. class ClippingNode extends Node {
  14219. static get type() {
  14220. return 'ClippingNode';
  14221. }
  14222. /**
  14223. * Constructs a new clipping node.
  14224. *
  14225. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  14226. * the selected scope influences the behavior of the node and what type of code is generated.
  14227. */
  14228. constructor( scope = ClippingNode.DEFAULT ) {
  14229. super();
  14230. /**
  14231. * The node's scope. Similar to other nodes, the selected scope influences
  14232. * the behavior of the node and what type of code is generated.
  14233. *
  14234. * @type {('default'|'hardware'|'alphaToCoverage')}
  14235. */
  14236. this.scope = scope;
  14237. }
  14238. /**
  14239. * Setups the node depending on the selected scope.
  14240. *
  14241. * @param {NodeBuilder} builder - The current node builder.
  14242. * @return {Node} The result node.
  14243. */
  14244. setup( builder ) {
  14245. super.setup( builder );
  14246. const clippingContext = builder.clippingContext;
  14247. const { intersectionPlanes, unionPlanes } = clippingContext;
  14248. this.hardwareClipping = builder.material.hardwareClipping;
  14249. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  14250. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  14251. } else if ( this.scope === ClippingNode.HARDWARE ) {
  14252. return this.setupHardwareClipping( unionPlanes, builder );
  14253. } else {
  14254. return this.setupDefault( intersectionPlanes, unionPlanes );
  14255. }
  14256. }
  14257. /**
  14258. * Setups alpha to coverage.
  14259. *
  14260. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  14261. * @param {Array<Vector4>} unionPlanes - The union planes.
  14262. * @return {Node} The result node.
  14263. */
  14264. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  14265. return Fn( () => {
  14266. const distanceToPlane = float().toVar( 'distanceToPlane' );
  14267. const distanceGradient = float().toVar( 'distanceToGradient' );
  14268. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  14269. const numUnionPlanes = unionPlanes.length;
  14270. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  14271. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14272. Loop( numUnionPlanes, ( { i } ) => {
  14273. const plane = clippingPlanes.element( i );
  14274. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  14275. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  14276. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  14277. } );
  14278. }
  14279. const numIntersectionPlanes = intersectionPlanes.length;
  14280. if ( numIntersectionPlanes > 0 ) {
  14281. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  14282. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  14283. Loop( numIntersectionPlanes, ( { i } ) => {
  14284. const plane = clippingPlanes.element( i );
  14285. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  14286. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  14287. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  14288. } );
  14289. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  14290. }
  14291. diffuseColor.a.mulAssign( clipOpacity );
  14292. diffuseColor.a.equal( 0.0 ).discard();
  14293. } )();
  14294. }
  14295. /**
  14296. * Setups the default clipping.
  14297. *
  14298. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  14299. * @param {Array<Vector4>} unionPlanes - The union planes.
  14300. * @return {Node} The result node.
  14301. */
  14302. setupDefault( intersectionPlanes, unionPlanes ) {
  14303. return Fn( () => {
  14304. const numUnionPlanes = unionPlanes.length;
  14305. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  14306. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14307. Loop( numUnionPlanes, ( { i } ) => {
  14308. const plane = clippingPlanes.element( i );
  14309. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  14310. } );
  14311. }
  14312. const numIntersectionPlanes = intersectionPlanes.length;
  14313. if ( numIntersectionPlanes > 0 ) {
  14314. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  14315. const clipped = bool( true ).toVar( 'clipped' );
  14316. Loop( numIntersectionPlanes, ( { i } ) => {
  14317. const plane = clippingPlanes.element( i );
  14318. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  14319. } );
  14320. clipped.discard();
  14321. }
  14322. } )();
  14323. }
  14324. /**
  14325. * Setups hardware clipping.
  14326. *
  14327. * @param {Array<Vector4>} unionPlanes - The union planes.
  14328. * @param {NodeBuilder} builder - The current node builder.
  14329. * @return {Node} The result node.
  14330. */
  14331. setupHardwareClipping( unionPlanes, builder ) {
  14332. const numUnionPlanes = unionPlanes.length;
  14333. builder.enableHardwareClipping( numUnionPlanes );
  14334. return Fn( () => {
  14335. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14336. const hw_clip_distances = builtin( builder.getClipDistance() );
  14337. Loop( numUnionPlanes, ( { i } ) => {
  14338. const plane = clippingPlanes.element( i );
  14339. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  14340. hw_clip_distances.element( i ).assign( distance );
  14341. } );
  14342. } )();
  14343. }
  14344. }
  14345. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  14346. ClippingNode.DEFAULT = 'default';
  14347. ClippingNode.HARDWARE = 'hardware';
  14348. /**
  14349. * TSL function for setting up the default clipping logic.
  14350. *
  14351. * @tsl
  14352. * @function
  14353. * @returns {ClippingNode}
  14354. */
  14355. const clipping = () => new ClippingNode();
  14356. /**
  14357. * TSL function for setting up alpha to coverage.
  14358. *
  14359. * @tsl
  14360. * @function
  14361. * @returns {ClippingNode}
  14362. */
  14363. const clippingAlpha = () => new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE );
  14364. /**
  14365. * TSL function for setting up hardware-based clipping.
  14366. *
  14367. * @tsl
  14368. * @function
  14369. * @returns {ClippingNode}
  14370. */
  14371. const hardwareClipping = () => new ClippingNode( ClippingNode.HARDWARE );
  14372. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  14373. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  14374. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  14375. 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 ) ) ) ) ) );
  14376. } );
  14377. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  14378. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  14379. } );
  14380. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  14381. // Find the discretized derivatives of our coordinates
  14382. const maxDeriv = max$1(
  14383. length( dFdx( position.xyz ) ),
  14384. length( dFdy( position.xyz ) )
  14385. );
  14386. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  14387. // Find two nearest log-discretized noise scales
  14388. const pixScales = vec2(
  14389. exp2( floor( log2( pixScale ) ) ),
  14390. exp2( ceil( log2( pixScale ) ) )
  14391. );
  14392. // Compute alpha thresholds at our two noise scales
  14393. const alpha = vec2(
  14394. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  14395. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  14396. );
  14397. // Factor to interpolate lerp with
  14398. const lerpFactor = fract( log2( pixScale ) );
  14399. // Interpolate alpha threshold from noise at two scales
  14400. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  14401. // Pass into CDF to compute uniformly distrib threshold
  14402. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  14403. const cases = vec3(
  14404. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  14405. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  14406. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  14407. // Find our final, uniformly distributed alpha threshold (ατ)
  14408. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  14409. // Avoids ατ == 0. Could also do ατ =1-ατ
  14410. return clamp( threshold, 1.0e-6, 1.0 );
  14411. } ).setLayout( {
  14412. name: 'getAlphaHashThreshold',
  14413. type: 'float',
  14414. inputs: [
  14415. { name: 'position', type: 'vec3' }
  14416. ]
  14417. } );
  14418. /**
  14419. * An attribute node for representing vertex colors.
  14420. *
  14421. * @augments AttributeNode
  14422. */
  14423. class VertexColorNode extends AttributeNode {
  14424. static get type() {
  14425. return 'VertexColorNode';
  14426. }
  14427. /**
  14428. * Constructs a new vertex color node.
  14429. *
  14430. * @param {number} index - The attribute index.
  14431. */
  14432. constructor( index ) {
  14433. super( null, 'vec4' );
  14434. /**
  14435. * This flag can be used for type testing.
  14436. *
  14437. * @type {boolean}
  14438. * @readonly
  14439. * @default true
  14440. */
  14441. this.isVertexColorNode = true;
  14442. /**
  14443. * The attribute index to enable more than one sets of vertex colors.
  14444. *
  14445. * @type {number}
  14446. * @default 0
  14447. */
  14448. this.index = index;
  14449. }
  14450. /**
  14451. * Overwrites the default implementation by honoring the attribute index.
  14452. *
  14453. * @param {NodeBuilder} builder - The current node builder.
  14454. * @return {string} The attribute name.
  14455. */
  14456. getAttributeName( /*builder*/ ) {
  14457. const index = this.index;
  14458. return 'color' + ( index > 0 ? index : '' );
  14459. }
  14460. generate( builder ) {
  14461. const attributeName = this.getAttributeName( builder );
  14462. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  14463. let result;
  14464. if ( geometryAttribute === true ) {
  14465. result = super.generate( builder );
  14466. } else {
  14467. // Vertex color fallback should be white
  14468. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  14469. }
  14470. return result;
  14471. }
  14472. serialize( data ) {
  14473. super.serialize( data );
  14474. data.index = this.index;
  14475. }
  14476. deserialize( data ) {
  14477. super.deserialize( data );
  14478. this.index = data.index;
  14479. }
  14480. }
  14481. /**
  14482. * TSL function for creating a reference node.
  14483. *
  14484. * @tsl
  14485. * @function
  14486. * @param {number} [index=0] - The attribute index.
  14487. * @returns {VertexColorNode}
  14488. */
  14489. const vertexColor = ( index = 0 ) => new VertexColorNode( index );
  14490. /**
  14491. * Represents a "Color Burn" blend mode.
  14492. *
  14493. * It's designed to darken the base layer's colors based on the color of the blend layer.
  14494. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  14495. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  14496. *
  14497. * @tsl
  14498. * @function
  14499. * @param {Node<vec3>} base - The base color.
  14500. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  14501. * @return {Node<vec3>} The result.
  14502. */
  14503. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14504. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  14505. } ).setLayout( {
  14506. name: 'blendBurn',
  14507. type: 'vec3',
  14508. inputs: [
  14509. { name: 'base', type: 'vec3' },
  14510. { name: 'blend', type: 'vec3' }
  14511. ]
  14512. } );
  14513. /**
  14514. * Represents a "Color Dodge" blend mode.
  14515. *
  14516. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  14517. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  14518. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  14519. *
  14520. * @tsl
  14521. * @function
  14522. * @param {Node<vec3>} base - The base color.
  14523. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14524. * @return {Node<vec3>} The result.
  14525. */
  14526. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14527. return min$1( base.div( blend.oneMinus() ), 1.0 );
  14528. } ).setLayout( {
  14529. name: 'blendDodge',
  14530. type: 'vec3',
  14531. inputs: [
  14532. { name: 'base', type: 'vec3' },
  14533. { name: 'blend', type: 'vec3' }
  14534. ]
  14535. } );
  14536. /**
  14537. * Represents a "Screen" blend mode.
  14538. *
  14539. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  14540. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  14541. * effects.
  14542. *
  14543. * @tsl
  14544. * @function
  14545. * @param {Node<vec3>} base - The base color.
  14546. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14547. * @return {Node<vec3>} The result.
  14548. */
  14549. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14550. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  14551. } ).setLayout( {
  14552. name: 'blendScreen',
  14553. type: 'vec3',
  14554. inputs: [
  14555. { name: 'base', type: 'vec3' },
  14556. { name: 'blend', type: 'vec3' }
  14557. ]
  14558. } );
  14559. /**
  14560. * Represents a "Overlay" blend mode.
  14561. *
  14562. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  14563. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  14564. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  14565. *
  14566. * @tsl
  14567. * @function
  14568. * @param {Node<vec3>} base - The base color.
  14569. * @param {Node<vec3>} blend - The blend color
  14570. * @return {Node<vec3>} The result.
  14571. */
  14572. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14573. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  14574. } ).setLayout( {
  14575. name: 'blendOverlay',
  14576. type: 'vec3',
  14577. inputs: [
  14578. { name: 'base', type: 'vec3' },
  14579. { name: 'blend', type: 'vec3' }
  14580. ]
  14581. } );
  14582. /**
  14583. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  14584. * It assumes both input colors have non-premultiplied alpha.
  14585. *
  14586. * @tsl
  14587. * @function
  14588. * @param {Node<vec4>} base - The base color.
  14589. * @param {Node<vec4>} blend - The blend color
  14590. * @return {Node<vec4>} The result.
  14591. */
  14592. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14593. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  14594. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  14595. } ).setLayout( {
  14596. name: 'blendColor',
  14597. type: 'vec4',
  14598. inputs: [
  14599. { name: 'base', type: 'vec4' },
  14600. { name: 'blend', type: 'vec4' }
  14601. ]
  14602. } );
  14603. /**
  14604. * Premultiplies the RGB channels of a color by its alpha channel.
  14605. *
  14606. * This function is useful for converting a non-premultiplied alpha color
  14607. * into a premultiplied alpha format, where the RGB values are scaled
  14608. * by the alpha value. Premultiplied alpha is often used in graphics
  14609. * rendering for certain operations, such as compositing and image processing.
  14610. *
  14611. * @tsl
  14612. * @function
  14613. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  14614. * @return {Node<vec4>} The color with premultiplied alpha.
  14615. */
  14616. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14617. return vec4( color.rgb.mul( color.a ), color.a );
  14618. }, { color: 'vec4', return: 'vec4' } );
  14619. /**
  14620. * Unpremultiplies the RGB channels of a color by its alpha channel.
  14621. *
  14622. * This function is useful for converting a premultiplied alpha color
  14623. * back into a non-premultiplied alpha format, where the RGB values are
  14624. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  14625. * rendering for certain operations, such as compositing and image processing.
  14626. *
  14627. * @tsl
  14628. * @function
  14629. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  14630. * @return {Node<vec4>} The color with non-premultiplied alpha.
  14631. */
  14632. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14633. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  14634. return vec4( color.rgb.div( color.a ), color.a );
  14635. }, { color: 'vec4', return: 'vec4' } );
  14636. /**
  14637. * Base class for all node materials.
  14638. *
  14639. * @augments Material
  14640. */
  14641. class NodeMaterial extends Material {
  14642. static get type() {
  14643. return 'NodeMaterial';
  14644. }
  14645. /**
  14646. * Represents the type of the node material.
  14647. *
  14648. * @type {string}
  14649. */
  14650. get type() {
  14651. return this.constructor.type;
  14652. }
  14653. set type( _value ) { /* */ }
  14654. /**
  14655. * Constructs a new node material.
  14656. */
  14657. constructor() {
  14658. super();
  14659. /**
  14660. * This flag can be used for type testing.
  14661. *
  14662. * @type {boolean}
  14663. * @readonly
  14664. * @default true
  14665. */
  14666. this.isNodeMaterial = true;
  14667. /**
  14668. * Whether this material is affected by fog or not.
  14669. *
  14670. * @type {boolean}
  14671. * @default true
  14672. */
  14673. this.fog = true;
  14674. /**
  14675. * Whether this material is affected by lights or not.
  14676. *
  14677. * @type {boolean}
  14678. * @default false
  14679. */
  14680. this.lights = false;
  14681. /**
  14682. * Whether this material uses hardware clipping or not.
  14683. * This property is managed by the engine and should not be
  14684. * modified by apps.
  14685. *
  14686. * @type {boolean}
  14687. * @default false
  14688. */
  14689. this.hardwareClipping = false;
  14690. /**
  14691. * Node materials which set their `lights` property to `true`
  14692. * are affected by all lights of the scene. Sometimes selective
  14693. * lighting is wanted which means only _some_ lights in the scene
  14694. * affect a material. This can be achieved by creating an instance
  14695. * of {@link LightsNode} with a list of selective
  14696. * lights and assign the node to this property.
  14697. *
  14698. * ```js
  14699. * const customLightsNode = lights( [ light1, light2 ] );
  14700. * material.lightsNode = customLightsNode;
  14701. * ```
  14702. *
  14703. * @type {?LightsNode}
  14704. * @default null
  14705. */
  14706. this.lightsNode = null;
  14707. /**
  14708. * The environment of node materials can be defined by an environment
  14709. * map assigned to the `envMap` property or by `Scene.environment`
  14710. * if the node material is a PBR material. This node property allows to overwrite
  14711. * the default behavior and define the environment with a custom node.
  14712. *
  14713. * ```js
  14714. * material.envNode = pmremTexture( renderTarget.texture );
  14715. * ```
  14716. *
  14717. * @type {?Node<vec3>}
  14718. * @default null
  14719. */
  14720. this.envNode = null;
  14721. /**
  14722. * The lighting of node materials might be influenced by ambient occlusion.
  14723. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14724. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14725. * the default and define the ambient occlusion with a custom node instead.
  14726. *
  14727. * If you don't want to overwrite the diffuse color but modify the existing
  14728. * values instead, use {@link materialAO}.
  14729. *
  14730. * @type {?Node<float>}
  14731. * @default null
  14732. */
  14733. this.aoNode = null;
  14734. /**
  14735. * The diffuse color of node materials is by default inferred from the
  14736. * `color` and `map` properties. This node property allows to overwrite the default
  14737. * and define the diffuse color with a node instead.
  14738. *
  14739. * ```js
  14740. * material.colorNode = color( 0xff0000 ); // define red color
  14741. * ```
  14742. *
  14743. * If you don't want to overwrite the diffuse color but modify the existing
  14744. * values instead, use {@link materialColor}.
  14745. *
  14746. * ```js
  14747. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14748. * ```
  14749. *
  14750. * @type {?Node<vec3>}
  14751. * @default null
  14752. */
  14753. this.colorNode = null;
  14754. /**
  14755. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14756. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14757. * and define the normals with a node instead.
  14758. *
  14759. * If you don't want to overwrite the normals but modify the existing values instead,
  14760. * use {@link materialNormal}.
  14761. *
  14762. * @type {?Node<vec3>}
  14763. * @default null
  14764. */
  14765. this.normalNode = null;
  14766. /**
  14767. * The opacity of node materials is by default inferred from the `opacity`
  14768. * and `alphaMap` properties. This node property allows to overwrite the default
  14769. * and define the opacity with a node instead.
  14770. *
  14771. * If you don't want to overwrite the opacity but modify the existing
  14772. * value instead, use {@link materialOpacity}.
  14773. *
  14774. * @type {?Node<float>}
  14775. * @default null
  14776. */
  14777. this.opacityNode = null;
  14778. /**
  14779. * This node can be used to implement a variety of filter-like effects. The idea is
  14780. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14781. * to create an arbitrary effect and then assign the node composition to this property.
  14782. * Everything behind the object using this material will now be affected by a filter.
  14783. *
  14784. * ```js
  14785. * const material = new NodeMaterial()
  14786. * material.transparent = true;
  14787. *
  14788. * // everything behind the object will be monochromatic
  14789. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14790. * ```
  14791. *
  14792. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14793. *
  14794. * @type {?Node<vec3>}
  14795. * @default null
  14796. */
  14797. this.backdropNode = null;
  14798. /**
  14799. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14800. *
  14801. * @type {?Node<float>}
  14802. * @default null
  14803. */
  14804. this.backdropAlphaNode = null;
  14805. /**
  14806. * The alpha test of node materials is by default inferred from the `alphaTest`
  14807. * property. This node property allows to overwrite the default and define the
  14808. * alpha test with a node instead.
  14809. *
  14810. * If you don't want to overwrite the alpha test but modify the existing
  14811. * value instead, use {@link materialAlphaTest}.
  14812. *
  14813. * @type {?Node<float>}
  14814. * @default null
  14815. */
  14816. this.alphaTestNode = null;
  14817. /**
  14818. * Discards the fragment if the mask value is `false`.
  14819. *
  14820. * @type {?Node<bool>}
  14821. * @default null
  14822. */
  14823. this.maskNode = null;
  14824. /**
  14825. * This node can be used to implement a shadow mask for the material.
  14826. *
  14827. * @type {?Node<bool>}
  14828. * @default null
  14829. */
  14830. this.maskShadowNode = null;
  14831. /**
  14832. * The local vertex positions are computed based on multiple factors like the
  14833. * attribute data, morphing or skinning. This node property allows to overwrite
  14834. * the default and define local vertex positions with nodes instead.
  14835. *
  14836. * If you don't want to overwrite the vertex positions but modify the existing
  14837. * values instead, use {@link positionLocal}.
  14838. *
  14839. *```js
  14840. * material.positionNode = positionLocal.add( displace );
  14841. * ```
  14842. *
  14843. * @type {?Node<vec3>}
  14844. * @default null
  14845. */
  14846. this.positionNode = null;
  14847. /**
  14848. * This node property is intended for logic which modifies geometry data once or per animation step.
  14849. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14850. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14851. * can be implemented.
  14852. *
  14853. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14854. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14855. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14856. * eventually assigned to `geometryNode`.
  14857. *
  14858. * @type {?Function}
  14859. * @default null
  14860. */
  14861. this.geometryNode = null;
  14862. /**
  14863. * Allows to overwrite depth values in the fragment shader.
  14864. *
  14865. * @type {?Node<float>}
  14866. * @default null
  14867. */
  14868. this.depthNode = null;
  14869. /**
  14870. * Allows to overwrite the position used for shadow map rendering which
  14871. * is by default {@link positionWorld}, the vertex position
  14872. * in world space.
  14873. *
  14874. * @type {?Node<float>}
  14875. * @default null
  14876. */
  14877. this.receivedShadowPositionNode = null;
  14878. /**
  14879. * Allows to overwrite the geometry position used for shadow map projection which
  14880. * is by default {@link positionLocal}, the vertex position in local space.
  14881. *
  14882. * @type {?Node<float>}
  14883. * @default null
  14884. */
  14885. this.castShadowPositionNode = null;
  14886. /**
  14887. * This node can be used to influence how an object using this node material
  14888. * receive shadows.
  14889. *
  14890. * ```js
  14891. * const totalShadows = float( 1 ).toVar();
  14892. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14893. * totalShadows.mulAssign( shadow );
  14894. * //return float( 1 ); // bypass received shadows
  14895. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14896. * } );
  14897. *
  14898. * @type {?(Function|FunctionNode<vec4>)}
  14899. * @default null
  14900. */
  14901. this.receivedShadowNode = null;
  14902. /**
  14903. * This node can be used to influence how an object using this node material
  14904. * casts shadows. To apply a color to shadows, you can simply do:
  14905. *
  14906. * ```js
  14907. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14908. * ```
  14909. *
  14910. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14911. * is also common to use the property with `Fn` function so checks are performed
  14912. * per fragment.
  14913. *
  14914. * ```js
  14915. * materialCustomShadow.castShadowNode = Fn( () => {
  14916. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14917. * return materialColor;
  14918. * } )();
  14919. * ```
  14920. *
  14921. * @type {?Node<vec4>}
  14922. * @default null
  14923. */
  14924. this.castShadowNode = null;
  14925. /**
  14926. * This node can be used to define the final output of the material.
  14927. *
  14928. * TODO: Explain the differences to `fragmentNode`.
  14929. *
  14930. * @type {?Node<vec4>}
  14931. * @default null
  14932. */
  14933. this.outputNode = null;
  14934. /**
  14935. * MRT configuration is done on renderer or pass level. This node allows to
  14936. * overwrite what values are written into MRT targets on material level. This
  14937. * can be useful for implementing selective FX features that should only affect
  14938. * specific objects.
  14939. *
  14940. * @type {?MRTNode}
  14941. * @default null
  14942. */
  14943. this.mrtNode = null;
  14944. /**
  14945. * This node property can be used if you need complete freedom in implementing
  14946. * the fragment shader. Assigning a node will replace the built-in material
  14947. * logic used in the fragment stage.
  14948. *
  14949. * @type {?Node<vec4>}
  14950. * @default null
  14951. */
  14952. this.fragmentNode = null;
  14953. /**
  14954. * This node property can be used if you need complete freedom in implementing
  14955. * the vertex shader. Assigning a node will replace the built-in material logic
  14956. * used in the vertex stage.
  14957. *
  14958. * @type {?Node<vec4>}
  14959. * @default null
  14960. */
  14961. this.vertexNode = null;
  14962. /**
  14963. * This node can be used as a global context management component for this material.
  14964. *
  14965. * @type {?ContextNode}
  14966. * @default null
  14967. */
  14968. this.contextNode = null;
  14969. }
  14970. /**
  14971. * Returns an array of child nodes for this material.
  14972. *
  14973. * @private
  14974. * @returns {Array<{property: string, childNode: Node}>}
  14975. */
  14976. _getNodeChildren() {
  14977. const children = [];
  14978. for ( const property of Object.getOwnPropertyNames( this ) ) {
  14979. if ( property.startsWith( '_' ) === true ) continue;
  14980. const object = this[ property ];
  14981. if ( object && object.isNode === true ) {
  14982. children.push( { property, childNode: object } );
  14983. }
  14984. }
  14985. return children;
  14986. }
  14987. /**
  14988. * Allows to define a custom cache key that influence the material key computation
  14989. * for render objects.
  14990. *
  14991. * @return {string} The custom cache key.
  14992. */
  14993. customProgramCacheKey() {
  14994. const values = [];
  14995. for ( const { property, childNode } of this._getNodeChildren() ) {
  14996. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey() );
  14997. }
  14998. return this.type + hashArray( values );
  14999. }
  15000. /**
  15001. * Builds this material with the given node builder.
  15002. *
  15003. * @param {NodeBuilder} builder - The current node builder.
  15004. */
  15005. build( builder ) {
  15006. this.setup( builder );
  15007. }
  15008. /**
  15009. * Setups a node material observer with the given builder.
  15010. *
  15011. * @param {NodeBuilder} builder - The current node builder.
  15012. * @return {NodeMaterialObserver} The node material observer.
  15013. */
  15014. setupObserver( builder ) {
  15015. return new NodeMaterialObserver( builder );
  15016. }
  15017. /**
  15018. * Setups the vertex and fragment stage of this node material.
  15019. *
  15020. * @param {NodeBuilder} builder - The current node builder.
  15021. */
  15022. setup( builder ) {
  15023. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  15024. builder.context.setupPositionView = () => this.setupPositionView( builder );
  15025. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  15026. const renderer = builder.renderer;
  15027. const renderTarget = renderer.getRenderTarget();
  15028. // < VERTEX STAGE >
  15029. builder.addStack();
  15030. const mvp = this.setupVertex( builder );
  15031. const vertexNode = subBuild( this.vertexNode || mvp, 'VERTEX' );
  15032. builder.context.clipSpace = vertexNode;
  15033. builder.stack.outputNode = vertexNode;
  15034. this.setupHardwareClipping( builder );
  15035. if ( this.geometryNode !== null ) {
  15036. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  15037. }
  15038. builder.addFlow( 'vertex', builder.removeStack() );
  15039. // < FRAGMENT STAGE >
  15040. builder.addStack();
  15041. let resultNode;
  15042. const clippingNode = this.setupClipping( builder );
  15043. if ( this.depthWrite === true || this.depthTest === true ) {
  15044. // only write depth if depth buffer is configured
  15045. if ( renderTarget !== null ) {
  15046. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  15047. } else {
  15048. if ( renderer.depth === true ) this.setupDepth( builder );
  15049. }
  15050. }
  15051. if ( this.fragmentNode === null ) {
  15052. this.setupDiffuseColor( builder );
  15053. this.setupVariants( builder );
  15054. const outgoingLightNode = this.setupLighting( builder );
  15055. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  15056. // force unsigned floats - useful for RenderTargets
  15057. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  15058. resultNode = this.setupOutput( builder, basicOutput );
  15059. // OUTPUT NODE
  15060. output.assign( resultNode );
  15061. //
  15062. const isCustomOutput = this.outputNode !== null;
  15063. if ( isCustomOutput ) resultNode = this.outputNode;
  15064. //
  15065. if ( builder.context.getOutput ) {
  15066. resultNode = builder.context.getOutput( resultNode, builder );
  15067. }
  15068. // MRT
  15069. if ( renderTarget !== null ) {
  15070. const mrt = renderer.getMRT();
  15071. const materialMRT = this.mrtNode;
  15072. if ( mrt !== null ) {
  15073. if ( isCustomOutput ) output.assign( resultNode );
  15074. resultNode = mrt;
  15075. if ( materialMRT !== null ) {
  15076. resultNode = mrt.merge( materialMRT );
  15077. }
  15078. } else if ( materialMRT !== null ) {
  15079. resultNode = materialMRT;
  15080. }
  15081. }
  15082. } else {
  15083. let fragmentNode = this.fragmentNode;
  15084. if ( fragmentNode.isOutputStructNode !== true ) {
  15085. fragmentNode = vec4( fragmentNode );
  15086. }
  15087. resultNode = this.setupOutput( builder, fragmentNode );
  15088. }
  15089. builder.stack.outputNode = resultNode;
  15090. builder.addFlow( 'fragment', builder.removeStack() );
  15091. // < OBSERVER >
  15092. builder.observer = this.setupObserver( builder );
  15093. }
  15094. /**
  15095. * Setups the clipping node.
  15096. *
  15097. * @param {NodeBuilder} builder - The current node builder.
  15098. * @return {ClippingNode} The clipping node.
  15099. */
  15100. setupClipping( builder ) {
  15101. if ( builder.clippingContext === null ) return null;
  15102. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  15103. let result = null;
  15104. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  15105. const samples = builder.renderer.currentSamples;
  15106. if ( this.alphaToCoverage && samples > 1 ) {
  15107. // to be added to flow when the color/alpha value has been determined
  15108. result = clippingAlpha();
  15109. } else {
  15110. builder.stack.addToStack( clipping() );
  15111. }
  15112. }
  15113. return result;
  15114. }
  15115. /**
  15116. * Setups the hardware clipping if available on the current device.
  15117. *
  15118. * @param {NodeBuilder} builder - The current node builder.
  15119. */
  15120. setupHardwareClipping( builder ) {
  15121. this.hardwareClipping = false;
  15122. if ( builder.clippingContext === null ) return;
  15123. const candidateCount = builder.clippingContext.unionPlanes.length;
  15124. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  15125. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  15126. builder.stack.addToStack( hardwareClipping() );
  15127. this.hardwareClipping = true;
  15128. }
  15129. return;
  15130. }
  15131. /**
  15132. * Setups the depth of this material.
  15133. *
  15134. * @param {NodeBuilder} builder - The current node builder.
  15135. */
  15136. setupDepth( builder ) {
  15137. const { renderer, camera } = builder;
  15138. // Depth
  15139. let depthNode = this.depthNode;
  15140. if ( depthNode === null ) {
  15141. const mrt = renderer.getMRT();
  15142. if ( mrt && mrt.has( 'depth' ) ) {
  15143. depthNode = mrt.get( 'depth' );
  15144. } else if ( renderer.logarithmicDepthBuffer === true ) {
  15145. if ( camera.isPerspectiveCamera ) {
  15146. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  15147. } else {
  15148. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  15149. }
  15150. }
  15151. }
  15152. if ( depthNode !== null ) {
  15153. depth.assign( depthNode ).toStack();
  15154. }
  15155. }
  15156. /**
  15157. * Setups the position node in view space. This method exists
  15158. * so derived node materials can modify the implementation e.g. sprite materials.
  15159. *
  15160. * @param {NodeBuilder} builder - The current node builder.
  15161. * @return {Node<vec3>} The position in view space.
  15162. */
  15163. setupPositionView( /*builder*/ ) {
  15164. return modelViewMatrix.mul( positionLocal ).xyz;
  15165. }
  15166. /**
  15167. * Setups the position in clip space.
  15168. *
  15169. * @param {NodeBuilder} builder - The current node builder.
  15170. * @return {Node<vec4>} The position in view space.
  15171. */
  15172. setupModelViewProjection( /*builder*/ ) {
  15173. return cameraProjectionMatrix.mul( positionView );
  15174. }
  15175. /**
  15176. * Setups the logic for the vertex stage.
  15177. *
  15178. * @param {NodeBuilder} builder - The current node builder.
  15179. * @return {Node<vec4>} The position in clip space.
  15180. */
  15181. setupVertex( builder ) {
  15182. builder.addStack();
  15183. this.setupPosition( builder );
  15184. builder.context.position = builder.removeStack();
  15185. return modelViewProjection;
  15186. }
  15187. /**
  15188. * Setups the computation of the position in local space.
  15189. *
  15190. * @param {NodeBuilder} builder - The current node builder.
  15191. * @return {Node<vec3>} The position in local space.
  15192. */
  15193. setupPosition( builder ) {
  15194. const { object, geometry } = builder;
  15195. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  15196. morphReference( object ).toStack();
  15197. }
  15198. if ( object.isSkinnedMesh === true ) {
  15199. skinning( object ).toStack();
  15200. }
  15201. if ( this.displacementMap ) {
  15202. const displacementMap = materialReference( 'displacementMap', 'texture' );
  15203. const displacementScale = materialReference( 'displacementScale', 'float' );
  15204. const displacementBias = materialReference( 'displacementBias', 'float' );
  15205. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  15206. }
  15207. if ( object.isBatchedMesh ) {
  15208. batch( object ).toStack();
  15209. }
  15210. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  15211. instancedMesh( object ).toStack();
  15212. }
  15213. if ( this.positionNode !== null ) {
  15214. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  15215. }
  15216. return positionLocal;
  15217. }
  15218. /**
  15219. * Setups the computation of the material's diffuse color.
  15220. *
  15221. * @param {NodeBuilder} builder - The current node builder.
  15222. * @param {BufferGeometry} geometry - The geometry.
  15223. */
  15224. setupDiffuseColor( builder ) {
  15225. const { object, geometry } = builder;
  15226. // MASK
  15227. if ( this.maskNode !== null ) {
  15228. // Discard if the mask is `false`
  15229. bool( this.maskNode ).not().discard();
  15230. }
  15231. // COLOR
  15232. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  15233. // VERTEX COLORS
  15234. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  15235. colorNode = colorNode.mul( vertexColor() );
  15236. }
  15237. // INSTANCED COLORS
  15238. if ( object.instanceColor ) {
  15239. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  15240. colorNode = instanceColor.mul( colorNode );
  15241. }
  15242. if ( object.isBatchedMesh && object._colorsTexture ) {
  15243. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  15244. colorNode = batchColor.mul( colorNode );
  15245. }
  15246. // DIFFUSE COLOR
  15247. diffuseColor.assign( colorNode );
  15248. // OPACITY
  15249. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15250. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  15251. // ALPHA TEST
  15252. let alphaTestNode = null;
  15253. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  15254. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  15255. if ( this.alphaToCoverage === true ) {
  15256. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  15257. diffuseColor.a.lessThanEqual( 0 ).discard();
  15258. } else {
  15259. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  15260. }
  15261. }
  15262. // ALPHA HASH
  15263. if ( this.alphaHash === true ) {
  15264. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  15265. }
  15266. // OPAQUE
  15267. if ( builder.isOpaque() ) {
  15268. diffuseColor.a.assign( 1.0 );
  15269. }
  15270. }
  15271. /**
  15272. * Abstract interface method that can be implemented by derived materials
  15273. * to setup material-specific node variables.
  15274. *
  15275. * @abstract
  15276. * @param {NodeBuilder} builder - The current node builder.
  15277. */
  15278. setupVariants( /*builder*/ ) {
  15279. // Interface function.
  15280. }
  15281. /**
  15282. * Setups the outgoing light node variable
  15283. *
  15284. * @return {Node<vec3>} The outgoing light node.
  15285. */
  15286. setupOutgoingLight() {
  15287. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  15288. }
  15289. /**
  15290. * Setups the normal node from the material.
  15291. *
  15292. * @return {Node<vec3>} The normal node.
  15293. */
  15294. setupNormal() {
  15295. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  15296. }
  15297. /**
  15298. * Setups the environment node from the material.
  15299. *
  15300. * @param {NodeBuilder} builder - The current node builder.
  15301. * @return {Node<vec4>} The environment node.
  15302. */
  15303. setupEnvironment( /*builder*/ ) {
  15304. let node = null;
  15305. if ( this.envNode ) {
  15306. node = this.envNode;
  15307. } else if ( this.envMap ) {
  15308. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  15309. }
  15310. return node;
  15311. }
  15312. /**
  15313. * Setups the light map node from the material.
  15314. *
  15315. * @param {NodeBuilder} builder - The current node builder.
  15316. * @return {Node<vec3>} The light map node.
  15317. */
  15318. setupLightMap( builder ) {
  15319. let node = null;
  15320. if ( builder.material.lightMap ) {
  15321. node = new IrradianceNode( materialLightMap );
  15322. }
  15323. return node;
  15324. }
  15325. /**
  15326. * Setups the lights node based on the scene, environment and material.
  15327. *
  15328. * @param {NodeBuilder} builder - The current node builder.
  15329. * @return {LightsNode} The lights node.
  15330. */
  15331. setupLights( builder ) {
  15332. const materialLightsNode = [];
  15333. //
  15334. const envNode = this.setupEnvironment( builder );
  15335. if ( envNode && envNode.isLightingNode ) {
  15336. materialLightsNode.push( envNode );
  15337. }
  15338. const lightMapNode = this.setupLightMap( builder );
  15339. if ( lightMapNode && lightMapNode.isLightingNode ) {
  15340. materialLightsNode.push( lightMapNode );
  15341. }
  15342. let aoNode = this.aoNode;
  15343. if ( aoNode === null && builder.material.aoMap ) {
  15344. aoNode = materialAO;
  15345. }
  15346. if ( builder.context.getAO ) {
  15347. aoNode = builder.context.getAO( aoNode, builder );
  15348. }
  15349. if ( aoNode ) {
  15350. materialLightsNode.push( new AONode( aoNode ) );
  15351. }
  15352. let lightsN = this.lightsNode || builder.lightsNode;
  15353. if ( materialLightsNode.length > 0 ) {
  15354. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  15355. }
  15356. return lightsN;
  15357. }
  15358. /**
  15359. * This method should be implemented by most derived materials
  15360. * since it defines the material's lighting model.
  15361. *
  15362. * @abstract
  15363. * @param {NodeBuilder} builder - The current node builder.
  15364. * @return {LightingModel} The lighting model.
  15365. */
  15366. setupLightingModel( /*builder*/ ) {
  15367. // Interface function.
  15368. }
  15369. /**
  15370. * Setups the outgoing light node.
  15371. *
  15372. * @param {NodeBuilder} builder - The current node builder.
  15373. * @return {Node<vec3>} The outgoing light node.
  15374. */
  15375. setupLighting( builder ) {
  15376. const { material } = builder;
  15377. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  15378. // OUTGOING LIGHT
  15379. const lights = this.lights === true || this.lightsNode !== null;
  15380. const lightsNode = lights ? this.setupLights( builder ) : null;
  15381. let outgoingLightNode = this.setupOutgoingLight( builder );
  15382. if ( lightsNode && lightsNode.getScope().hasLights ) {
  15383. const lightingModel = this.setupLightingModel( builder ) || null;
  15384. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  15385. } else if ( backdropNode !== null ) {
  15386. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  15387. }
  15388. // EMISSIVE
  15389. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  15390. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  15391. outgoingLightNode = outgoingLightNode.add( emissive );
  15392. }
  15393. return outgoingLightNode;
  15394. }
  15395. /**
  15396. * Setup the fog.
  15397. *
  15398. * @param {NodeBuilder} builder - The current node builder.
  15399. * @param {Node<vec4>} outputNode - The existing output node.
  15400. * @return {Node<vec4>} The output node.
  15401. */
  15402. setupFog( builder, outputNode ) {
  15403. const fogNode = builder.fogNode;
  15404. if ( fogNode ) {
  15405. output.assign( outputNode );
  15406. outputNode = vec4( fogNode.toVar() );
  15407. }
  15408. return outputNode;
  15409. }
  15410. /**
  15411. * Setups premultiplied alpha.
  15412. *
  15413. * @param {NodeBuilder} builder - The current node builder.
  15414. * @param {Node<vec4>} outputNode - The existing output node.
  15415. * @return {Node<vec4>} The output node.
  15416. */
  15417. setupPremultipliedAlpha( builder, outputNode ) {
  15418. return premultiplyAlpha( outputNode );
  15419. }
  15420. /**
  15421. * Setups the output node.
  15422. *
  15423. * @param {NodeBuilder} builder - The current node builder.
  15424. * @param {Node<vec4>} outputNode - The existing output node.
  15425. * @return {Node<vec4>} The output node.
  15426. */
  15427. setupOutput( builder, outputNode ) {
  15428. // FOG
  15429. if ( this.fog === true ) {
  15430. outputNode = this.setupFog( builder, outputNode );
  15431. }
  15432. // PREMULTIPLIED ALPHA
  15433. if ( this.premultipliedAlpha === true ) {
  15434. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  15435. }
  15436. return outputNode;
  15437. }
  15438. /**
  15439. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  15440. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  15441. * defining all material properties of the classic type in the node type.
  15442. *
  15443. * @param {Material} material - The material to copy properties with their values to this node material.
  15444. */
  15445. setDefaultValues( material ) {
  15446. // This approach is to reuse the native refreshUniforms*
  15447. // and turn available the use of features like transmission and environment in core
  15448. for ( const property in material ) {
  15449. const value = material[ property ];
  15450. if ( this[ property ] === undefined ) {
  15451. this[ property ] = value;
  15452. if ( value && value.clone ) this[ property ] = value.clone();
  15453. }
  15454. }
  15455. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  15456. for ( const key in descriptors ) {
  15457. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  15458. descriptors[ key ].get !== undefined ) {
  15459. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  15460. }
  15461. }
  15462. }
  15463. /**
  15464. * Serializes this material to JSON.
  15465. *
  15466. * @param {?(Object|string)} meta - The meta information for serialization.
  15467. * @return {Object} The serialized node.
  15468. */
  15469. toJSON( meta ) {
  15470. const isRoot = ( meta === undefined || typeof meta === 'string' );
  15471. if ( isRoot ) {
  15472. meta = {
  15473. textures: {},
  15474. images: {},
  15475. nodes: {}
  15476. };
  15477. }
  15478. const data = Material.prototype.toJSON.call( this, meta );
  15479. data.inputNodes = {};
  15480. for ( const { property, childNode } of this._getNodeChildren() ) {
  15481. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  15482. }
  15483. // TODO: Copied from Object3D.toJSON
  15484. function extractFromCache( cache ) {
  15485. const values = [];
  15486. for ( const key in cache ) {
  15487. const data = cache[ key ];
  15488. delete data.metadata;
  15489. values.push( data );
  15490. }
  15491. return values;
  15492. }
  15493. if ( isRoot ) {
  15494. const textures = extractFromCache( meta.textures );
  15495. const images = extractFromCache( meta.images );
  15496. const nodes = extractFromCache( meta.nodes );
  15497. if ( textures.length > 0 ) data.textures = textures;
  15498. if ( images.length > 0 ) data.images = images;
  15499. if ( nodes.length > 0 ) data.nodes = nodes;
  15500. }
  15501. return data;
  15502. }
  15503. /**
  15504. * Copies the properties of the given node material to this instance.
  15505. *
  15506. * @param {NodeMaterial} source - The material to copy.
  15507. * @return {NodeMaterial} A reference to this node material.
  15508. */
  15509. copy( source ) {
  15510. this.lightsNode = source.lightsNode;
  15511. this.envNode = source.envNode;
  15512. this.aoNode = source.aoNode;
  15513. this.colorNode = source.colorNode;
  15514. this.normalNode = source.normalNode;
  15515. this.opacityNode = source.opacityNode;
  15516. this.backdropNode = source.backdropNode;
  15517. this.backdropAlphaNode = source.backdropAlphaNode;
  15518. this.alphaTestNode = source.alphaTestNode;
  15519. this.maskNode = source.maskNode;
  15520. this.maskShadowNode = source.maskShadowNode;
  15521. this.positionNode = source.positionNode;
  15522. this.geometryNode = source.geometryNode;
  15523. this.depthNode = source.depthNode;
  15524. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  15525. this.castShadowPositionNode = source.castShadowPositionNode;
  15526. this.receivedShadowNode = source.receivedShadowNode;
  15527. this.castShadowNode = source.castShadowNode;
  15528. this.outputNode = source.outputNode;
  15529. this.mrtNode = source.mrtNode;
  15530. this.fragmentNode = source.fragmentNode;
  15531. this.vertexNode = source.vertexNode;
  15532. this.contextNode = source.contextNode;
  15533. return super.copy( source );
  15534. }
  15535. }
  15536. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  15537. /**
  15538. * Node material version of {@link LineBasicMaterial}.
  15539. *
  15540. * @augments NodeMaterial
  15541. */
  15542. class LineBasicNodeMaterial extends NodeMaterial {
  15543. static get type() {
  15544. return 'LineBasicNodeMaterial';
  15545. }
  15546. /**
  15547. * Constructs a new line basic node material.
  15548. *
  15549. * @param {Object} [parameters] - The configuration parameter.
  15550. */
  15551. constructor( parameters ) {
  15552. super();
  15553. /**
  15554. * This flag can be used for type testing.
  15555. *
  15556. * @type {boolean}
  15557. * @readonly
  15558. * @default true
  15559. */
  15560. this.isLineBasicNodeMaterial = true;
  15561. this.setDefaultValues( _defaultValues$d );
  15562. this.setValues( parameters );
  15563. }
  15564. }
  15565. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  15566. /**
  15567. * Node material version of {@link LineDashedMaterial}.
  15568. *
  15569. * @augments NodeMaterial
  15570. */
  15571. class LineDashedNodeMaterial extends NodeMaterial {
  15572. static get type() {
  15573. return 'LineDashedNodeMaterial';
  15574. }
  15575. /**
  15576. * Constructs a new line dashed node material.
  15577. *
  15578. * @param {Object} [parameters] - The configuration parameter.
  15579. */
  15580. constructor( parameters ) {
  15581. super();
  15582. /**
  15583. * This flag can be used for type testing.
  15584. *
  15585. * @type {boolean}
  15586. * @readonly
  15587. * @default true
  15588. */
  15589. this.isLineDashedNodeMaterial = true;
  15590. this.setDefaultValues( _defaultValues$c );
  15591. /**
  15592. * The dash offset.
  15593. *
  15594. * @type {number}
  15595. * @default 0
  15596. */
  15597. this.dashOffset = 0;
  15598. /**
  15599. * The offset of dash materials is by default inferred from the `dashOffset`
  15600. * property. This node property allows to overwrite the default
  15601. * and define the offset with a node instead.
  15602. *
  15603. * If you don't want to overwrite the offset but modify the existing
  15604. * value instead, use {@link materialLineDashOffset}.
  15605. *
  15606. * @type {?Node<float>}
  15607. * @default null
  15608. */
  15609. this.offsetNode = null;
  15610. /**
  15611. * The scale of dash materials is by default inferred from the `scale`
  15612. * property. This node property allows to overwrite the default
  15613. * and define the scale with a node instead.
  15614. *
  15615. * If you don't want to overwrite the scale but modify the existing
  15616. * value instead, use {@link materialLineScale}.
  15617. *
  15618. * @type {?Node<float>}
  15619. * @default null
  15620. */
  15621. this.dashScaleNode = null;
  15622. /**
  15623. * The dash size of dash materials is by default inferred from the `dashSize`
  15624. * property. This node property allows to overwrite the default
  15625. * and define the dash size with a node instead.
  15626. *
  15627. * If you don't want to overwrite the dash size but modify the existing
  15628. * value instead, use {@link materialLineDashSize}.
  15629. *
  15630. * @type {?Node<float>}
  15631. * @default null
  15632. */
  15633. this.dashSizeNode = null;
  15634. /**
  15635. * The gap size of dash materials is by default inferred from the `gapSize`
  15636. * property. This node property allows to overwrite the default
  15637. * and define the gap size with a node instead.
  15638. *
  15639. * If you don't want to overwrite the gap size but modify the existing
  15640. * value instead, use {@link materialLineGapSize}.
  15641. *
  15642. * @type {?Node<float>}
  15643. * @default null
  15644. */
  15645. this.gapSizeNode = null;
  15646. this.setValues( parameters );
  15647. }
  15648. /**
  15649. * Setups the dash specific node variables.
  15650. *
  15651. * @param {NodeBuilder} builder - The current node builder.
  15652. */
  15653. setupVariants( /* builder */ ) {
  15654. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15655. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15656. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15657. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15658. dashSize.assign( dashSizeNode );
  15659. gapSize.assign( gapSizeNode );
  15660. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  15661. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  15662. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  15663. }
  15664. }
  15665. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  15666. /**
  15667. * This node material can be used to render lines with a size larger than one
  15668. * by representing them as instanced meshes.
  15669. *
  15670. * @augments NodeMaterial
  15671. */
  15672. class Line2NodeMaterial extends NodeMaterial {
  15673. static get type() {
  15674. return 'Line2NodeMaterial';
  15675. }
  15676. /**
  15677. * Constructs a new node material for wide line rendering.
  15678. *
  15679. * @param {Object} [parameters={}] - The configuration parameter.
  15680. */
  15681. constructor( parameters = {} ) {
  15682. super();
  15683. /**
  15684. * This flag can be used for type testing.
  15685. *
  15686. * @type {boolean}
  15687. * @readonly
  15688. * @default true
  15689. */
  15690. this.isLine2NodeMaterial = true;
  15691. this.setDefaultValues( _defaultValues$b );
  15692. /**
  15693. * Whether vertex colors should be used or not.
  15694. *
  15695. * @type {boolean}
  15696. * @default false
  15697. */
  15698. this.vertexColors = parameters.vertexColors;
  15699. /**
  15700. * The dash offset.
  15701. *
  15702. * @type {number}
  15703. * @default 0
  15704. */
  15705. this.dashOffset = 0;
  15706. /**
  15707. * Defines the lines color.
  15708. *
  15709. * @type {?Node<vec3>}
  15710. * @default null
  15711. */
  15712. this.lineColorNode = null;
  15713. /**
  15714. * Defines the offset.
  15715. *
  15716. * @type {?Node<float>}
  15717. * @default null
  15718. */
  15719. this.offsetNode = null;
  15720. /**
  15721. * Defines the dash scale.
  15722. *
  15723. * @type {?Node<float>}
  15724. * @default null
  15725. */
  15726. this.dashScaleNode = null;
  15727. /**
  15728. * Defines the dash size.
  15729. *
  15730. * @type {?Node<float>}
  15731. * @default null
  15732. */
  15733. this.dashSizeNode = null;
  15734. /**
  15735. * Defines the gap size.
  15736. *
  15737. * @type {?Node<float>}
  15738. * @default null
  15739. */
  15740. this.gapSizeNode = null;
  15741. /**
  15742. * Blending is set to `NoBlending` since transparency
  15743. * is not supported, yet.
  15744. *
  15745. * @type {number}
  15746. * @default 0
  15747. */
  15748. this.blending = NoBlending;
  15749. this._useDash = parameters.dashed;
  15750. this._useAlphaToCoverage = true;
  15751. this._useWorldUnits = false;
  15752. this.setValues( parameters );
  15753. }
  15754. /**
  15755. * Setups the vertex and fragment stage of this node material.
  15756. *
  15757. * @param {NodeBuilder} builder - The current node builder.
  15758. */
  15759. setup( builder ) {
  15760. const { renderer } = builder;
  15761. const useAlphaToCoverage = this._useAlphaToCoverage;
  15762. const vertexColors = this.vertexColors;
  15763. const useDash = this._useDash;
  15764. const useWorldUnits = this._useWorldUnits;
  15765. const trimSegment = Fn( ( { start, end } ) => {
  15766. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15767. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15768. const nearEstimate = b.mul( -0.5 ).div( a );
  15769. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15770. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15771. } ).setLayout( {
  15772. name: 'trimSegment',
  15773. type: 'vec4',
  15774. inputs: [
  15775. { name: 'start', type: 'vec4' },
  15776. { name: 'end', type: 'vec4' }
  15777. ]
  15778. } );
  15779. this.vertexNode = Fn( () => {
  15780. const instanceStart = attribute( 'instanceStart' );
  15781. const instanceEnd = attribute( 'instanceEnd' );
  15782. // camera space
  15783. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15784. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15785. if ( useDash ) {
  15786. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15787. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15788. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15789. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15790. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15791. lineDistance = lineDistance.add( offsetNode );
  15792. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15793. }
  15794. if ( useWorldUnits ) {
  15795. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15796. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15797. }
  15798. const aspect = viewport.z.div( viewport.w );
  15799. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15800. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15801. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15802. // perhaps there is a more elegant solution -- WestLangley
  15803. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15804. If( perspective, () => {
  15805. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15806. end.assign( trimSegment( { start: start, end: end } ) );
  15807. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15808. start.assign( trimSegment( { start: end, end: start } ) );
  15809. } );
  15810. } );
  15811. // clip space
  15812. const clipStart = cameraProjectionMatrix.mul( start );
  15813. const clipEnd = cameraProjectionMatrix.mul( end );
  15814. // ndc space
  15815. const ndcStart = clipStart.xyz.div( clipStart.w );
  15816. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15817. // direction
  15818. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15819. // account for clip-space aspect ratio
  15820. dir.x.assign( dir.x.mul( aspect ) );
  15821. dir.assign( dir.normalize() );
  15822. const clip = vec4().toVar();
  15823. if ( useWorldUnits ) {
  15824. // get the offset direction as perpendicular to the view vector
  15825. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15826. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15827. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15828. const worldFwd = worldDir.cross( worldUp );
  15829. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15830. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15831. // height offset
  15832. const hw = materialLineWidth.mul( 0.5 );
  15833. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15834. // don't extend the line if we're rendering dashes because we
  15835. // won't be rendering the endcaps
  15836. if ( ! useDash ) {
  15837. // cap extension
  15838. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15839. // add width to the box
  15840. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15841. // endcaps
  15842. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15843. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15844. } );
  15845. }
  15846. // project the worldpos
  15847. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15848. // shift the depth of the projected points so the line
  15849. // segments overlap neatly
  15850. const clipPose = vec3().toVar();
  15851. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15852. clip.z.assign( clipPose.z.mul( clip.w ) );
  15853. } else {
  15854. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15855. // undo aspect ratio adjustment
  15856. dir.x.assign( dir.x.div( aspect ) );
  15857. offset.x.assign( offset.x.div( aspect ) );
  15858. // sign flip
  15859. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15860. // endcaps
  15861. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15862. offset.assign( offset.sub( dir ) );
  15863. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15864. offset.assign( offset.add( dir ) );
  15865. } );
  15866. // adjust for linewidth
  15867. offset.assign( offset.mul( materialLineWidth ) );
  15868. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15869. offset.assign( offset.div( viewport.w.div( screenDPR ) ) );
  15870. // select end
  15871. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15872. // back to clip space
  15873. offset.assign( offset.mul( clip.w ) );
  15874. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15875. }
  15876. return clip;
  15877. } )();
  15878. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15879. const p13 = p1.sub( p3 );
  15880. const p43 = p4.sub( p3 );
  15881. const p21 = p2.sub( p1 );
  15882. const d1343 = p13.dot( p43 );
  15883. const d4321 = p43.dot( p21 );
  15884. const d1321 = p13.dot( p21 );
  15885. const d4343 = p43.dot( p43 );
  15886. const d2121 = p21.dot( p21 );
  15887. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15888. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15889. const mua = numer.div( denom ).clamp();
  15890. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15891. return vec2( mua, mub );
  15892. } );
  15893. this.colorNode = Fn( () => {
  15894. const vUv = uv$1();
  15895. if ( useDash ) {
  15896. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15897. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15898. dashSize.assign( dashSizeNode );
  15899. gapSize.assign( gapSizeNode );
  15900. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15901. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15902. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15903. }
  15904. const alpha = float( 1 ).toVar( 'alpha' );
  15905. if ( useWorldUnits ) {
  15906. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15907. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15908. // Find the closest points on the view ray and the line segment
  15909. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15910. const lineDir = worldEnd.sub( worldStart );
  15911. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15912. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15913. const p2 = rayEnd.mul( params.y );
  15914. const delta = p1.sub( p2 );
  15915. const len = delta.length();
  15916. const norm = len.div( materialLineWidth );
  15917. if ( ! useDash ) {
  15918. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15919. const dnorm = norm.fwidth();
  15920. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15921. } else {
  15922. norm.greaterThan( 0.5 ).discard();
  15923. }
  15924. }
  15925. } else {
  15926. // round endcaps
  15927. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15928. const a = vUv.x;
  15929. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15930. const len2 = a.mul( a ).add( b.mul( b ) );
  15931. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15932. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15933. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15934. } );
  15935. } else {
  15936. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15937. const a = vUv.x;
  15938. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15939. const len2 = a.mul( a ).add( b.mul( b ) );
  15940. len2.greaterThan( 1.0 ).discard();
  15941. } );
  15942. }
  15943. }
  15944. let lineColorNode;
  15945. if ( this.lineColorNode ) {
  15946. lineColorNode = this.lineColorNode;
  15947. } else {
  15948. if ( vertexColors ) {
  15949. const instanceColorStart = attribute( 'instanceColorStart' );
  15950. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15951. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15952. lineColorNode = instanceColor.mul( materialColor );
  15953. } else {
  15954. lineColorNode = materialColor;
  15955. }
  15956. }
  15957. return vec4( lineColorNode, alpha );
  15958. } )();
  15959. if ( this.transparent ) {
  15960. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15961. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportOpaqueMipTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15962. }
  15963. super.setup( builder );
  15964. }
  15965. /**
  15966. * Whether the lines should sized in world units or not.
  15967. * When set to `false` the unit is pixel.
  15968. *
  15969. * @type {boolean}
  15970. * @default false
  15971. */
  15972. get worldUnits() {
  15973. return this._useWorldUnits;
  15974. }
  15975. set worldUnits( value ) {
  15976. if ( this._useWorldUnits !== value ) {
  15977. this._useWorldUnits = value;
  15978. this.needsUpdate = true;
  15979. }
  15980. }
  15981. /**
  15982. * Whether the lines should be dashed or not.
  15983. *
  15984. * @type {boolean}
  15985. * @default false
  15986. */
  15987. get dashed() {
  15988. return this._useDash;
  15989. }
  15990. set dashed( value ) {
  15991. if ( this._useDash !== value ) {
  15992. this._useDash = value;
  15993. this.needsUpdate = true;
  15994. }
  15995. }
  15996. /**
  15997. * Whether alpha to coverage should be used or not.
  15998. *
  15999. * @type {boolean}
  16000. * @default true
  16001. */
  16002. get alphaToCoverage() {
  16003. return this._useAlphaToCoverage;
  16004. }
  16005. set alphaToCoverage( value ) {
  16006. if ( this._useAlphaToCoverage !== value ) {
  16007. this._useAlphaToCoverage = value;
  16008. this.needsUpdate = true;
  16009. }
  16010. }
  16011. /**
  16012. * Copies the properties of the given material to this instance.
  16013. *
  16014. * @param {Line2NodeMaterial} source - The material to copy.
  16015. * @return {Line2NodeMaterial} A reference to this material.
  16016. */
  16017. copy( source ) {
  16018. super.copy( source );
  16019. this.vertexColors = source.vertexColors;
  16020. this.dashOffset = source.dashOffset;
  16021. this.lineColorNode = source.lineColorNode;
  16022. this.offsetNode = source.offsetNode;
  16023. this.dashScaleNode = source.dashScaleNode;
  16024. this.dashSizeNode = source.dashSizeNode;
  16025. this.gapSizeNode = source.gapSizeNode;
  16026. this._useDash = source._useDash;
  16027. this._useAlphaToCoverage = source._useAlphaToCoverage;
  16028. this._useWorldUnits = source._useWorldUnits;
  16029. return this;
  16030. }
  16031. }
  16032. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  16033. /**
  16034. * Node material version of {@link MeshNormalMaterial}.
  16035. *
  16036. * @augments NodeMaterial
  16037. */
  16038. class MeshNormalNodeMaterial extends NodeMaterial {
  16039. static get type() {
  16040. return 'MeshNormalNodeMaterial';
  16041. }
  16042. /**
  16043. * Constructs a new mesh normal node material.
  16044. *
  16045. * @param {Object} [parameters] - The configuration parameter.
  16046. */
  16047. constructor( parameters ) {
  16048. super();
  16049. /**
  16050. * This flag can be used for type testing.
  16051. *
  16052. * @type {boolean}
  16053. * @readonly
  16054. * @default true
  16055. */
  16056. this.isMeshNormalNodeMaterial = true;
  16057. this.setDefaultValues( _defaultValues$a );
  16058. this.setValues( parameters );
  16059. }
  16060. /**
  16061. * Overwrites the default implementation by computing the diffuse color
  16062. * based on the normal data.
  16063. */
  16064. setupDiffuseColor() {
  16065. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  16066. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  16067. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  16068. }
  16069. }
  16070. /**
  16071. * TSL function for creating an equirect uv node.
  16072. *
  16073. * Can be used to compute texture coordinates for projecting an
  16074. * equirectangular texture onto a mesh for using it as the scene's
  16075. * background.
  16076. *
  16077. * ```js
  16078. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  16079. * ```
  16080. *
  16081. * @tsl
  16082. * @function
  16083. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  16084. * @returns {Node<vec2>}
  16085. */
  16086. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  16087. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  16088. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  16089. return vec2( u, v );
  16090. } );
  16091. /**
  16092. * This class represents a cube render target. It is a special version
  16093. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  16094. *
  16095. * @augments RenderTarget
  16096. */
  16097. class CubeRenderTarget extends RenderTarget {
  16098. /**
  16099. * Constructs a new cube render target.
  16100. *
  16101. * @param {number} [size=1] - The size of the render target.
  16102. * @param {RenderTarget~Options} [options] - The configuration object.
  16103. */
  16104. constructor( size = 1, options = {} ) {
  16105. super( size, size, options );
  16106. /**
  16107. * This flag can be used for type testing.
  16108. *
  16109. * @type {boolean}
  16110. * @readonly
  16111. * @default true
  16112. */
  16113. this.isCubeRenderTarget = true;
  16114. const image = { width: size, height: size, depth: 1 };
  16115. const images = [ image, image, image, image, image, image ];
  16116. /**
  16117. * Overwritten with a different texture type.
  16118. *
  16119. * @type {DataArrayTexture}
  16120. */
  16121. this.texture = new CubeTexture( images );
  16122. this._setTextureOptions( options );
  16123. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16124. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16125. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16126. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16127. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16128. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16129. this.texture.isRenderTargetTexture = true;
  16130. }
  16131. /**
  16132. * Converts the given equirectangular texture to a cube map.
  16133. *
  16134. * @param {Renderer} renderer - The renderer.
  16135. * @param {Texture} texture - The equirectangular texture.
  16136. * @return {CubeRenderTarget} A reference to this cube render target.
  16137. */
  16138. fromEquirectangularTexture( renderer, texture$1 ) {
  16139. const currentMinFilter = texture$1.minFilter;
  16140. const currentGenerateMipmaps = texture$1.generateMipmaps;
  16141. texture$1.generateMipmaps = true;
  16142. this.texture.type = texture$1.type;
  16143. this.texture.colorSpace = texture$1.colorSpace;
  16144. this.texture.generateMipmaps = texture$1.generateMipmaps;
  16145. this.texture.minFilter = texture$1.minFilter;
  16146. this.texture.magFilter = texture$1.magFilter;
  16147. const geometry = new BoxGeometry( 5, 5, 5 );
  16148. const uvNode = equirectUV( positionWorldDirection );
  16149. const material = new NodeMaterial();
  16150. material.colorNode = texture( texture$1, uvNode, 0 );
  16151. material.side = BackSide;
  16152. material.blending = NoBlending;
  16153. const mesh = new Mesh( geometry, material );
  16154. const scene = new Scene();
  16155. scene.add( mesh );
  16156. // Avoid blurred poles
  16157. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  16158. const camera = new CubeCamera( 1, 10, this );
  16159. const currentMRT = renderer.getMRT();
  16160. renderer.setMRT( null );
  16161. camera.update( renderer, scene );
  16162. renderer.setMRT( currentMRT );
  16163. texture$1.minFilter = currentMinFilter;
  16164. texture$1.generateMipmaps = currentGenerateMipmaps;
  16165. mesh.geometry.dispose();
  16166. mesh.material.dispose();
  16167. return this;
  16168. }
  16169. /**
  16170. * Clears this cube render target.
  16171. *
  16172. * @param {Renderer} renderer - The renderer.
  16173. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16174. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16175. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16176. */
  16177. clear( renderer, color = true, depth = true, stencil = true ) {
  16178. const currentRenderTarget = renderer.getRenderTarget();
  16179. for ( let i = 0; i < 6; i ++ ) {
  16180. renderer.setRenderTarget( this, i );
  16181. renderer.clear( color, depth, stencil );
  16182. }
  16183. renderer.setRenderTarget( currentRenderTarget );
  16184. }
  16185. }
  16186. const _cache$1 = new WeakMap();
  16187. /**
  16188. * This node can be used to automatically convert environment maps in the
  16189. * equirectangular format into the cube map format.
  16190. *
  16191. * @augments TempNode
  16192. */
  16193. class CubeMapNode extends TempNode {
  16194. static get type() {
  16195. return 'CubeMapNode';
  16196. }
  16197. /**
  16198. * Constructs a new cube map node.
  16199. *
  16200. * @param {Node} envNode - The node representing the environment map.
  16201. */
  16202. constructor( envNode ) {
  16203. super( 'vec3' );
  16204. /**
  16205. * The node representing the environment map.
  16206. *
  16207. * @type {Node}
  16208. */
  16209. this.envNode = envNode;
  16210. /**
  16211. * A reference to the internal cube texture.
  16212. *
  16213. * @private
  16214. * @type {?CubeTexture}
  16215. * @default null
  16216. */
  16217. this._cubeTexture = null;
  16218. /**
  16219. * A reference to the internal cube texture node.
  16220. *
  16221. * @private
  16222. * @type {CubeTextureNode}
  16223. */
  16224. this._cubeTextureNode = cubeTexture( null );
  16225. const defaultTexture = new CubeTexture();
  16226. defaultTexture.isRenderTargetTexture = true;
  16227. /**
  16228. * A default cube texture that acts as a placeholder.
  16229. * It is used when the conversion from equirectangular to cube
  16230. * map has not finished yet for a given texture.
  16231. *
  16232. * @private
  16233. * @type {CubeTexture}
  16234. */
  16235. this._defaultTexture = defaultTexture;
  16236. /**
  16237. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  16238. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  16239. *
  16240. * @type {string}
  16241. * @default 'render'
  16242. */
  16243. this.updateBeforeType = NodeUpdateType.RENDER;
  16244. }
  16245. updateBefore( frame ) {
  16246. const { renderer, material } = frame;
  16247. const envNode = this.envNode;
  16248. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  16249. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  16250. if ( texture && texture.isTexture ) {
  16251. const mapping = texture.mapping;
  16252. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  16253. // check for converted cubemap map
  16254. if ( _cache$1.has( texture ) ) {
  16255. const cubeMap = _cache$1.get( texture );
  16256. mapTextureMapping( cubeMap, texture.mapping );
  16257. this._cubeTexture = cubeMap;
  16258. } else {
  16259. // create cube map from equirectangular map
  16260. const image = texture.image;
  16261. if ( isEquirectangularMapReady$1( image ) ) {
  16262. const renderTarget = new CubeRenderTarget( image.height );
  16263. renderTarget.fromEquirectangularTexture( renderer, texture );
  16264. mapTextureMapping( renderTarget.texture, texture.mapping );
  16265. this._cubeTexture = renderTarget.texture;
  16266. _cache$1.set( texture, renderTarget.texture );
  16267. texture.addEventListener( 'dispose', onTextureDispose );
  16268. } else {
  16269. // default cube texture as fallback when equirectangular texture is not yet loaded
  16270. this._cubeTexture = this._defaultTexture;
  16271. }
  16272. }
  16273. //
  16274. this._cubeTextureNode.value = this._cubeTexture;
  16275. } else {
  16276. // envNode already refers to a cube map
  16277. this._cubeTextureNode = this.envNode;
  16278. }
  16279. }
  16280. }
  16281. }
  16282. setup( builder ) {
  16283. this.updateBefore( builder );
  16284. return this._cubeTextureNode;
  16285. }
  16286. }
  16287. /**
  16288. * Returns true if the given equirectangular image has been fully loaded
  16289. * and is ready for further processing.
  16290. *
  16291. * @private
  16292. * @param {Image} image - The equirectangular image to check.
  16293. * @return {boolean} Whether the image is ready or not.
  16294. */
  16295. function isEquirectangularMapReady$1( image ) {
  16296. if ( image === null || image === undefined ) return false;
  16297. return image.height > 0;
  16298. }
  16299. /**
  16300. * This function is executed when `dispose()` is called on the equirectangular
  16301. * texture. In this case, the generated cube map with its render target
  16302. * is deleted as well.
  16303. *
  16304. * @private
  16305. * @param {Object} event - The event object.
  16306. */
  16307. function onTextureDispose( event ) {
  16308. const texture = event.target;
  16309. texture.removeEventListener( 'dispose', onTextureDispose );
  16310. const renderTarget = _cache$1.get( texture );
  16311. if ( renderTarget !== undefined ) {
  16312. _cache$1.delete( texture );
  16313. renderTarget.dispose();
  16314. }
  16315. }
  16316. /**
  16317. * This function makes sure the generated cube map uses the correct
  16318. * texture mapping that corresponds to the equirectangular original.
  16319. *
  16320. * @private
  16321. * @param {Texture} texture - The cube texture.
  16322. * @param {number} mapping - The original texture mapping.
  16323. */
  16324. function mapTextureMapping( texture, mapping ) {
  16325. if ( mapping === EquirectangularReflectionMapping ) {
  16326. texture.mapping = CubeReflectionMapping;
  16327. } else if ( mapping === EquirectangularRefractionMapping ) {
  16328. texture.mapping = CubeRefractionMapping;
  16329. }
  16330. }
  16331. /**
  16332. * TSL function for creating a cube map node.
  16333. *
  16334. * @tsl
  16335. * @function
  16336. * @param {Node} envNode - The node representing the environment map.
  16337. * @returns {CubeMapNode}
  16338. */
  16339. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  16340. /**
  16341. * Represents a basic model for Image-based lighting (IBL). The environment
  16342. * is defined via environment maps in the equirectangular or cube map format.
  16343. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  16344. * or {@link MeshPhongNodeMaterial}.
  16345. *
  16346. * @augments LightingNode
  16347. */
  16348. class BasicEnvironmentNode extends LightingNode {
  16349. static get type() {
  16350. return 'BasicEnvironmentNode';
  16351. }
  16352. /**
  16353. * Constructs a new basic environment node.
  16354. *
  16355. * @param {Node} [envNode=null] - A node representing the environment.
  16356. */
  16357. constructor( envNode = null ) {
  16358. super();
  16359. /**
  16360. * A node representing the environment.
  16361. *
  16362. * @type {Node}
  16363. * @default null
  16364. */
  16365. this.envNode = envNode;
  16366. }
  16367. setup( builder ) {
  16368. // environment property is used in the finish() method of BasicLightingModel
  16369. builder.context.environment = cubeMapNode( this.envNode );
  16370. }
  16371. }
  16372. /**
  16373. * A specific version of {@link IrradianceNode} that is only relevant
  16374. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  16375. * requires a special scaling factor for the light map.
  16376. *
  16377. * @augments LightingNode
  16378. */
  16379. class BasicLightMapNode extends LightingNode {
  16380. static get type() {
  16381. return 'BasicLightMapNode';
  16382. }
  16383. /**
  16384. * Constructs a new basic light map node.
  16385. *
  16386. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  16387. */
  16388. constructor( lightMapNode = null ) {
  16389. super();
  16390. /**
  16391. * The light map node.
  16392. *
  16393. * @type {?Node<vec3>}
  16394. */
  16395. this.lightMapNode = lightMapNode;
  16396. }
  16397. setup( builder ) {
  16398. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  16399. const RECIPROCAL_PI = float( 1 / Math.PI );
  16400. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  16401. }
  16402. }
  16403. /**
  16404. * Abstract class for implementing lighting models. The module defines
  16405. * multiple methods that concrete lighting models can implement. These
  16406. * methods are executed at different points during the light evaluation
  16407. * process.
  16408. */
  16409. class LightingModel {
  16410. /**
  16411. * This method is intended for setting up lighting model and context data
  16412. * which are later used in the evaluation process.
  16413. *
  16414. * @abstract
  16415. * @param {NodeBuilder} builder - The current node builder.
  16416. */
  16417. start( builder ) {
  16418. // lights ( direct )
  16419. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  16420. // indirect
  16421. this.indirect( builder );
  16422. }
  16423. /**
  16424. * This method is intended for executing final tasks like final updates
  16425. * to the outgoing light.
  16426. *
  16427. * @abstract
  16428. * @param {NodeBuilder} builder - The current node builder.
  16429. */
  16430. finish( /*builder*/ ) { }
  16431. /**
  16432. * This method is intended for implementing the direct light term and
  16433. * executed during the build process of directional, point and spot light nodes.
  16434. *
  16435. * @abstract
  16436. * @param {Object} lightData - The light data.
  16437. * @param {NodeBuilder} builder - The current node builder.
  16438. */
  16439. direct( /*lightData, builder*/ ) { }
  16440. /**
  16441. * This method is intended for implementing the direct light term for
  16442. * rect area light nodes.
  16443. *
  16444. * @abstract
  16445. * @param {Object} lightData - The light data.
  16446. * @param {NodeBuilder} builder - The current node builder.
  16447. */
  16448. directRectArea( /*lightData, builder*/ ) {}
  16449. /**
  16450. * This method is intended for implementing the indirect light term.
  16451. *
  16452. * @abstract
  16453. * @param {NodeBuilder} builder - The current node builder.
  16454. */
  16455. indirect( /*builder*/ ) { }
  16456. /**
  16457. * This method is intended for implementing the ambient occlusion term.
  16458. * Unlike other methods, this method must be called manually by the lighting
  16459. * model in its indirect term.
  16460. *
  16461. * @abstract
  16462. * @param {NodeBuilder} builder - The current node builder.
  16463. */
  16464. ambientOcclusion( /*input, stack, builder*/ ) { }
  16465. }
  16466. /**
  16467. * Represents the lighting model for unlit materials. The only light contribution
  16468. * is baked indirect lighting modulated with ambient occlusion and the material's
  16469. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  16470. *
  16471. * @augments LightingModel
  16472. */
  16473. class BasicLightingModel extends LightingModel {
  16474. /**
  16475. * Constructs a new basic lighting model.
  16476. */
  16477. constructor() {
  16478. super();
  16479. }
  16480. /**
  16481. * Implements the baked indirect lighting with its modulation.
  16482. *
  16483. * @param {NodeBuilder} builder - The current node builder.
  16484. */
  16485. indirect( { context } ) {
  16486. const ambientOcclusion = context.ambientOcclusion;
  16487. const reflectedLight = context.reflectedLight;
  16488. const irradianceLightMap = context.irradianceLightMap;
  16489. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  16490. // accumulation (baked indirect lighting only)
  16491. if ( irradianceLightMap ) {
  16492. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  16493. } else {
  16494. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  16495. }
  16496. // modulation
  16497. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16498. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  16499. }
  16500. /**
  16501. * Implements the environment mapping.
  16502. *
  16503. * @param {NodeBuilder} builder - The current node builder.
  16504. */
  16505. finish( builder ) {
  16506. const { material, context } = builder;
  16507. const outgoingLight = context.outgoingLight;
  16508. const envNode = builder.context.environment;
  16509. if ( envNode ) {
  16510. switch ( material.combine ) {
  16511. case MultiplyOperation:
  16512. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  16513. break;
  16514. case MixOperation:
  16515. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  16516. break;
  16517. case AddOperation:
  16518. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  16519. break;
  16520. default:
  16521. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  16522. break;
  16523. }
  16524. }
  16525. }
  16526. }
  16527. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  16528. /**
  16529. * Node material version of {@link MeshBasicMaterial}.
  16530. *
  16531. * @augments NodeMaterial
  16532. */
  16533. class MeshBasicNodeMaterial extends NodeMaterial {
  16534. static get type() {
  16535. return 'MeshBasicNodeMaterial';
  16536. }
  16537. /**
  16538. * Constructs a new mesh basic node material.
  16539. *
  16540. * @param {Object} [parameters] - The configuration parameter.
  16541. */
  16542. constructor( parameters ) {
  16543. super();
  16544. /**
  16545. * This flag can be used for type testing.
  16546. *
  16547. * @type {boolean}
  16548. * @readonly
  16549. * @default true
  16550. */
  16551. this.isMeshBasicNodeMaterial = true;
  16552. /**
  16553. * Although the basic material is by definition unlit, we set
  16554. * this property to `true` since we use a lighting model to compute
  16555. * the outgoing light of the fragment shader.
  16556. *
  16557. * @type {boolean}
  16558. * @default true
  16559. */
  16560. this.lights = true;
  16561. this.setDefaultValues( _defaultValues$9 );
  16562. this.setValues( parameters );
  16563. }
  16564. /**
  16565. * Basic materials are not affected by normal and bump maps so we
  16566. * return by default {@link normalViewGeometry}.
  16567. *
  16568. * @return {Node<vec3>} The normal node.
  16569. */
  16570. setupNormal() {
  16571. return directionToFaceDirection( normalViewGeometry ); // see #28839
  16572. }
  16573. /**
  16574. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16575. * to implement the default environment mapping.
  16576. *
  16577. * @param {NodeBuilder} builder - The current node builder.
  16578. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16579. */
  16580. setupEnvironment( builder ) {
  16581. const envNode = super.setupEnvironment( builder );
  16582. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16583. }
  16584. /**
  16585. * This method must be overwritten since light maps are evaluated
  16586. * with a special scaling factor for basic materials.
  16587. *
  16588. * @param {NodeBuilder} builder - The current node builder.
  16589. * @return {?BasicLightMapNode<vec3>} The light map node.
  16590. */
  16591. setupLightMap( builder ) {
  16592. let node = null;
  16593. if ( builder.material.lightMap ) {
  16594. node = new BasicLightMapNode( materialLightMap );
  16595. }
  16596. return node;
  16597. }
  16598. /**
  16599. * The material overwrites this method because `lights` is set to `true` but
  16600. * we still want to return the diffuse color as the outgoing light.
  16601. *
  16602. * @return {Node<vec3>} The outgoing light node.
  16603. */
  16604. setupOutgoingLight() {
  16605. return diffuseColor.rgb;
  16606. }
  16607. /**
  16608. * Setups the lighting model.
  16609. *
  16610. * @return {BasicLightingModel} The lighting model.
  16611. */
  16612. setupLightingModel() {
  16613. return new BasicLightingModel();
  16614. }
  16615. }
  16616. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  16617. // Original approximation by Christophe Schlick '94
  16618. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  16619. // Optimized variant (presented by Epic at SIGGRAPH '13)
  16620. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  16621. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  16622. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  16623. } ); // validated
  16624. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  16625. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  16626. } ); // validated
  16627. const G_BlinnPhong_Implicit = () => float( 0.25 );
  16628. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  16629. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  16630. } );
  16631. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16632. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16633. const dotNH = normalView.dot( halfDir ).clamp();
  16634. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16635. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  16636. const G = G_BlinnPhong_Implicit();
  16637. const D = D_BlinnPhong( { dotNH } );
  16638. return F.mul( G ).mul( D );
  16639. } );
  16640. /**
  16641. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  16642. *
  16643. * @augments BasicLightingModel
  16644. */
  16645. class PhongLightingModel extends BasicLightingModel {
  16646. /**
  16647. * Constructs a new phong lighting model.
  16648. *
  16649. * @param {boolean} [specular=true] - Whether specular is supported or not.
  16650. */
  16651. constructor( specular = true ) {
  16652. super();
  16653. /**
  16654. * Whether specular is supported or not. Set this to `false` if you are
  16655. * looking for a Lambert-like material meaning a material for non-shiny
  16656. * surfaces, without specular highlights.
  16657. *
  16658. * @type {boolean}
  16659. * @default true
  16660. */
  16661. this.specular = specular;
  16662. }
  16663. /**
  16664. * Implements the direct lighting. The specular portion is optional an can be controlled
  16665. * with the {@link PhongLightingModel#specular} flag.
  16666. *
  16667. * @param {Object} lightData - The light data.
  16668. */
  16669. direct( { lightDirection, lightColor, reflectedLight } ) {
  16670. const dotNL = normalView.dot( lightDirection ).clamp();
  16671. const irradiance = dotNL.mul( lightColor );
  16672. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16673. if ( this.specular === true ) {
  16674. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  16675. }
  16676. }
  16677. /**
  16678. * Implements the indirect lighting.
  16679. *
  16680. * @param {NodeBuilder} builder - The current node builder.
  16681. */
  16682. indirect( builder ) {
  16683. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16684. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16685. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16686. }
  16687. }
  16688. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  16689. /**
  16690. * Node material version of {@link MeshLambertMaterial}.
  16691. *
  16692. * @augments NodeMaterial
  16693. */
  16694. class MeshLambertNodeMaterial extends NodeMaterial {
  16695. static get type() {
  16696. return 'MeshLambertNodeMaterial';
  16697. }
  16698. /**
  16699. * Constructs a new mesh lambert node material.
  16700. *
  16701. * @param {Object} [parameters] - The configuration parameter.
  16702. */
  16703. constructor( parameters ) {
  16704. super();
  16705. /**
  16706. * This flag can be used for type testing.
  16707. *
  16708. * @type {boolean}
  16709. * @readonly
  16710. * @default true
  16711. */
  16712. this.isMeshLambertNodeMaterial = true;
  16713. /**
  16714. * Set to `true` because lambert materials react on lights.
  16715. *
  16716. * @type {boolean}
  16717. * @default true
  16718. */
  16719. this.lights = true;
  16720. this.setDefaultValues( _defaultValues$8 );
  16721. this.setValues( parameters );
  16722. }
  16723. /**
  16724. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16725. * to implement the default environment mapping.
  16726. *
  16727. * @param {NodeBuilder} builder - The current node builder.
  16728. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16729. */
  16730. setupEnvironment( builder ) {
  16731. const envNode = super.setupEnvironment( builder );
  16732. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16733. }
  16734. /**
  16735. * Setups the lighting model.
  16736. *
  16737. * @return {PhongLightingModel} The lighting model.
  16738. */
  16739. setupLightingModel( /*builder*/ ) {
  16740. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16741. }
  16742. }
  16743. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16744. /**
  16745. * Node material version of {@link MeshPhongMaterial}.
  16746. *
  16747. * @augments NodeMaterial
  16748. */
  16749. class MeshPhongNodeMaterial extends NodeMaterial {
  16750. static get type() {
  16751. return 'MeshPhongNodeMaterial';
  16752. }
  16753. /**
  16754. * Constructs a new mesh lambert node material.
  16755. *
  16756. * @param {Object} [parameters] - The configuration parameter.
  16757. */
  16758. constructor( parameters ) {
  16759. super();
  16760. /**
  16761. * This flag can be used for type testing.
  16762. *
  16763. * @type {boolean}
  16764. * @readonly
  16765. * @default true
  16766. */
  16767. this.isMeshPhongNodeMaterial = true;
  16768. /**
  16769. * Set to `true` because phong materials react on lights.
  16770. *
  16771. * @type {boolean}
  16772. * @default true
  16773. */
  16774. this.lights = true;
  16775. /**
  16776. * The shininess of phong materials is by default inferred from the `shininess`
  16777. * property. This node property allows to overwrite the default
  16778. * and define the shininess with a node instead.
  16779. *
  16780. * If you don't want to overwrite the shininess but modify the existing
  16781. * value instead, use {@link materialShininess}.
  16782. *
  16783. * @type {?Node<float>}
  16784. * @default null
  16785. */
  16786. this.shininessNode = null;
  16787. /**
  16788. * The specular color of phong materials is by default inferred from the
  16789. * `specular` property. This node property allows to overwrite the default
  16790. * and define the specular color with a node instead.
  16791. *
  16792. * If you don't want to overwrite the specular color but modify the existing
  16793. * value instead, use {@link materialSpecular}.
  16794. *
  16795. * @type {?Node<vec3>}
  16796. * @default null
  16797. */
  16798. this.specularNode = null;
  16799. this.setDefaultValues( _defaultValues$7 );
  16800. this.setValues( parameters );
  16801. }
  16802. /**
  16803. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16804. * to implement the default environment mapping.
  16805. *
  16806. * @param {NodeBuilder} builder - The current node builder.
  16807. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16808. */
  16809. setupEnvironment( builder ) {
  16810. const envNode = super.setupEnvironment( builder );
  16811. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16812. }
  16813. /**
  16814. * Setups the lighting model.
  16815. *
  16816. * @return {PhongLightingModel} The lighting model.
  16817. */
  16818. setupLightingModel( /*builder*/ ) {
  16819. return new PhongLightingModel();
  16820. }
  16821. /**
  16822. * Setups the phong specific node variables.
  16823. *
  16824. * @param {NodeBuilder} builder - The current node builder.
  16825. */
  16826. setupVariants( /*builder*/ ) {
  16827. // SHININESS
  16828. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16829. shininess.assign( shininessNode );
  16830. // SPECULAR COLOR
  16831. const specularNode = this.specularNode || materialSpecular;
  16832. specularColor.assign( specularNode );
  16833. }
  16834. copy( source ) {
  16835. this.shininessNode = source.shininessNode;
  16836. this.specularNode = source.specularNode;
  16837. return super.copy( source );
  16838. }
  16839. }
  16840. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16841. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16842. return float( 0 );
  16843. }
  16844. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16845. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16846. return geometryRoughness;
  16847. } );
  16848. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16849. const { roughness } = inputs;
  16850. const geometryRoughness = getGeometryRoughness();
  16851. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16852. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16853. roughnessFactor = roughnessFactor.min( 1.0 );
  16854. return roughnessFactor;
  16855. } );
  16856. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16857. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16858. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16859. const a2 = alpha.pow2();
  16860. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16861. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16862. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16863. } ).setLayout( {
  16864. name: 'V_GGX_SmithCorrelated',
  16865. type: 'float',
  16866. inputs: [
  16867. { name: 'alpha', type: 'float' },
  16868. { name: 'dotNL', type: 'float' },
  16869. { name: 'dotNV', type: 'float' }
  16870. ]
  16871. } ); // validated
  16872. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16873. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16874. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16875. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16876. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16877. } ).setLayout( {
  16878. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16879. type: 'float',
  16880. inputs: [
  16881. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16882. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16883. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16884. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16885. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16886. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16887. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16888. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16889. ]
  16890. } );
  16891. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16892. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16893. // alpha is "roughness squared" in Disney’s reparameterization
  16894. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16895. const a2 = alpha.pow2();
  16896. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16897. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16898. } ).setLayout( {
  16899. name: 'D_GGX',
  16900. type: 'float',
  16901. inputs: [
  16902. { name: 'alpha', type: 'float' },
  16903. { name: 'dotNH', type: 'float' }
  16904. ]
  16905. } ); // validated
  16906. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16907. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16908. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16909. const a2 = alphaT.mul( alphaB );
  16910. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16911. const v2 = v.dot( v );
  16912. const w2 = a2.div( v2 );
  16913. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16914. } ).setLayout( {
  16915. name: 'D_GGX_Anisotropic',
  16916. type: 'float',
  16917. inputs: [
  16918. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16919. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16920. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16921. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16922. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16923. ]
  16924. } );
  16925. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16926. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16927. const alpha = roughness.pow2(); // UE4's roughness
  16928. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16929. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16930. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16931. const dotNH = normalView$1.dot( halfDir ).clamp();
  16932. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16933. let F = F_Schlick( { f0, f90, dotVH } );
  16934. let V, D;
  16935. if ( defined( USE_IRIDESCENCE ) ) {
  16936. F = iridescence.mix( F, f );
  16937. }
  16938. if ( defined( USE_ANISOTROPY ) ) {
  16939. const dotTL = anisotropyT.dot( lightDirection );
  16940. const dotTV = anisotropyT.dot( positionViewDirection );
  16941. const dotTH = anisotropyT.dot( halfDir );
  16942. const dotBL = anisotropyB.dot( lightDirection );
  16943. const dotBV = anisotropyB.dot( positionViewDirection );
  16944. const dotBH = anisotropyB.dot( halfDir );
  16945. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16946. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16947. } else {
  16948. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16949. D = D_GGX( { alpha, dotNH } );
  16950. }
  16951. return F.mul( V ).mul( D );
  16952. } ); // validated
  16953. /**
  16954. * Precomputed DFG LUT for Image-Based Lighting
  16955. * Resolution: 16x16
  16956. * Samples: 4096 per texel
  16957. * Format: RG16F (2 half floats per texel: scale, bias)
  16958. */
  16959. const DATA = new Uint16Array( [
  16960. 0x30b5, 0x3ad1, 0x314c, 0x3a4d, 0x33d2, 0x391c, 0x35ef, 0x3828, 0x37f3, 0x36a6, 0x38d1, 0x3539, 0x3979, 0x3410, 0x39f8, 0x3252, 0x3a53, 0x30f0, 0x3a94, 0x2fc9, 0x3abf, 0x2e35, 0x3ada, 0x2d05, 0x3ae8, 0x2c1f, 0x3aed, 0x2ae0, 0x3aea, 0x29d1, 0x3ae1, 0x28ff,
  16961. 0x3638, 0x38e4, 0x364a, 0x38ce, 0x3699, 0x385e, 0x374e, 0x372c, 0x3839, 0x35a4, 0x38dc, 0x3462, 0x396e, 0x32c4, 0x39de, 0x3134, 0x3a2b, 0x3003, 0x3a59, 0x2e3a, 0x3a6d, 0x2ce1, 0x3a6e, 0x2bba, 0x3a5f, 0x2a33, 0x3a49, 0x290a, 0x3a2d, 0x2826, 0x3a0a, 0x26e8,
  16962. 0x3894, 0x36d7, 0x3897, 0x36c9, 0x38a3, 0x3675, 0x38bc, 0x35ac, 0x38ee, 0x349c, 0x393e, 0x3332, 0x3997, 0x3186, 0x39e2, 0x3038, 0x3a13, 0x2e75, 0x3a29, 0x2cf5, 0x3a2d, 0x2bac, 0x3a21, 0x29ff, 0x3a04, 0x28bc, 0x39dc, 0x2790, 0x39ad, 0x261a, 0x3978, 0x24fa,
  16963. 0x39ac, 0x34a8, 0x39ac, 0x34a3, 0x39ae, 0x3480, 0x39ae, 0x3423, 0x39b1, 0x330e, 0x39c2, 0x31a9, 0x39e0, 0x3063, 0x39fc, 0x2eb5, 0x3a0c, 0x2d1d, 0x3a14, 0x2bcf, 0x3a07, 0x29ff, 0x39e9, 0x28a3, 0x39be, 0x273c, 0x3989, 0x25b3, 0x394a, 0x2488, 0x3907, 0x2345,
  16964. 0x3a77, 0x3223, 0x3a76, 0x321f, 0x3a73, 0x3204, 0x3a6a, 0x31b3, 0x3a58, 0x3114, 0x3a45, 0x303b, 0x3a34, 0x2eb6, 0x3a26, 0x2d31, 0x3a1e, 0x2bef, 0x3a0b, 0x2a0d, 0x39ec, 0x28a1, 0x39c0, 0x271b, 0x3987, 0x2580, 0x3944, 0x2449, 0x38fa, 0x22bd, 0x38ac, 0x2155,
  16965. 0x3b07, 0x2fca, 0x3b06, 0x2fca, 0x3b00, 0x2fb8, 0x3af4, 0x2f7c, 0x3adb, 0x2eea, 0x3ab4, 0x2e00, 0x3a85, 0x2cec, 0x3a5e, 0x2bc5, 0x3a36, 0x2a00, 0x3a0d, 0x2899, 0x39dc, 0x2707, 0x39a0, 0x2562, 0x395a, 0x2424, 0x390b, 0x2268, 0x38b7, 0x20fd, 0x385f, 0x1fd1,
  16966. 0x3b69, 0x2cb9, 0x3b68, 0x2cbb, 0x3b62, 0x2cbb, 0x3b56, 0x2cae, 0x3b3b, 0x2c78, 0x3b0d, 0x2c0a, 0x3acf, 0x2ae3, 0x3a92, 0x2998, 0x3a54, 0x2867, 0x3a17, 0x26d0, 0x39d3, 0x253c, 0x3989, 0x2402, 0x3935, 0x2226, 0x38dc, 0x20bd, 0x387d, 0x1f54, 0x381d, 0x1db3,
  16967. 0x3ba9, 0x296b, 0x3ba8, 0x296f, 0x3ba3, 0x297b, 0x3b98, 0x2987, 0x3b7f, 0x2976, 0x3b4e, 0x2927, 0x3b0e, 0x2895, 0x3ac2, 0x27b7, 0x3a73, 0x263b, 0x3a23, 0x24e7, 0x39d0, 0x239b, 0x3976, 0x21d9, 0x3917, 0x207e, 0x38b2, 0x1ee7, 0x384b, 0x1d53, 0x37c7, 0x1c1e,
  16968. 0x3bd2, 0x25cb, 0x3bd1, 0x25d3, 0x3bcd, 0x25f0, 0x3bc2, 0x261f, 0x3bad, 0x2645, 0x3b7d, 0x262d, 0x3b3e, 0x25c4, 0x3aec, 0x250f, 0x3a93, 0x243a, 0x3a32, 0x22ce, 0x39d0, 0x215b, 0x3969, 0x202a, 0x38fe, 0x1e6e, 0x388f, 0x1cf1, 0x381f, 0x1b9b, 0x3762, 0x19dd,
  16969. 0x3be9, 0x21ab, 0x3be9, 0x21b7, 0x3be5, 0x21e5, 0x3bdd, 0x2241, 0x3bc9, 0x22a7, 0x3ba0, 0x22ec, 0x3b62, 0x22cd, 0x3b0f, 0x2247, 0x3aae, 0x2175, 0x3a44, 0x2088, 0x39d4, 0x1f49, 0x3960, 0x1dbe, 0x38e9, 0x1c77, 0x3870, 0x1ae8, 0x37f1, 0x1953, 0x3708, 0x181b,
  16970. 0x3bf6, 0x1cea, 0x3bf6, 0x1cfb, 0x3bf3, 0x1d38, 0x3bec, 0x1dbd, 0x3bda, 0x1e7c, 0x3bb7, 0x1f25, 0x3b7d, 0x1f79, 0x3b2c, 0x1f4c, 0x3ac6, 0x1ea6, 0x3a55, 0x1dbb, 0x39da, 0x1cbd, 0x395a, 0x1b9d, 0x38d8, 0x1a00, 0x3855, 0x18ac, 0x37ab, 0x173c, 0x36b7, 0x1598,
  16971. 0x3bfc, 0x1736, 0x3bfc, 0x1759, 0x3bf9, 0x17e7, 0x3bf4, 0x1896, 0x3be4, 0x1997, 0x3bc6, 0x1aa8, 0x3b91, 0x1b84, 0x3b43, 0x1bd2, 0x3ade, 0x1b8a, 0x3a65, 0x1acd, 0x39e2, 0x19d3, 0x3957, 0x18cd, 0x38ca, 0x17b3, 0x383e, 0x1613, 0x376d, 0x14bf, 0x366f, 0x135e,
  16972. 0x3bff, 0x101b, 0x3bff, 0x1039, 0x3bfc, 0x10c8, 0x3bf9, 0x1226, 0x3bea, 0x1428, 0x3bcf, 0x1584, 0x3b9f, 0x16c5, 0x3b54, 0x179a, 0x3af0, 0x17ce, 0x3a76, 0x1771, 0x39ea, 0x16a4, 0x3956, 0x15a7, 0x38bf, 0x14a7, 0x3829, 0x1379, 0x3735, 0x11ea, 0x362d, 0x10a1,
  16973. 0x3c00, 0x061b, 0x3c00, 0x066a, 0x3bfe, 0x081c, 0x3bfa, 0x0a4c, 0x3bed, 0x0d16, 0x3bd5, 0x0fb3, 0x3ba9, 0x114d, 0x3b63, 0x127c, 0x3b01, 0x132f, 0x3a85, 0x1344, 0x39f4, 0x12d2, 0x3957, 0x120d, 0x38b5, 0x1122, 0x3817, 0x103c, 0x3703, 0x0ed3, 0x35f0, 0x0d6d,
  16974. 0x3c00, 0x007a, 0x3c00, 0x0089, 0x3bfe, 0x011d, 0x3bfb, 0x027c, 0x3bf0, 0x04fa, 0x3bda, 0x0881, 0x3bb1, 0x0acd, 0x3b6f, 0x0c97, 0x3b10, 0x0d7b, 0x3a93, 0x0df1, 0x39fe, 0x0def, 0x3959, 0x0d8a, 0x38af, 0x0ce9, 0x3808, 0x0c31, 0x36d5, 0x0af0, 0x35b9, 0x09a3,
  16975. 0x3c00, 0x0000, 0x3c00, 0x0001, 0x3bff, 0x0015, 0x3bfb, 0x0059, 0x3bf2, 0x00fd, 0x3bdd, 0x01df, 0x3bb7, 0x031c, 0x3b79, 0x047c, 0x3b1d, 0x05d4, 0x3aa0, 0x06d5, 0x3a08, 0x075a, 0x395d, 0x075e, 0x38aa, 0x06f7, 0x37f4, 0x0648, 0x36ac, 0x0576, 0x3586, 0x049f
  16976. ] );
  16977. let lut = null;
  16978. const DFGLUT = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16979. if ( lut === null ) {
  16980. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  16981. lut.name = 'DFG_LUT';
  16982. lut.minFilter = LinearFilter;
  16983. lut.magFilter = LinearFilter;
  16984. lut.wrapS = ClampToEdgeWrapping;
  16985. lut.wrapT = ClampToEdgeWrapping;
  16986. lut.generateMipmaps = false;
  16987. lut.needsUpdate = true;
  16988. }
  16989. const uv = vec2( roughness, dotNV );
  16990. return texture( lut, uv ).rg;
  16991. } );
  16992. // GGX BRDF with multi-scattering energy compensation for direct lighting
  16993. // This provides more accurate energy conservation, especially for rough materials
  16994. // Based on "Practical Multiple Scattering Compensation for Microfacet Models"
  16995. // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf
  16996. const BRDF_GGX_Multiscatter = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16997. // Single-scattering BRDF (standard GGX)
  16998. const singleScatter = BRDF_GGX( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } );
  16999. // Multi-scattering compensation
  17000. const dotNL = normalView.dot( lightDirection ).clamp();
  17001. const dotNV = normalView.dot( positionViewDirection ).clamp();
  17002. // Precomputed DFG values for view and light directions
  17003. const dfgV = DFGLUT( { roughness: _roughness, dotNV } );
  17004. const dfgL = DFGLUT( { roughness: _roughness, dotNV: dotNL } );
  17005. // Single-scattering energy for view and light
  17006. const FssEss_V = f0.mul( dfgV.x ).add( f90.mul( dfgV.y ) );
  17007. const FssEss_L = f0.mul( dfgL.x ).add( f90.mul( dfgL.y ) );
  17008. const Ess_V = dfgV.x.add( dfgV.y );
  17009. const Ess_L = dfgL.x.add( dfgL.y );
  17010. // Energy lost to multiple scattering
  17011. const Ems_V = float( 1.0 ).sub( Ess_V );
  17012. const Ems_L = float( 1.0 ).sub( Ess_L );
  17013. // Average Fresnel reflectance
  17014. const Favg = f0.add( f0.oneMinus().mul( 0.047619 ) ); // 1/21
  17015. // Multiple scattering contribution
  17016. // Uses geometric mean of view and light contributions for better energy distribution
  17017. const Fms = FssEss_V.mul( FssEss_L ).mul( Favg ).div( float( 1.0 ).sub( Ems_V.mul( Ems_L ).mul( Favg ).mul( Favg ) ).add( EPSILON ) );
  17018. // Energy compensation factor
  17019. const compensationFactor = Ems_V.mul( Ems_L );
  17020. const multiScatter = Fms.mul( compensationFactor );
  17021. return singleScatter.add( multiScatter );
  17022. } );
  17023. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  17024. const { dotNV, specularColor, specularF90, roughness } = inputs;
  17025. const fab = DFGLUT( { dotNV, roughness } );
  17026. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17027. } );
  17028. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  17029. const x = dotVH.oneMinus().saturate();
  17030. const x2 = x.mul( x );
  17031. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  17032. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  17033. } ).setLayout( {
  17034. name: 'Schlick_to_F0',
  17035. type: 'vec3',
  17036. inputs: [
  17037. { name: 'f', type: 'vec3' },
  17038. { name: 'f90', type: 'float' },
  17039. { name: 'dotVH', type: 'float' }
  17040. ]
  17041. } );
  17042. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  17043. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  17044. const alpha = roughness.pow2();
  17045. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  17046. const invAlpha = float( 1.0 ).div( alpha );
  17047. const cos2h = dotNH.pow2();
  17048. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  17049. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  17050. } ).setLayout( {
  17051. name: 'D_Charlie',
  17052. type: 'float',
  17053. inputs: [
  17054. { name: 'roughness', type: 'float' },
  17055. { name: 'dotNH', type: 'float' }
  17056. ]
  17057. } );
  17058. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  17059. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  17060. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  17061. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  17062. } ).setLayout( {
  17063. name: 'V_Neubelt',
  17064. type: 'float',
  17065. inputs: [
  17066. { name: 'dotNV', type: 'float' },
  17067. { name: 'dotNL', type: 'float' }
  17068. ]
  17069. } );
  17070. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  17071. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  17072. const dotNL = normalView.dot( lightDirection ).clamp();
  17073. const dotNV = normalView.dot( positionViewDirection ).clamp();
  17074. const dotNH = normalView.dot( halfDir ).clamp();
  17075. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  17076. const V = V_Neubelt( { dotNV, dotNL } );
  17077. return sheen.mul( D ).mul( V );
  17078. } );
  17079. // Rect Area Light
  17080. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  17081. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  17082. // code: https://github.com/selfshadow/ltc_code/
  17083. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  17084. const LUT_SIZE = 64.0;
  17085. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  17086. const LUT_BIAS = 0.5 / LUT_SIZE;
  17087. const dotNV = N.dot( V ).saturate();
  17088. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  17089. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  17090. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  17091. return uv;
  17092. } ).setLayout( {
  17093. name: 'LTC_Uv',
  17094. type: 'vec2',
  17095. inputs: [
  17096. { name: 'N', type: 'vec3' },
  17097. { name: 'V', type: 'vec3' },
  17098. { name: 'roughness', type: 'float' }
  17099. ]
  17100. } );
  17101. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  17102. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  17103. // An approximation of the form factor of a horizon-clipped rectangle.
  17104. const l = f.length();
  17105. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  17106. } ).setLayout( {
  17107. name: 'LTC_ClippedSphereFormFactor',
  17108. type: 'float',
  17109. inputs: [
  17110. { name: 'f', type: 'vec3' }
  17111. ]
  17112. } );
  17113. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  17114. const x = v1.dot( v2 );
  17115. const y = x.abs().toVar();
  17116. // rational polynomial approximation to theta / sin( theta ) / 2PI
  17117. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  17118. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  17119. const v = a.div( b );
  17120. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  17121. return v1.cross( v2 ).mul( theta_sintheta );
  17122. } ).setLayout( {
  17123. name: 'LTC_EdgeVectorFormFactor',
  17124. type: 'vec3',
  17125. inputs: [
  17126. { name: 'v1', type: 'vec3' },
  17127. { name: 'v2', type: 'vec3' }
  17128. ]
  17129. } );
  17130. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  17131. // bail if point is on back side of plane of light
  17132. // assumes ccw winding order of light vertices
  17133. const v1 = p1.sub( p0 ).toVar();
  17134. const v2 = p3.sub( p0 ).toVar();
  17135. const lightNormal = v1.cross( v2 );
  17136. const result = vec3().toVar();
  17137. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  17138. // construct orthonormal basis around N
  17139. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  17140. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  17141. // compute transform
  17142. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  17143. // transform rect
  17144. // & project rect onto sphere
  17145. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  17146. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  17147. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  17148. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  17149. // calculate vector form factor
  17150. const vectorFormFactor = vec3( 0 ).toVar();
  17151. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  17152. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  17153. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  17154. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  17155. // adjust for horizon clipping
  17156. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  17157. } );
  17158. return result;
  17159. } ).setLayout( {
  17160. name: 'LTC_Evaluate',
  17161. type: 'vec3',
  17162. inputs: [
  17163. { name: 'N', type: 'vec3' },
  17164. { name: 'V', type: 'vec3' },
  17165. { name: 'P', type: 'vec3' },
  17166. { name: 'mInv', type: 'mat3' },
  17167. { name: 'p0', type: 'vec3' },
  17168. { name: 'p1', type: 'vec3' },
  17169. { name: 'p2', type: 'vec3' },
  17170. { name: 'p3', type: 'vec3' }
  17171. ]
  17172. } );
  17173. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  17174. // bail if point is on back side of plane of light
  17175. // assumes ccw winding order of light vertices
  17176. const v1 = p1.sub( p0 ).toVar();
  17177. const v2 = p3.sub( p0 ).toVar();
  17178. const lightNormal = v1.cross( v2 );
  17179. const result = vec3().toVar();
  17180. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  17181. // transform rect
  17182. // & project rect onto sphere
  17183. const coords0 = p0.sub( P ).normalize().toVar();
  17184. const coords1 = p1.sub( P ).normalize().toVar();
  17185. const coords2 = p2.sub( P ).normalize().toVar();
  17186. const coords3 = p3.sub( P ).normalize().toVar();
  17187. // calculate vector form factor
  17188. const vectorFormFactor = vec3( 0 ).toVar();
  17189. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  17190. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  17191. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  17192. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  17193. // adjust for horizon clipping
  17194. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  17195. } );
  17196. return result;
  17197. } ).setLayout( {
  17198. name: 'LTC_Evaluate',
  17199. type: 'vec3',
  17200. inputs: [
  17201. { name: 'P', type: 'vec3' },
  17202. { name: 'p0', type: 'vec3' },
  17203. { name: 'p1', type: 'vec3' },
  17204. { name: 'p2', type: 'vec3' },
  17205. { name: 'p3', type: 'vec3' }
  17206. ]
  17207. } );
  17208. // Mipped Bicubic Texture Filtering by N8
  17209. // https://www.shadertoy.com/view/Dl2SDW
  17210. const bC = 1.0 / 6.0;
  17211. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  17212. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  17213. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  17214. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  17215. const g0 = ( a ) => w0( a ).add( w1( a ) );
  17216. const g1 = ( a ) => w2( a ).add( w3( a ) );
  17217. // h0 and h1 are the two offset functions
  17218. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  17219. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  17220. const bicubic = ( textureNode, texelSize, lod ) => {
  17221. const uv = textureNode.uvNode;
  17222. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  17223. const iuv = floor( uvScaled );
  17224. const fuv = fract( uvScaled );
  17225. const g0x = g0( fuv.x );
  17226. const g1x = g1( fuv.x );
  17227. const h0x = h0( fuv.x );
  17228. const h1x = h1( fuv.x );
  17229. const h0y = h0( fuv.y );
  17230. const h1y = h1( fuv.y );
  17231. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  17232. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  17233. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  17234. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  17235. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  17236. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  17237. return a.add( b );
  17238. };
  17239. /**
  17240. * Applies mipped bicubic texture filtering to the given texture node.
  17241. *
  17242. * @tsl
  17243. * @function
  17244. * @param {TextureNode} textureNode - The texture node that should be filtered.
  17245. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  17246. * @return {Node} The filtered texture sample.
  17247. */
  17248. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  17249. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  17250. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  17251. const fLodSizeInv = div( 1.0, fLodSize );
  17252. const cLodSizeInv = div( 1.0, cLodSize );
  17253. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  17254. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  17255. return fract( lodNode ).mix( fSample, cSample );
  17256. } );
  17257. /**
  17258. * Applies mipped bicubic texture filtering to the given texture node.
  17259. *
  17260. * @tsl
  17261. * @function
  17262. * @param {TextureNode} textureNode - The texture node that should be filtered.
  17263. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  17264. * @return {Node} The filtered texture sample.
  17265. */
  17266. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  17267. const lod = strength.mul( maxMipLevel( textureNode ) );
  17268. return textureBicubicLevel( textureNode, lod );
  17269. } );
  17270. //
  17271. // Transmission
  17272. //
  17273. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  17274. // Direction of refracted light.
  17275. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  17276. // Compute rotation-independent scaling of the model matrix.
  17277. const modelScale = vec3(
  17278. length( modelMatrix[ 0 ].xyz ),
  17279. length( modelMatrix[ 1 ].xyz ),
  17280. length( modelMatrix[ 2 ].xyz )
  17281. );
  17282. // The thickness is specified in local space.
  17283. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  17284. } ).setLayout( {
  17285. name: 'getVolumeTransmissionRay',
  17286. type: 'vec3',
  17287. inputs: [
  17288. { name: 'n', type: 'vec3' },
  17289. { name: 'v', type: 'vec3' },
  17290. { name: 'thickness', type: 'float' },
  17291. { name: 'ior', type: 'float' },
  17292. { name: 'modelMatrix', type: 'mat4' }
  17293. ]
  17294. } );
  17295. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  17296. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  17297. // an IOR of 1.5 results in the default amount of microfacet refraction.
  17298. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  17299. } ).setLayout( {
  17300. name: 'applyIorToRoughness',
  17301. type: 'float',
  17302. inputs: [
  17303. { name: 'roughness', type: 'float' },
  17304. { name: 'ior', type: 'float' }
  17305. ]
  17306. } );
  17307. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  17308. const viewportFrontSideTexture = /*@__PURE__*/ viewportOpaqueMipTexture();
  17309. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  17310. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  17311. const transmissionSample = vTexture.sample( fragCoord );
  17312. //const transmissionSample = viewportMipTexture( fragCoord );
  17313. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  17314. return textureBicubicLevel( transmissionSample, lod );
  17315. } );
  17316. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  17317. If( attenuationDistance.notEqual( 0 ), () => {
  17318. // Compute light attenuation using Beer's law.
  17319. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  17320. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  17321. return transmittance;
  17322. } );
  17323. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  17324. return vec3( 1.0 );
  17325. } ).setLayout( {
  17326. name: 'volumeAttenuation',
  17327. type: 'vec3',
  17328. inputs: [
  17329. { name: 'transmissionDistance', type: 'float' },
  17330. { name: 'attenuationColor', type: 'vec3' },
  17331. { name: 'attenuationDistance', type: 'float' }
  17332. ]
  17333. } );
  17334. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  17335. let transmittedLight, transmittance;
  17336. if ( dispersion ) {
  17337. transmittedLight = vec4().toVar();
  17338. transmittance = vec3().toVar();
  17339. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  17340. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  17341. Loop( { start: 0, end: 3 }, ( { i } ) => {
  17342. const ior = iors.element( i );
  17343. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  17344. const refractedRayExit = position.add( transmissionRay );
  17345. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  17346. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  17347. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  17348. refractionCoords.addAssign( 1.0 );
  17349. refractionCoords.divAssign( 2.0 );
  17350. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  17351. // Sample framebuffer to get pixel the refracted ray hits.
  17352. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  17353. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  17354. transmittedLight.a.addAssign( transmissionSample.a );
  17355. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  17356. } );
  17357. transmittedLight.a.divAssign( 3.0 );
  17358. } else {
  17359. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  17360. const refractedRayExit = position.add( transmissionRay );
  17361. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  17362. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  17363. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  17364. refractionCoords.addAssign( 1.0 );
  17365. refractionCoords.divAssign( 2.0 );
  17366. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  17367. // Sample framebuffer to get pixel the refracted ray hits.
  17368. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  17369. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  17370. }
  17371. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  17372. const dotNV = n.dot( v ).clamp();
  17373. // Get the specular component.
  17374. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  17375. dotNV,
  17376. specularColor,
  17377. specularF90,
  17378. roughness
  17379. } ) );
  17380. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  17381. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  17382. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  17383. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  17384. } );
  17385. //
  17386. // Iridescence
  17387. //
  17388. // XYZ to linear-sRGB color space
  17389. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  17390. 3.2404542, -0.969266, 0.0556434,
  17391. -1.5371385, 1.8760108, -0.2040259,
  17392. -0.4985314, 0.0415560, 1.0572252
  17393. );
  17394. // Assume air interface for top
  17395. // Note: We don't handle the case fresnel0 == 1
  17396. const Fresnel0ToIor = ( fresnel0 ) => {
  17397. const sqrtF0 = fresnel0.sqrt();
  17398. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  17399. };
  17400. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  17401. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  17402. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  17403. };
  17404. // Fresnel equations for dielectric/dielectric interfaces.
  17405. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  17406. // Evaluation XYZ sensitivity curves in Fourier space
  17407. const evalSensitivity = ( OPD, shift ) => {
  17408. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  17409. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  17410. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  17411. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  17412. 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() );
  17413. 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() );
  17414. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  17415. const rgb = XYZ_TO_REC709.mul( xyz );
  17416. return rgb;
  17417. };
  17418. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  17419. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  17420. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  17421. // Evaluate the cosTheta on the base layer (Snell law)
  17422. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  17423. // Handle TIR:
  17424. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  17425. If( cosTheta2Sq.lessThan( 0 ), () => {
  17426. return vec3( 1.0 );
  17427. } );
  17428. const cosTheta2 = cosTheta2Sq.sqrt();
  17429. // First interface
  17430. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  17431. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  17432. //const R21 = R12;
  17433. const T121 = R12.oneMinus();
  17434. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  17435. const phi21 = float( Math.PI ).sub( phi12 );
  17436. // Second interface
  17437. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  17438. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  17439. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  17440. const phi23 = vec3(
  17441. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17442. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17443. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  17444. );
  17445. // Phase shift
  17446. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  17447. const phi = vec3( phi21 ).add( phi23 );
  17448. // Compound terms
  17449. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  17450. const r123 = R123.sqrt();
  17451. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  17452. // Reflectance term for m = 0 (DC term amplitude)
  17453. const C0 = R12.add( Rs );
  17454. const I = C0.toVar();
  17455. // Reflectance term for m > 0 (pairs of diracs)
  17456. const Cm = Rs.sub( T121 ).toVar();
  17457. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  17458. Cm.mulAssign( r123 );
  17459. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  17460. I.addAssign( Cm.mul( Sm ) );
  17461. } );
  17462. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  17463. return I.max( vec3( 0.0 ) );
  17464. } ).setLayout( {
  17465. name: 'evalIridescence',
  17466. type: 'vec3',
  17467. inputs: [
  17468. { name: 'outsideIOR', type: 'float' },
  17469. { name: 'eta2', type: 'float' },
  17470. { name: 'cosTheta1', type: 'float' },
  17471. { name: 'thinFilmThickness', type: 'float' },
  17472. { name: 'baseF0', type: 'vec3' }
  17473. ]
  17474. } );
  17475. //
  17476. // Sheen
  17477. //
  17478. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  17479. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF".
  17480. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  17481. const dotNV = normal.dot( viewDir ).saturate();
  17482. const r2 = roughness.mul( roughness );
  17483. const rInv = roughness.add( 0.1 ).reciprocal();
  17484. const a = float( -1.9362 ).add( roughness.mul( 1.0678 ) ).add( r2.mul( 0.4573 ) ).sub( rInv.mul( 0.8469 ) );
  17485. const b = float( -0.6014 ).add( roughness.mul( 0.5538 ) ).sub( r2.mul( 0.4670 ) ).sub( rInv.mul( 0.1255 ) );
  17486. const DG = a.mul( dotNV ).add( b ).exp();
  17487. return DG.saturate();
  17488. } );
  17489. const clearcoatF0 = vec3( 0.04 );
  17490. const clearcoatF90 = float( 1 );
  17491. /**
  17492. * Represents the lighting model for a PBR material.
  17493. *
  17494. * @augments LightingModel
  17495. */
  17496. class PhysicalLightingModel extends LightingModel {
  17497. /**
  17498. * Constructs a new physical lighting model.
  17499. *
  17500. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17501. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17502. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17503. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17504. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17505. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17506. */
  17507. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  17508. super();
  17509. /**
  17510. * Whether clearcoat is supported or not.
  17511. *
  17512. * @type {boolean}
  17513. * @default false
  17514. */
  17515. this.clearcoat = clearcoat;
  17516. /**
  17517. * Whether sheen is supported or not.
  17518. *
  17519. * @type {boolean}
  17520. * @default false
  17521. */
  17522. this.sheen = sheen;
  17523. /**
  17524. * Whether iridescence is supported or not.
  17525. *
  17526. * @type {boolean}
  17527. * @default false
  17528. */
  17529. this.iridescence = iridescence;
  17530. /**
  17531. * Whether anisotropy is supported or not.
  17532. *
  17533. * @type {boolean}
  17534. * @default false
  17535. */
  17536. this.anisotropy = anisotropy;
  17537. /**
  17538. * Whether transmission is supported or not.
  17539. *
  17540. * @type {boolean}
  17541. * @default false
  17542. */
  17543. this.transmission = transmission;
  17544. /**
  17545. * Whether dispersion is supported or not.
  17546. *
  17547. * @type {boolean}
  17548. * @default false
  17549. */
  17550. this.dispersion = dispersion;
  17551. /**
  17552. * The clear coat radiance.
  17553. *
  17554. * @type {?Node}
  17555. * @default null
  17556. */
  17557. this.clearcoatRadiance = null;
  17558. /**
  17559. * The clear coat specular direct.
  17560. *
  17561. * @type {?Node}
  17562. * @default null
  17563. */
  17564. this.clearcoatSpecularDirect = null;
  17565. /**
  17566. * The clear coat specular indirect.
  17567. *
  17568. * @type {?Node}
  17569. * @default null
  17570. */
  17571. this.clearcoatSpecularIndirect = null;
  17572. /**
  17573. * The sheen specular direct.
  17574. *
  17575. * @type {?Node}
  17576. * @default null
  17577. */
  17578. this.sheenSpecularDirect = null;
  17579. /**
  17580. * The sheen specular indirect.
  17581. *
  17582. * @type {?Node}
  17583. * @default null
  17584. */
  17585. this.sheenSpecularIndirect = null;
  17586. /**
  17587. * The iridescence Fresnel.
  17588. *
  17589. * @type {?Node}
  17590. * @default null
  17591. */
  17592. this.iridescenceFresnel = null;
  17593. /**
  17594. * The iridescence F0.
  17595. *
  17596. * @type {?Node}
  17597. * @default null
  17598. */
  17599. this.iridescenceF0 = null;
  17600. /**
  17601. * The iridescence F0 dielectric.
  17602. *
  17603. * @type {?Node}
  17604. * @default null
  17605. */
  17606. this.iridescenceF0Dielectric = null;
  17607. /**
  17608. * The iridescence F0 metallic.
  17609. *
  17610. * @type {?Node}
  17611. * @default null
  17612. */
  17613. this.iridescenceF0Metallic = null;
  17614. }
  17615. /**
  17616. * Depending on what features are requested, the method prepares certain node variables
  17617. * which are later used for lighting computations.
  17618. *
  17619. * @param {NodeBuilder} builder - The current node builder.
  17620. */
  17621. start( builder ) {
  17622. if ( this.clearcoat === true ) {
  17623. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  17624. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  17625. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  17626. }
  17627. if ( this.sheen === true ) {
  17628. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  17629. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  17630. }
  17631. if ( this.iridescence === true ) {
  17632. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  17633. const iridescenceFresnelDielectric = evalIridescence( {
  17634. outsideIOR: float( 1.0 ),
  17635. eta2: iridescenceIOR,
  17636. cosTheta1: dotNVi,
  17637. thinFilmThickness: iridescenceThickness,
  17638. baseF0: specularColor
  17639. } );
  17640. const iridescenceFresnelMetallic = evalIridescence( {
  17641. outsideIOR: float( 1.0 ),
  17642. eta2: iridescenceIOR,
  17643. cosTheta1: dotNVi,
  17644. thinFilmThickness: iridescenceThickness,
  17645. baseF0: diffuseColor.rgb
  17646. } );
  17647. this.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, metalness );
  17648. this.iridescenceF0Dielectric = Schlick_to_F0( { f: iridescenceFresnelDielectric, f90: 1.0, dotVH: dotNVi } );
  17649. this.iridescenceF0Metallic = Schlick_to_F0( { f: iridescenceFresnelMetallic, f90: 1.0, dotVH: dotNVi } );
  17650. this.iridescenceF0 = mix( this.iridescenceF0Dielectric, this.iridescenceF0Metallic, metalness );
  17651. }
  17652. if ( this.transmission === true ) {
  17653. const position = positionWorld;
  17654. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  17655. const n = normalWorld;
  17656. const context = builder.context;
  17657. context.backdrop = getIBLVolumeRefraction(
  17658. n,
  17659. v,
  17660. roughness,
  17661. diffuseContribution,
  17662. specularColorBlended,
  17663. specularF90, // specularF90
  17664. position, // positionWorld
  17665. modelWorldMatrix, // modelMatrix
  17666. cameraViewMatrix, // viewMatrix
  17667. cameraProjectionMatrix, // projMatrix
  17668. ior,
  17669. thickness,
  17670. attenuationColor,
  17671. attenuationDistance,
  17672. this.dispersion ? dispersion : null
  17673. );
  17674. context.backdropAlpha = transmission;
  17675. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  17676. }
  17677. super.start( builder );
  17678. }
  17679. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  17680. // Approximates multi-scattering in order to preserve energy.
  17681. // http://www.jcgt.org/published/0008/01/03/
  17682. computeMultiscattering( singleScatter, multiScatter, specularF90, f0, iridescenceF0 = null ) {
  17683. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17684. const fab = DFGLUT( { roughness, dotNV } );
  17685. const Fr = iridescenceF0 ? iridescence.mix( f0, iridescenceF0 ) : f0;
  17686. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17687. const Ess = fab.x.add( fab.y );
  17688. const Ems = Ess.oneMinus();
  17689. const Favg = Fr.add( Fr.oneMinus().mul( 0.047619 ) ); // 1/21
  17690. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  17691. singleScatter.addAssign( FssEss );
  17692. multiScatter.addAssign( Fms.mul( Ems ) );
  17693. }
  17694. /**
  17695. * Implements the direct light.
  17696. *
  17697. * @param {Object} lightData - The light data.
  17698. * @param {NodeBuilder} builder - The current node builder.
  17699. */
  17700. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  17701. const dotNL = normalView.dot( lightDirection ).clamp();
  17702. const irradiance = dotNL.mul( lightColor ).toVar();
  17703. if ( this.sheen === true ) {
  17704. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  17705. const sheenAlbedoV = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17706. const sheenAlbedoL = IBLSheenBRDF( { normal: normalView, viewDir: lightDirection, roughness: sheenRoughness } );
  17707. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedoV.max( sheenAlbedoL ) ).oneMinus();
  17708. irradiance.mulAssign( sheenEnergyComp );
  17709. }
  17710. if ( this.clearcoat === true ) {
  17711. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  17712. const ccIrradiance = dotNLcc.mul( lightColor );
  17713. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  17714. }
  17715. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ) );
  17716. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX_Multiscatter( { lightDirection, f0: specularColorBlended, f90: 1, roughness, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  17717. }
  17718. /**
  17719. * This method is intended for implementing the direct light term for
  17720. * rect area light nodes.
  17721. *
  17722. * @param {Object} input - The input data.
  17723. * @param {NodeBuilder} builder - The current node builder.
  17724. */
  17725. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  17726. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17727. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17728. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17729. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17730. const N = normalView;
  17731. const V = positionViewDirection;
  17732. const P = positionView.toVar();
  17733. const uv = LTC_Uv( { N, V, roughness } );
  17734. const t1 = ltc_1.sample( uv ).toVar();
  17735. const t2 = ltc_2.sample( uv ).toVar();
  17736. const mInv = mat3(
  17737. vec3( t1.x, 0, t1.y ),
  17738. vec3( 0, 1, 0 ),
  17739. vec3( t1.z, 0, t1.w )
  17740. ).toVar();
  17741. // LTC Fresnel Approximation by Stephen Hill
  17742. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  17743. const fresnel = specularColorBlended.mul( t2.x ).add( specularF90.sub( specularColorBlended ).mul( t2.y ) ).toVar();
  17744. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  17745. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseContribution ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  17746. if ( this.clearcoat === true ) {
  17747. const Ncc = clearcoatNormalView;
  17748. const uvClearcoat = LTC_Uv( { N: Ncc, V, roughness: clearcoatRoughness } );
  17749. const t1Clearcoat = ltc_1.sample( uvClearcoat );
  17750. const t2Clearcoat = ltc_2.sample( uvClearcoat );
  17751. const mInvClearcoat = mat3(
  17752. vec3( t1Clearcoat.x, 0, t1Clearcoat.y ),
  17753. vec3( 0, 1, 0 ),
  17754. vec3( t1Clearcoat.z, 0, t1Clearcoat.w )
  17755. );
  17756. // LTC Fresnel Approximation for clearcoat
  17757. const fresnelClearcoat = clearcoatF0.mul( t2Clearcoat.x ).add( clearcoatF90.sub( clearcoatF0 ).mul( t2Clearcoat.y ) );
  17758. this.clearcoatSpecularDirect.addAssign( lightColor.mul( fresnelClearcoat ).mul( LTC_Evaluate( { N: Ncc, V, P, mInv: mInvClearcoat, p0, p1, p2, p3 } ) ) );
  17759. }
  17760. }
  17761. /**
  17762. * Implements the indirect lighting.
  17763. *
  17764. * @param {NodeBuilder} builder - The current node builder.
  17765. */
  17766. indirect( builder ) {
  17767. this.indirectDiffuse( builder );
  17768. this.indirectSpecular( builder );
  17769. this.ambientOcclusion( builder );
  17770. }
  17771. /**
  17772. * Implements the indirect diffuse term.
  17773. *
  17774. * @param {NodeBuilder} builder - The current node builder.
  17775. */
  17776. indirectDiffuse( builder ) {
  17777. const { irradiance, reflectedLight } = builder.context;
  17778. const diffuse = irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ).toVar();
  17779. if ( this.sheen === true ) {
  17780. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17781. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17782. diffuse.mulAssign( sheenEnergyComp );
  17783. }
  17784. reflectedLight.indirectDiffuse.addAssign( diffuse );
  17785. }
  17786. /**
  17787. * Implements the indirect specular term.
  17788. *
  17789. * @param {NodeBuilder} builder - The current node builder.
  17790. */
  17791. indirectSpecular( builder ) {
  17792. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  17793. if ( this.sheen === true ) {
  17794. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  17795. sheen,
  17796. IBLSheenBRDF( {
  17797. normal: normalView,
  17798. viewDir: positionViewDirection,
  17799. roughness: sheenRoughness
  17800. } )
  17801. ) );
  17802. }
  17803. if ( this.clearcoat === true ) {
  17804. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17805. const clearcoatEnv = EnvironmentBRDF( {
  17806. dotNV: dotNVcc,
  17807. specularColor: clearcoatF0,
  17808. specularF90: clearcoatF90,
  17809. roughness: clearcoatRoughness
  17810. } );
  17811. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  17812. }
  17813. // Both indirect specular and indirect diffuse light accumulate here
  17814. // Compute multiscattering separately for dielectric and metallic, then mix
  17815. const singleScatteringDielectric = vec3().toVar( 'singleScatteringDielectric' );
  17816. const multiScatteringDielectric = vec3().toVar( 'multiScatteringDielectric' );
  17817. const singleScatteringMetallic = vec3().toVar( 'singleScatteringMetallic' );
  17818. const multiScatteringMetallic = vec3().toVar( 'multiScatteringMetallic' );
  17819. this.computeMultiscattering( singleScatteringDielectric, multiScatteringDielectric, specularF90, specularColor, this.iridescenceF0Dielectric );
  17820. this.computeMultiscattering( singleScatteringMetallic, multiScatteringMetallic, specularF90, diffuseColor.rgb, this.iridescenceF0Metallic );
  17821. // Mix based on metalness
  17822. const singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, metalness );
  17823. const multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, metalness );
  17824. // Diffuse energy conservation uses dielectric path
  17825. const totalScatteringDielectric = singleScatteringDielectric.add( multiScatteringDielectric );
  17826. const diffuse = diffuseContribution.mul( totalScatteringDielectric.oneMinus() );
  17827. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  17828. const indirectSpecular = radiance.mul( singleScattering ).add( multiScattering.mul( cosineWeightedIrradiance ) ).toVar();
  17829. const indirectDiffuse = diffuse.mul( cosineWeightedIrradiance ).toVar();
  17830. if ( this.sheen === true ) {
  17831. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17832. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17833. indirectSpecular.mulAssign( sheenEnergyComp );
  17834. indirectDiffuse.mulAssign( sheenEnergyComp );
  17835. }
  17836. reflectedLight.indirectSpecular.addAssign( indirectSpecular );
  17837. reflectedLight.indirectDiffuse.addAssign( indirectDiffuse );
  17838. }
  17839. /**
  17840. * Implements the ambient occlusion term.
  17841. *
  17842. * @param {NodeBuilder} builder - The current node builder.
  17843. */
  17844. ambientOcclusion( builder ) {
  17845. const { ambientOcclusion, reflectedLight } = builder.context;
  17846. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17847. const aoNV = dotNV.add( ambientOcclusion );
  17848. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17849. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17850. if ( this.clearcoat === true ) {
  17851. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17852. }
  17853. if ( this.sheen === true ) {
  17854. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  17855. }
  17856. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17857. reflectedLight.indirectSpecular.mulAssign( aoNode );
  17858. }
  17859. /**
  17860. * Used for final lighting accumulations depending on the requested features.
  17861. *
  17862. * @param {NodeBuilder} builder - The current node builder.
  17863. */
  17864. finish( { context } ) {
  17865. const { outgoingLight } = context;
  17866. if ( this.clearcoat === true ) {
  17867. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17868. const Fcc = F_Schlick( {
  17869. dotVH: dotNVcc,
  17870. f0: clearcoatF0,
  17871. f90: clearcoatF90
  17872. } );
  17873. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17874. outgoingLight.assign( clearcoatLight );
  17875. }
  17876. if ( this.sheen === true ) {
  17877. const sheenLight = outgoingLight.add( this.sheenSpecularDirect, this.sheenSpecularIndirect.mul( 1.0 / Math.PI ) );
  17878. outgoingLight.assign( sheenLight );
  17879. }
  17880. }
  17881. }
  17882. // These defines must match with PMREMGenerator
  17883. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17884. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17885. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17886. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17887. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17888. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17889. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17890. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17891. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17892. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17893. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17894. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17895. // These shader functions convert between the UV coordinates of a single face of
  17896. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17897. // sampling a textureCube (not generally normalized ).
  17898. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17899. const absDirection = vec3( abs( direction ) ).toVar();
  17900. const face = float( -1 ).toVar();
  17901. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17902. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17903. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17904. } ).Else( () => {
  17905. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17906. } );
  17907. } ).Else( () => {
  17908. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17909. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17910. } ).Else( () => {
  17911. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17912. } );
  17913. } );
  17914. return face;
  17915. } ).setLayout( {
  17916. name: 'getFace',
  17917. type: 'float',
  17918. inputs: [
  17919. { name: 'direction', type: 'vec3' }
  17920. ]
  17921. } );
  17922. // RH coordinate system; PMREM face-indexing convention
  17923. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17924. const uv = vec2().toVar();
  17925. If( face.equal( 0.0 ), () => {
  17926. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17927. } ).ElseIf( face.equal( 1.0 ), () => {
  17928. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17929. } ).ElseIf( face.equal( 2.0 ), () => {
  17930. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17931. } ).ElseIf( face.equal( 3.0 ), () => {
  17932. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17933. } ).ElseIf( face.equal( 4.0 ), () => {
  17934. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17935. } ).Else( () => {
  17936. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17937. } );
  17938. return mul( 0.5, uv.add( 1.0 ) );
  17939. } ).setLayout( {
  17940. name: 'getUV',
  17941. type: 'vec2',
  17942. inputs: [
  17943. { name: 'direction', type: 'vec3' },
  17944. { name: 'face', type: 'float' }
  17945. ]
  17946. } );
  17947. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17948. const mip = float( 0.0 ).toVar();
  17949. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17950. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17951. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17952. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17953. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17954. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17955. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17956. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17957. } ).Else( () => {
  17958. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17959. } );
  17960. return mip;
  17961. } ).setLayout( {
  17962. name: 'roughnessToMip',
  17963. type: 'float',
  17964. inputs: [
  17965. { name: 'roughness', type: 'float' }
  17966. ]
  17967. } );
  17968. // RH coordinate system; PMREM face-indexing convention
  17969. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17970. const uv = uv_immutable.toVar();
  17971. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17972. const direction = vec3( uv, 1.0 ).toVar();
  17973. If( face.equal( 0.0 ), () => {
  17974. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17975. } ).ElseIf( face.equal( 1.0 ), () => {
  17976. direction.assign( direction.xzy );
  17977. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17978. } ).ElseIf( face.equal( 2.0 ), () => {
  17979. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17980. } ).ElseIf( face.equal( 3.0 ), () => {
  17981. direction.assign( direction.zyx );
  17982. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17983. } ).ElseIf( face.equal( 4.0 ), () => {
  17984. direction.assign( direction.xzy );
  17985. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17986. } ).ElseIf( face.equal( 5.0 ), () => {
  17987. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17988. } );
  17989. return direction;
  17990. } ).setLayout( {
  17991. name: 'getDirection',
  17992. type: 'vec3',
  17993. inputs: [
  17994. { name: 'uv', type: 'vec2' },
  17995. { name: 'face', type: 'float' }
  17996. ]
  17997. } );
  17998. //
  17999. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  18000. const roughness = float( roughness_immutable );
  18001. const sampleDir = vec3( sampleDir_immutable );
  18002. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  18003. const mipF = fract( mip );
  18004. const mipInt = floor( mip );
  18005. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  18006. If( mipF.notEqual( 0.0 ), () => {
  18007. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  18008. color0.assign( mix( color0, color1, mipF ) );
  18009. } );
  18010. return color0;
  18011. } );
  18012. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  18013. const mipInt = float( mipInt_immutable ).toVar();
  18014. const direction = vec3( direction_immutable );
  18015. const face = float( getFace( direction ) ).toVar();
  18016. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  18017. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  18018. const faceSize = float( exp2( mipInt ) ).toVar();
  18019. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  18020. If( face.greaterThan( 2.0 ), () => {
  18021. uv.y.addAssign( faceSize );
  18022. face.subAssign( 3.0 );
  18023. } );
  18024. uv.x.addAssign( face.mul( faceSize ) );
  18025. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  18026. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  18027. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  18028. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  18029. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  18030. } );
  18031. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  18032. const cosTheta = cos( theta );
  18033. // Rodrigues' axis-angle rotation
  18034. const sampleDirection = outputDirection.mul( cosTheta )
  18035. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  18036. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  18037. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  18038. } );
  18039. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  18040. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  18041. If( axis.equal( vec3( 0.0 ) ), () => {
  18042. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  18043. } );
  18044. axis.assign( normalize( axis ) );
  18045. const gl_FragColor = vec3().toVar();
  18046. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  18047. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  18048. If( i.greaterThanEqual( samples ), () => {
  18049. Break();
  18050. } );
  18051. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  18052. 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 } ) ) );
  18053. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  18054. } );
  18055. return vec4( gl_FragColor, 1 );
  18056. } );
  18057. // GGX VNDF importance sampling functions
  18058. // Van der Corput radical inverse for generating quasi-random sequences
  18059. const radicalInverse_VdC = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  18060. const bits = uint( bits_immutable ).toVar();
  18061. bits.assign( bits.shiftLeft( uint( 16 ) ).bitOr( bits.shiftRight( uint( 16 ) ) ) );
  18062. bits.assign( bits.bitAnd( uint( 0x55555555 ) ).shiftLeft( uint( 1 ) ).bitOr( bits.bitAnd( uint( 0xAAAAAAAA ) ).shiftRight( uint( 1 ) ) ) );
  18063. bits.assign( bits.bitAnd( uint( 0x33333333 ) ).shiftLeft( uint( 2 ) ).bitOr( bits.bitAnd( uint( 0xCCCCCCCC ) ).shiftRight( uint( 2 ) ) ) );
  18064. bits.assign( bits.bitAnd( uint( 0x0F0F0F0F ) ).shiftLeft( uint( 4 ) ).bitOr( bits.bitAnd( uint( 0xF0F0F0F0 ) ).shiftRight( uint( 4 ) ) ) );
  18065. bits.assign( bits.bitAnd( uint( 0x00FF00FF ) ).shiftLeft( uint( 8 ) ).bitOr( bits.bitAnd( uint( 0xFF00FF00 ) ).shiftRight( uint( 8 ) ) ) );
  18066. return float( bits ).mul( 2.3283064365386963e-10 ); // / 0x100000000
  18067. } );
  18068. // Hammersley sequence for quasi-Monte Carlo sampling
  18069. const hammersley = /*@__PURE__*/ Fn( ( [ i, N ] ) => {
  18070. return vec2( float( i ).div( float( N ) ), radicalInverse_VdC( i ) );
  18071. } );
  18072. // GGX VNDF importance sampling (Eric Heitz 2018)
  18073. // "Sampling the GGX Distribution of Visible Normals"
  18074. // https://jcgt.org/published/0007/04/01/
  18075. const importanceSampleGGX_VNDF = /*@__PURE__*/ Fn( ( [ Xi, V, roughness ] ) => {
  18076. const alpha = roughness.mul( roughness ).toConst();
  18077. // Section 4.1: Orthonormal basis
  18078. const T1 = vec3( 1.0, 0.0, 0.0 ).toConst();
  18079. const T2 = cross( V, T1 ).toConst();
  18080. // Section 4.2: Parameterization of projected area
  18081. const r = sqrt( Xi.x ).toConst();
  18082. const phi = mul( 2.0, 3.14159265359 ).mul( Xi.y ).toConst();
  18083. const t1 = r.mul( cos( phi ) ).toConst();
  18084. const t2 = r.mul( sin( phi ) ).toVar();
  18085. const s = mul( 0.5, V.z.add( 1.0 ) ).toConst();
  18086. t2.assign( s.oneMinus().mul( sqrt( t1.mul( t1 ).oneMinus() ) ).add( s.mul( t2 ) ) );
  18087. // Section 4.3: Reprojection onto hemisphere
  18088. const Nh = T1.mul( t1 ).add( T2.mul( t2 ) ).add( V.mul( sqrt( max$1( 0.0, t1.mul( t1 ).add( t2.mul( t2 ) ).oneMinus() ) ) ) );
  18089. // Section 3.4: Transform back to ellipsoid configuration
  18090. return normalize( vec3( alpha.mul( Nh.x ), alpha.mul( Nh.y ), max$1( 0.0, Nh.z ) ) );
  18091. } );
  18092. // GGX convolution using VNDF importance sampling
  18093. const ggxConvolution = /*@__PURE__*/ Fn( ( { roughness, mipInt, envMap, N_immutable, GGX_SAMPLES, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  18094. const N = vec3( N_immutable ).toVar();
  18095. const prefilteredColor = vec3( 0.0 ).toVar();
  18096. const totalWeight = float( 0.0 ).toVar();
  18097. // For very low roughness, just sample the environment directly
  18098. If( roughness.lessThan( 0.001 ), () => {
  18099. prefilteredColor.assign( bilinearCubeUV( envMap, N, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) );
  18100. } ).Else( () => {
  18101. // Tangent space basis for VNDF sampling
  18102. const up = select( abs( N.z ).lessThan( 0.999 ), vec3( 0.0, 0.0, 1.0 ), vec3( 1.0, 0.0, 0.0 ) );
  18103. const tangent = normalize( cross( up, N ) ).toVar();
  18104. const bitangent = cross( N, tangent ).toVar();
  18105. Loop( { start: uint( 0 ), end: GGX_SAMPLES }, ( { i } ) => {
  18106. const Xi = hammersley( i, GGX_SAMPLES );
  18107. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  18108. const H_tangent = importanceSampleGGX_VNDF( Xi, vec3( 0.0, 0.0, 1.0 ), roughness );
  18109. // Transform H back to world space
  18110. const H = normalize( tangent.mul( H_tangent.x ).add( bitangent.mul( H_tangent.y ) ).add( N.mul( H_tangent.z ) ) );
  18111. const L = normalize( H.mul( dot( N, H ).mul( 2.0 ) ).sub( N ) );
  18112. const NdotL = max$1( dot( N, L ), 0.0 );
  18113. If( NdotL.greaterThan( 0.0 ), () => {
  18114. // Sample environment at fixed mip level
  18115. // VNDF importance sampling handles the distribution filtering
  18116. const sampleColor = bilinearCubeUV( envMap, L, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  18117. // Weight by NdotL for the split-sum approximation
  18118. // VNDF PDF naturally accounts for the visible microfacet distribution
  18119. prefilteredColor.addAssign( sampleColor.mul( NdotL ) );
  18120. totalWeight.addAssign( NdotL );
  18121. } );
  18122. } );
  18123. If( totalWeight.greaterThan( 0.0 ), () => {
  18124. prefilteredColor.assign( prefilteredColor.div( totalWeight ) );
  18125. } );
  18126. } );
  18127. return vec4( prefilteredColor, 1.0 );
  18128. } );
  18129. const LOD_MIN = 4;
  18130. // The standard deviations (radians) associated with the extra mips.
  18131. // Used for scene blur in fromScene() method.
  18132. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  18133. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  18134. // samples and exit early, but not recompile the shader.
  18135. // Used for scene blur in fromScene() method.
  18136. const MAX_SAMPLES = 20;
  18137. // GGX VNDF importance sampling configuration
  18138. const GGX_SAMPLES = 512;
  18139. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  18140. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  18141. const _clearColor$2 = /*@__PURE__*/ new Color();
  18142. let _oldTarget = null;
  18143. let _oldActiveCubeFace = 0;
  18144. let _oldActiveMipmapLevel = 0;
  18145. const _origin = /*@__PURE__*/ new Vector3();
  18146. // maps blur materials to their uniforms dictionary
  18147. const _uniformsMap = new WeakMap();
  18148. // WebGPU Face indices
  18149. const _faceLib = [
  18150. 3, 1, 5,
  18151. 0, 4, 2
  18152. ];
  18153. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  18154. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  18155. /**
  18156. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  18157. * (PMREM) from a cubeMap environment texture. This allows different levels of
  18158. * blur to be quickly accessed based on material roughness. It is packed into a
  18159. * special CubeUV format that allows us to perform custom interpolation so that
  18160. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  18161. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  18162. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  18163. * higher roughness levels. In this way we maintain resolution to smoothly
  18164. * interpolate diffuse lighting while limiting sampling computation.
  18165. *
  18166. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  18167. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  18168. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  18169. * used in material rendering for physically-based image-based lighting.
  18170. */
  18171. class PMREMGenerator {
  18172. /**
  18173. * Constructs a new PMREM generator.
  18174. *
  18175. * @param {Renderer} renderer - The renderer.
  18176. */
  18177. constructor( renderer ) {
  18178. this._renderer = renderer;
  18179. this._pingPongRenderTarget = null;
  18180. this._lodMax = 0;
  18181. this._cubeSize = 0;
  18182. this._sizeLods = [];
  18183. this._sigmas = [];
  18184. this._lodMeshes = [];
  18185. this._blurMaterial = null;
  18186. this._ggxMaterial = null;
  18187. this._cubemapMaterial = null;
  18188. this._equirectMaterial = null;
  18189. this._backgroundBox = null;
  18190. }
  18191. get _hasInitialized() {
  18192. return this._renderer.hasInitialized();
  18193. }
  18194. /**
  18195. * Generates a PMREM from a supplied Scene, which can be faster than using an
  18196. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  18197. * in radians to be applied to the scene before PMREM generation. Optional near
  18198. * and far planes ensure the scene is rendered in its entirety.
  18199. *
  18200. * @param {Scene} scene - The scene to be captured.
  18201. * @param {number} [sigma=0] - The blur radius in radians.
  18202. * @param {number} [near=0.1] - The near plane distance.
  18203. * @param {number} [far=100] - The far plane distance.
  18204. * @param {Object} [options={}] - The configuration options.
  18205. * @param {number} [options.size=256] - The texture size of the PMREM.
  18206. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  18207. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  18208. * @return {RenderTarget} The resulting PMREM.
  18209. * @see {@link PMREMGenerator#fromScene}
  18210. */
  18211. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  18212. const {
  18213. size = 256,
  18214. position = _origin,
  18215. renderTarget = null,
  18216. } = options;
  18217. this._setSize( size );
  18218. if ( this._hasInitialized === false ) {
  18219. warn( 'PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.' );
  18220. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18221. options.renderTarget = cubeUVRenderTarget;
  18222. this.fromSceneAsync( scene, sigma, near, far, options );
  18223. return cubeUVRenderTarget;
  18224. }
  18225. _oldTarget = this._renderer.getRenderTarget();
  18226. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18227. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18228. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18229. cubeUVRenderTarget.depthBuffer = true;
  18230. this._init( cubeUVRenderTarget );
  18231. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  18232. if ( sigma > 0 ) {
  18233. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  18234. }
  18235. this._applyPMREM( cubeUVRenderTarget );
  18236. this._cleanup( cubeUVRenderTarget );
  18237. return cubeUVRenderTarget;
  18238. }
  18239. /**
  18240. * Generates a PMREM from a supplied Scene, which can be faster than using an
  18241. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  18242. * in radians to be applied to the scene before PMREM generation. Optional near
  18243. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  18244. * is placed at the origin).
  18245. *
  18246. * @deprecated
  18247. * @param {Scene} scene - The scene to be captured.
  18248. * @param {number} [sigma=0] - The blur radius in radians.
  18249. * @param {number} [near=0.1] - The near plane distance.
  18250. * @param {number} [far=100] - The far plane distance.
  18251. * @param {Object} [options={}] - The configuration options.
  18252. * @param {number} [options.size=256] - The texture size of the PMREM.
  18253. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  18254. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  18255. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  18256. * @see {@link PMREMGenerator#fromScene}
  18257. */
  18258. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  18259. warnOnce( 'PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18260. await this._renderer.init();
  18261. return this.fromScene( scene, sigma, near, far, options );
  18262. }
  18263. /**
  18264. * Generates a PMREM from an equirectangular texture, which can be either LDR
  18265. * or HDR. The ideal input image size is 1k (1024 x 512),
  18266. * as this matches best with the 256 x 256 cubemap output.
  18267. *
  18268. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  18269. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18270. * @return {RenderTarget} The resulting PMREM.
  18271. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  18272. */
  18273. fromEquirectangular( equirectangular, renderTarget = null ) {
  18274. if ( this._hasInitialized === false ) {
  18275. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.' );
  18276. this._setSizeFromTexture( equirectangular );
  18277. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18278. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  18279. return cubeUVRenderTarget;
  18280. }
  18281. return this._fromTexture( equirectangular, renderTarget );
  18282. }
  18283. /**
  18284. * Generates a PMREM from an equirectangular texture, which can be either LDR
  18285. * or HDR. The ideal input image size is 1k (1024 x 512),
  18286. * as this matches best with the 256 x 256 cubemap output.
  18287. *
  18288. * @deprecated
  18289. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  18290. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18291. * @return {Promise<RenderTarget>} The resulting PMREM.
  18292. * @see {@link PMREMGenerator#fromEquirectangular}
  18293. */
  18294. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  18295. warnOnce( 'PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18296. await this._renderer.init();
  18297. return this._fromTexture( equirectangular, renderTarget );
  18298. }
  18299. /**
  18300. * Generates a PMREM from an cubemap texture, which can be either LDR
  18301. * or HDR. The ideal input cube size is 256 x 256,
  18302. * as this matches best with the 256 x 256 cubemap output.
  18303. *
  18304. * @param {Texture} cubemap - The cubemap texture to be converted.
  18305. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18306. * @return {RenderTarget} The resulting PMREM.
  18307. * @see {@link PMREMGenerator#fromCubemapAsync}
  18308. */
  18309. fromCubemap( cubemap, renderTarget = null ) {
  18310. if ( this._hasInitialized === false ) {
  18311. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  18312. this._setSizeFromTexture( cubemap );
  18313. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18314. this.fromCubemapAsync( cubemap, renderTarget );
  18315. return cubeUVRenderTarget;
  18316. }
  18317. return this._fromTexture( cubemap, renderTarget );
  18318. }
  18319. /**
  18320. * Generates a PMREM from an cubemap texture, which can be either LDR
  18321. * or HDR. The ideal input cube size is 256 x 256,
  18322. * with the 256 x 256 cubemap output.
  18323. *
  18324. * @deprecated
  18325. * @param {Texture} cubemap - The cubemap texture to be converted.
  18326. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18327. * @return {Promise<RenderTarget>} The resulting PMREM.
  18328. * @see {@link PMREMGenerator#fromCubemap}
  18329. */
  18330. async fromCubemapAsync( cubemap, renderTarget = null ) {
  18331. warnOnce( 'PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18332. await this._renderer.init();
  18333. return this._fromTexture( cubemap, renderTarget );
  18334. }
  18335. /**
  18336. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  18337. * your texture's network fetch for increased concurrency.
  18338. *
  18339. * @returns {Promise}
  18340. */
  18341. async compileCubemapShader() {
  18342. if ( this._cubemapMaterial === null ) {
  18343. this._cubemapMaterial = _getCubemapMaterial();
  18344. await this._compileMaterial( this._cubemapMaterial );
  18345. }
  18346. }
  18347. /**
  18348. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  18349. * your texture's network fetch for increased concurrency.
  18350. *
  18351. * @returns {Promise}
  18352. */
  18353. async compileEquirectangularShader() {
  18354. if ( this._equirectMaterial === null ) {
  18355. this._equirectMaterial = _getEquirectMaterial();
  18356. await this._compileMaterial( this._equirectMaterial );
  18357. }
  18358. }
  18359. /**
  18360. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  18361. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  18362. * one of them will cause any others to also become unusable.
  18363. */
  18364. dispose() {
  18365. this._dispose();
  18366. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  18367. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  18368. if ( this._backgroundBox !== null ) {
  18369. this._backgroundBox.geometry.dispose();
  18370. this._backgroundBox.material.dispose();
  18371. }
  18372. }
  18373. // private interface
  18374. _setSizeFromTexture( texture ) {
  18375. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  18376. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  18377. } else { // Equirectangular
  18378. this._setSize( texture.image.width / 4 );
  18379. }
  18380. }
  18381. _setSize( cubeSize ) {
  18382. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  18383. this._cubeSize = Math.pow( 2, this._lodMax );
  18384. }
  18385. _dispose() {
  18386. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  18387. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  18388. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  18389. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  18390. this._lodMeshes[ i ].geometry.dispose();
  18391. }
  18392. }
  18393. _cleanup( outputTarget ) {
  18394. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  18395. outputTarget.scissorTest = false;
  18396. this._setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  18397. }
  18398. _fromTexture( texture, renderTarget ) {
  18399. this._setSizeFromTexture( texture );
  18400. _oldTarget = this._renderer.getRenderTarget();
  18401. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18402. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18403. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18404. this._init( cubeUVRenderTarget );
  18405. this._textureToCubeUV( texture, cubeUVRenderTarget );
  18406. this._applyPMREM( cubeUVRenderTarget );
  18407. this._cleanup( cubeUVRenderTarget );
  18408. return cubeUVRenderTarget;
  18409. }
  18410. _allocateTarget() {
  18411. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  18412. const height = 4 * this._cubeSize;
  18413. const cubeUVRenderTarget = _createRenderTarget( width, height );
  18414. return cubeUVRenderTarget;
  18415. }
  18416. _init( renderTarget ) {
  18417. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  18418. if ( this._pingPongRenderTarget !== null ) {
  18419. this._dispose();
  18420. }
  18421. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  18422. const { _lodMax } = this;
  18423. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  18424. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  18425. this._ggxMaterial = _getGGXShader( _lodMax, renderTarget.width, renderTarget.height );
  18426. }
  18427. }
  18428. async _compileMaterial( material ) {
  18429. const mesh = new Mesh( new BufferGeometry(), material );
  18430. await this._renderer.compile( mesh, _flatCamera );
  18431. }
  18432. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  18433. const cubeCamera = _cubeCamera;
  18434. cubeCamera.near = near;
  18435. cubeCamera.far = far;
  18436. // px, py, pz, nx, ny, nz
  18437. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  18438. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  18439. const renderer = this._renderer;
  18440. const originalAutoClear = renderer.autoClear;
  18441. renderer.getClearColor( _clearColor$2 );
  18442. renderer.autoClear = false;
  18443. if ( this._backgroundBox === null ) {
  18444. this._backgroundBox = new Mesh(
  18445. new BoxGeometry(),
  18446. new MeshBasicMaterial( {
  18447. name: 'PMREM.Background',
  18448. side: BackSide,
  18449. depthWrite: false,
  18450. depthTest: false,
  18451. } )
  18452. );
  18453. }
  18454. const backgroundBox = this._backgroundBox;
  18455. const backgroundMaterial = backgroundBox.material;
  18456. let useSolidColor = false;
  18457. const background = scene.background;
  18458. if ( background ) {
  18459. if ( background.isColor ) {
  18460. backgroundMaterial.color.copy( background );
  18461. scene.background = null;
  18462. useSolidColor = true;
  18463. }
  18464. } else {
  18465. backgroundMaterial.color.copy( _clearColor$2 );
  18466. useSolidColor = true;
  18467. }
  18468. renderer.setRenderTarget( cubeUVRenderTarget );
  18469. renderer.clear();
  18470. if ( useSolidColor ) {
  18471. renderer.render( backgroundBox, cubeCamera );
  18472. }
  18473. for ( let i = 0; i < 6; i ++ ) {
  18474. const col = i % 3;
  18475. if ( col === 0 ) {
  18476. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18477. cubeCamera.position.set( position.x, position.y, position.z );
  18478. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  18479. } else if ( col === 1 ) {
  18480. cubeCamera.up.set( 0, 0, upSign[ i ] );
  18481. cubeCamera.position.set( position.x, position.y, position.z );
  18482. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  18483. } else {
  18484. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18485. cubeCamera.position.set( position.x, position.y, position.z );
  18486. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  18487. }
  18488. const size = this._cubeSize;
  18489. this._setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  18490. renderer.render( scene, cubeCamera );
  18491. }
  18492. renderer.autoClear = originalAutoClear;
  18493. scene.background = background;
  18494. }
  18495. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  18496. const renderer = this._renderer;
  18497. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  18498. if ( isCubeTexture ) {
  18499. if ( this._cubemapMaterial === null ) {
  18500. this._cubemapMaterial = _getCubemapMaterial( texture );
  18501. }
  18502. } else {
  18503. if ( this._equirectMaterial === null ) {
  18504. this._equirectMaterial = _getEquirectMaterial( texture );
  18505. }
  18506. }
  18507. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  18508. material.fragmentNode.value = texture;
  18509. const mesh = this._lodMeshes[ 0 ];
  18510. mesh.material = material;
  18511. const size = this._cubeSize;
  18512. this._setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  18513. renderer.setRenderTarget( cubeUVRenderTarget );
  18514. renderer.render( mesh, _flatCamera );
  18515. }
  18516. _applyPMREM( cubeUVRenderTarget ) {
  18517. const renderer = this._renderer;
  18518. const autoClear = renderer.autoClear;
  18519. renderer.autoClear = false;
  18520. const n = this._lodMeshes.length;
  18521. // Use GGX VNDF importance sampling
  18522. for ( let i = 1; i < n; i ++ ) {
  18523. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  18524. }
  18525. renderer.autoClear = autoClear;
  18526. }
  18527. /**
  18528. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  18529. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  18530. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  18531. * applies incremental roughness filtering to avoid over-blurring.
  18532. *
  18533. * @private
  18534. * @param {RenderTarget} cubeUVRenderTarget
  18535. * @param {number} lodIn - Source LOD level to read from
  18536. * @param {number} lodOut - Target LOD level to write to
  18537. */
  18538. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  18539. const renderer = this._renderer;
  18540. const pingPongRenderTarget = this._pingPongRenderTarget;
  18541. const ggxMaterial = this._ggxMaterial;
  18542. const ggxMesh = this._lodMeshes[ lodOut ];
  18543. ggxMesh.material = ggxMaterial;
  18544. const ggxUniforms = _uniformsMap.get( ggxMaterial );
  18545. // Calculate incremental roughness between LOD levels
  18546. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  18547. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  18548. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  18549. // Apply blur strength mapping for better quality across the roughness range
  18550. const blurStrength = 0.0 + targetRoughness * 1.25;
  18551. const adjustedRoughness = incrementalRoughness * blurStrength;
  18552. // Calculate viewport position based on output LOD level
  18553. const { _lodMax } = this;
  18554. const outputSize = this._sizeLods[ lodOut ];
  18555. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18556. const y = 4 * ( this._cubeSize - outputSize );
  18557. // Read from previous LOD with incremental roughness
  18558. cubeUVRenderTarget.texture.frame = ( cubeUVRenderTarget.texture.frame || 0 ) + 1;
  18559. ggxUniforms.envMap.value = cubeUVRenderTarget.texture;
  18560. ggxUniforms.roughness.value = adjustedRoughness;
  18561. ggxUniforms.mipInt.value = _lodMax - lodIn; // Sample from input LOD
  18562. this._setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18563. renderer.setRenderTarget( pingPongRenderTarget );
  18564. renderer.render( ggxMesh, _flatCamera );
  18565. // Copy from pingPong back to cubeUV (simple direct copy)
  18566. pingPongRenderTarget.texture.frame = ( pingPongRenderTarget.texture.frame || 0 ) + 1;
  18567. ggxUniforms.envMap.value = pingPongRenderTarget.texture;
  18568. ggxUniforms.roughness.value = 0.0; // Direct copy
  18569. ggxUniforms.mipInt.value = _lodMax - lodOut; // Read from the level we just wrote
  18570. this._setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18571. renderer.setRenderTarget( cubeUVRenderTarget );
  18572. renderer.render( ggxMesh, _flatCamera );
  18573. }
  18574. /**
  18575. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  18576. * vertically and horizontally, but this breaks down on a cube. Here we apply
  18577. * the blur latitudinally (around the poles), and then longitudinally (towards
  18578. * the poles) to approximate the orthogonally-separable blur. It is least
  18579. * accurate at the poles, but still does a decent job.
  18580. *
  18581. * Used for initial scene blur in fromScene() method when sigma > 0.
  18582. *
  18583. * @private
  18584. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  18585. * @param {number} lodIn - The input level-of-detail.
  18586. * @param {number} lodOut - The output level-of-detail.
  18587. * @param {number} sigma - The blur radius in radians.
  18588. * @param {Vector3} [poleAxis] - The pole axis.
  18589. */
  18590. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  18591. const pingPongRenderTarget = this._pingPongRenderTarget;
  18592. this._halfBlur(
  18593. cubeUVRenderTarget,
  18594. pingPongRenderTarget,
  18595. lodIn,
  18596. lodOut,
  18597. sigma,
  18598. 'latitudinal',
  18599. poleAxis );
  18600. this._halfBlur(
  18601. pingPongRenderTarget,
  18602. cubeUVRenderTarget,
  18603. lodOut,
  18604. lodOut,
  18605. sigma,
  18606. 'longitudinal',
  18607. poleAxis );
  18608. }
  18609. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  18610. const renderer = this._renderer;
  18611. const blurMaterial = this._blurMaterial;
  18612. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  18613. error( 'blur direction must be either latitudinal or longitudinal!' );
  18614. }
  18615. // Number of standard deviations at which to cut off the discrete approximation.
  18616. const STANDARD_DEVIATIONS = 3;
  18617. const blurMesh = this._lodMeshes[ lodOut ];
  18618. blurMesh.material = blurMaterial;
  18619. const blurUniforms = _uniformsMap.get( blurMaterial );
  18620. const pixels = this._sizeLods[ lodIn ] - 1;
  18621. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  18622. const sigmaPixels = sigmaRadians / radiansPerPixel;
  18623. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  18624. if ( samples > MAX_SAMPLES ) {
  18625. warn( `sigmaRadians, ${
  18626. sigmaRadians}, is too large and will clip, as it requested ${
  18627. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  18628. }
  18629. const weights = [];
  18630. let sum = 0;
  18631. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  18632. const x = i / sigmaPixels;
  18633. const weight = Math.exp( - x * x / 2 );
  18634. weights.push( weight );
  18635. if ( i === 0 ) {
  18636. sum += weight;
  18637. } else if ( i < samples ) {
  18638. sum += 2 * weight;
  18639. }
  18640. }
  18641. for ( let i = 0; i < weights.length; i ++ ) {
  18642. weights[ i ] = weights[ i ] / sum;
  18643. }
  18644. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18645. blurUniforms.envMap.value = targetIn.texture;
  18646. blurUniforms.samples.value = samples;
  18647. blurUniforms.weights.array = weights;
  18648. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  18649. if ( poleAxis ) {
  18650. blurUniforms.poleAxis.value = poleAxis;
  18651. }
  18652. const { _lodMax } = this;
  18653. blurUniforms.dTheta.value = radiansPerPixel;
  18654. blurUniforms.mipInt.value = _lodMax - lodIn;
  18655. const outputSize = this._sizeLods[ lodOut ];
  18656. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18657. const y = 4 * ( this._cubeSize - outputSize );
  18658. this._setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18659. renderer.setRenderTarget( targetOut );
  18660. renderer.render( blurMesh, _flatCamera );
  18661. }
  18662. _setViewport( target, x, y, width, height ) {
  18663. if ( this._renderer.isWebGLRenderer ) {
  18664. target.viewport.set( x, target.height - height - y, width, height );
  18665. target.scissor.set( x, target.height - height - y, width, height );
  18666. } else {
  18667. target.viewport.set( x, y, width, height );
  18668. target.scissor.set( x, y, width, height );
  18669. }
  18670. }
  18671. }
  18672. function _createPlanes( lodMax ) {
  18673. const sizeLods = [];
  18674. const sigmas = [];
  18675. const lodMeshes = [];
  18676. let lod = lodMax;
  18677. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  18678. for ( let i = 0; i < totalLods; i ++ ) {
  18679. const sizeLod = Math.pow( 2, lod );
  18680. sizeLods.push( sizeLod );
  18681. let sigma = 1.0 / sizeLod;
  18682. if ( i > lodMax - LOD_MIN ) {
  18683. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  18684. } else if ( i === 0 ) {
  18685. sigma = 0;
  18686. }
  18687. sigmas.push( sigma );
  18688. const texelSize = 1.0 / ( sizeLod - 2 );
  18689. const min = - texelSize;
  18690. const max = 1 + texelSize;
  18691. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18692. const cubeFaces = 6;
  18693. const vertices = 6;
  18694. const positionSize = 3;
  18695. const uvSize = 2;
  18696. const faceIndexSize = 1;
  18697. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18698. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  18699. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  18700. for ( let face = 0; face < cubeFaces; face ++ ) {
  18701. const x = ( face % 3 ) * 2 / 3 - 1;
  18702. const y = face > 2 ? 0 : -1;
  18703. const coordinates = [
  18704. x, y, 0,
  18705. x + 2 / 3, y, 0,
  18706. x + 2 / 3, y + 1, 0,
  18707. x, y, 0,
  18708. x + 2 / 3, y + 1, 0,
  18709. x, y + 1, 0
  18710. ];
  18711. const faceIdx = _faceLib[ face ];
  18712. position.set( coordinates, positionSize * vertices * faceIdx );
  18713. uv.set( uv1, uvSize * vertices * faceIdx );
  18714. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  18715. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  18716. }
  18717. const planes = new BufferGeometry();
  18718. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18719. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  18720. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  18721. lodMeshes.push( new Mesh( planes, null ) );
  18722. if ( lod > LOD_MIN ) {
  18723. lod --;
  18724. }
  18725. }
  18726. return { lodMeshes, sizeLods, sigmas };
  18727. }
  18728. function _createRenderTarget( width, height ) {
  18729. const params = {
  18730. magFilter: LinearFilter,
  18731. minFilter: LinearFilter,
  18732. generateMipmaps: false,
  18733. type: HalfFloatType,
  18734. format: RGBAFormat,
  18735. colorSpace: LinearSRGBColorSpace,
  18736. //depthBuffer: false
  18737. };
  18738. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18739. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18740. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18741. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18742. cubeUVRenderTarget.scissorTest = true;
  18743. return cubeUVRenderTarget;
  18744. }
  18745. function _getMaterial( type ) {
  18746. const material = new NodeMaterial();
  18747. material.depthTest = false;
  18748. material.depthWrite = false;
  18749. material.blending = NoBlending;
  18750. material.name = `PMREM_${ type }`;
  18751. return material;
  18752. }
  18753. function _getBlurShader( lodMax, width, height ) {
  18754. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  18755. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  18756. const dTheta = uniform( 0 );
  18757. const n = float( MAX_SAMPLES );
  18758. const latitudinal = uniform( 0 ); // false, bool
  18759. const samples = uniform( 1 ); // int
  18760. const envMap = texture();
  18761. const mipInt = uniform( 0 ); // int
  18762. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18763. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18764. const CUBEUV_MAX_MIP = float( lodMax );
  18765. const materialUniforms = {
  18766. n,
  18767. latitudinal,
  18768. weights,
  18769. poleAxis,
  18770. outputDirection: _outputDirection,
  18771. dTheta,
  18772. samples,
  18773. envMap,
  18774. mipInt,
  18775. CUBEUV_TEXEL_WIDTH,
  18776. CUBEUV_TEXEL_HEIGHT,
  18777. CUBEUV_MAX_MIP
  18778. };
  18779. const material = _getMaterial( 'blur' );
  18780. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  18781. _uniformsMap.set( material, materialUniforms );
  18782. return material;
  18783. }
  18784. function _getGGXShader( lodMax, width, height ) {
  18785. const envMap = texture();
  18786. const roughness = uniform( 0 );
  18787. const mipInt = uniform( 0 );
  18788. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18789. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18790. const CUBEUV_MAX_MIP = float( lodMax );
  18791. const materialUniforms = {
  18792. envMap,
  18793. roughness,
  18794. mipInt,
  18795. CUBEUV_TEXEL_WIDTH,
  18796. CUBEUV_TEXEL_HEIGHT,
  18797. CUBEUV_MAX_MIP
  18798. };
  18799. const material = _getMaterial( 'ggx' );
  18800. material.fragmentNode = ggxConvolution( {
  18801. ...materialUniforms,
  18802. N_immutable: _outputDirection,
  18803. GGX_SAMPLES: uint( GGX_SAMPLES )
  18804. } );
  18805. _uniformsMap.set( material, materialUniforms );
  18806. return material;
  18807. }
  18808. function _getCubemapMaterial( envTexture ) {
  18809. const material = _getMaterial( 'cubemap' );
  18810. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  18811. return material;
  18812. }
  18813. function _getEquirectMaterial( envTexture ) {
  18814. const material = _getMaterial( 'equirect' );
  18815. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  18816. return material;
  18817. }
  18818. const _cache = new WeakMap();
  18819. /**
  18820. * Generates the cubeUV size based on the given image height.
  18821. *
  18822. * @private
  18823. * @param {number} imageHeight - The image height.
  18824. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  18825. */
  18826. function _generateCubeUVSize( imageHeight ) {
  18827. const maxMip = Math.log2( imageHeight ) - 2;
  18828. const texelHeight = 1.0 / imageHeight;
  18829. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  18830. return { texelWidth, texelHeight, maxMip };
  18831. }
  18832. /**
  18833. * Generates a PMREM from the given texture.
  18834. *
  18835. * @private
  18836. * @param {Texture} texture - The texture to create the PMREM for.
  18837. * @param {Renderer} renderer - The renderer.
  18838. * @param {PMREMGenerator} generator - The PMREM generator.
  18839. * @return {?Texture} The PMREM.
  18840. */
  18841. function _getPMREMFromTexture( texture, renderer, generator ) {
  18842. const cache = _getCache( renderer );
  18843. let cacheTexture = cache.get( texture );
  18844. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  18845. if ( pmremVersion !== texture.pmremVersion ) {
  18846. const image = texture.image;
  18847. if ( texture.isCubeTexture ) {
  18848. if ( isCubeMapReady( image ) ) {
  18849. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  18850. } else {
  18851. return null;
  18852. }
  18853. } else {
  18854. if ( isEquirectangularMapReady( image ) ) {
  18855. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  18856. } else {
  18857. return null;
  18858. }
  18859. }
  18860. cacheTexture.pmremVersion = texture.pmremVersion;
  18861. cache.set( texture, cacheTexture );
  18862. }
  18863. return cacheTexture.texture;
  18864. }
  18865. /**
  18866. * Returns a cache that stores generated PMREMs for the respective textures.
  18867. * A cache must be maintained per renderer since PMREMs are render target textures
  18868. * which can't be shared across render contexts.
  18869. *
  18870. * @private
  18871. * @param {Renderer} renderer - The renderer.
  18872. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  18873. */
  18874. function _getCache( renderer ) {
  18875. let rendererCache = _cache.get( renderer );
  18876. if ( rendererCache === undefined ) {
  18877. rendererCache = new WeakMap();
  18878. _cache.set( renderer, rendererCache );
  18879. }
  18880. return rendererCache;
  18881. }
  18882. /**
  18883. * This node represents a PMREM which is a special type of preprocessed
  18884. * environment map intended for PBR materials.
  18885. *
  18886. * ```js
  18887. * const material = new MeshStandardNodeMaterial();
  18888. * material.envNode = pmremTexture( envMap );
  18889. * ```
  18890. *
  18891. * @augments TempNode
  18892. */
  18893. class PMREMNode extends TempNode {
  18894. static get type() {
  18895. return 'PMREMNode';
  18896. }
  18897. /**
  18898. * Constructs a new function overloading node.
  18899. *
  18900. * @param {Texture} value - The input texture.
  18901. * @param {Node<vec2>} [uvNode=null] - The uv node.
  18902. * @param {Node<float>} [levelNode=null] - The level node.
  18903. */
  18904. constructor( value, uvNode = null, levelNode = null ) {
  18905. super( 'vec3' );
  18906. /**
  18907. * Reference to the input texture.
  18908. *
  18909. * @private
  18910. * @type {Texture}
  18911. */
  18912. this._value = value;
  18913. /**
  18914. * Reference to the generated PMREM.
  18915. *
  18916. * @private
  18917. * @type {Texture | null}
  18918. * @default null
  18919. */
  18920. this._pmrem = null;
  18921. /**
  18922. * The uv node.
  18923. *
  18924. * @type {Node<vec2>}
  18925. */
  18926. this.uvNode = uvNode;
  18927. /**
  18928. * The level node.
  18929. *
  18930. * @type {Node<float>}
  18931. */
  18932. this.levelNode = levelNode;
  18933. /**
  18934. * Reference to a PMREM generator.
  18935. *
  18936. * @private
  18937. * @type {?PMREMGenerator}
  18938. * @default null
  18939. */
  18940. this._generator = null;
  18941. const defaultTexture = new Texture();
  18942. defaultTexture.isRenderTargetTexture = true;
  18943. /**
  18944. * The texture node holding the generated PMREM.
  18945. *
  18946. * @private
  18947. * @type {TextureNode}
  18948. */
  18949. this._texture = texture( defaultTexture );
  18950. /**
  18951. * A uniform representing the PMREM's width.
  18952. *
  18953. * @private
  18954. * @type {UniformNode<float>}
  18955. */
  18956. this._width = uniform( 0 );
  18957. /**
  18958. * A uniform representing the PMREM's height.
  18959. *
  18960. * @private
  18961. * @type {UniformNode<float>}
  18962. */
  18963. this._height = uniform( 0 );
  18964. /**
  18965. * A uniform representing the PMREM's max Mip.
  18966. *
  18967. * @private
  18968. * @type {UniformNode<float>}
  18969. */
  18970. this._maxMip = uniform( 0 );
  18971. /**
  18972. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  18973. *
  18974. * @type {string}
  18975. * @default 'render'
  18976. */
  18977. this.updateBeforeType = NodeUpdateType.RENDER;
  18978. }
  18979. set value( value ) {
  18980. this._value = value;
  18981. this._pmrem = null;
  18982. }
  18983. /**
  18984. * The node's texture value.
  18985. *
  18986. * @type {Texture}
  18987. */
  18988. get value() {
  18989. return this._value;
  18990. }
  18991. /**
  18992. * Uses the given PMREM texture to update internal values.
  18993. *
  18994. * @param {Texture} texture - The PMREM texture.
  18995. */
  18996. updateFromTexture( texture ) {
  18997. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  18998. this._texture.value = texture;
  18999. this._width.value = cubeUVSize.texelWidth;
  19000. this._height.value = cubeUVSize.texelHeight;
  19001. this._maxMip.value = cubeUVSize.maxMip;
  19002. }
  19003. updateBefore( frame ) {
  19004. let pmrem = this._pmrem;
  19005. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  19006. const texture = this._value;
  19007. if ( pmremVersion !== texture.pmremVersion ) {
  19008. if ( texture.isPMREMTexture === true ) {
  19009. pmrem = texture;
  19010. } else {
  19011. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  19012. }
  19013. if ( pmrem !== null ) {
  19014. this._pmrem = pmrem;
  19015. this.updateFromTexture( pmrem );
  19016. }
  19017. }
  19018. }
  19019. setup( builder ) {
  19020. if ( this._generator === null ) {
  19021. this._generator = new PMREMGenerator( builder.renderer );
  19022. }
  19023. this.updateBefore( builder );
  19024. //
  19025. let uvNode = this.uvNode;
  19026. if ( uvNode === null && builder.context.getUV ) {
  19027. uvNode = builder.context.getUV( this, builder );
  19028. }
  19029. //
  19030. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  19031. //
  19032. let levelNode = this.levelNode;
  19033. if ( levelNode === null && builder.context.getTextureLevel ) {
  19034. levelNode = builder.context.getTextureLevel( this );
  19035. }
  19036. //
  19037. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  19038. }
  19039. dispose() {
  19040. super.dispose();
  19041. if ( this._generator !== null ) this._generator.dispose();
  19042. }
  19043. }
  19044. /**
  19045. * Returns `true` if the given cube map image has been fully loaded.
  19046. *
  19047. * @private
  19048. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  19049. * @return {boolean} Whether the given cube map is ready or not.
  19050. */
  19051. function isCubeMapReady( image ) {
  19052. if ( image === null || image === undefined ) return false;
  19053. let count = 0;
  19054. const length = 6;
  19055. for ( let i = 0; i < length; i ++ ) {
  19056. if ( image[ i ] !== undefined ) count ++;
  19057. }
  19058. return count === length;
  19059. }
  19060. /**
  19061. * Returns `true` if the given equirectangular image has been fully loaded.
  19062. *
  19063. * @private
  19064. * @param {(Image|Object)} image - The equirectangular image.
  19065. * @return {boolean} Whether the given cube map is ready or not.
  19066. */
  19067. function isEquirectangularMapReady( image ) {
  19068. if ( image === null || image === undefined ) return false;
  19069. return image.height > 0;
  19070. }
  19071. /**
  19072. * TSL function for creating a PMREM node.
  19073. *
  19074. * @tsl
  19075. * @function
  19076. * @param {Texture} value - The input texture.
  19077. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  19078. * @param {?Node<float>} [levelNode=null] - The level node.
  19079. * @returns {PMREMNode}
  19080. */
  19081. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  19082. const _rendererCache = new WeakMap();
  19083. /**
  19084. * Represents a physical model for Image-based lighting (IBL). The environment
  19085. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  19086. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  19087. *
  19088. * @augments LightingNode
  19089. */
  19090. class EnvironmentNode extends LightingNode {
  19091. static get type() {
  19092. return 'EnvironmentNode';
  19093. }
  19094. /**
  19095. * Constructs a new environment node.
  19096. *
  19097. * @param {Node} [envNode=null] - A node representing the environment.
  19098. */
  19099. constructor( envNode = null ) {
  19100. super();
  19101. /**
  19102. * A node representing the environment.
  19103. *
  19104. * @type {?Node}
  19105. * @default null
  19106. */
  19107. this.envNode = envNode;
  19108. }
  19109. setup( builder ) {
  19110. const { material } = builder;
  19111. let envNode = this.envNode;
  19112. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  19113. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  19114. const cache = this._getPMREMNodeCache( builder.renderer );
  19115. let cacheEnvNode = cache.get( value );
  19116. if ( cacheEnvNode === undefined ) {
  19117. cacheEnvNode = pmremTexture( value );
  19118. cache.set( value, cacheEnvNode );
  19119. }
  19120. envNode = cacheEnvNode;
  19121. }
  19122. //
  19123. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  19124. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  19125. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  19126. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  19127. const isolateRadiance = isolate( radiance );
  19128. const isolateIrradiance = isolate( irradiance );
  19129. //
  19130. builder.context.radiance.addAssign( isolateRadiance );
  19131. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  19132. //
  19133. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  19134. if ( clearcoatRadiance ) {
  19135. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  19136. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  19137. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  19138. }
  19139. }
  19140. /**
  19141. * Returns the PMREM node cache of the current renderer.
  19142. *
  19143. * @private
  19144. * @param {Renderer} renderer - The current renderer.
  19145. * @return {WeakMap} The node cache.
  19146. */
  19147. _getPMREMNodeCache( renderer ) {
  19148. let pmremCache = _rendererCache.get( renderer );
  19149. if ( pmremCache === undefined ) {
  19150. pmremCache = new WeakMap();
  19151. _rendererCache.set( renderer, pmremCache );
  19152. }
  19153. return pmremCache;
  19154. }
  19155. }
  19156. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  19157. let reflectVec = null;
  19158. return {
  19159. getUV: () => {
  19160. if ( reflectVec === null ) {
  19161. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  19162. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  19163. reflectVec = pow4( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  19164. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  19165. }
  19166. return reflectVec;
  19167. },
  19168. getTextureLevel: () => {
  19169. return roughnessNode;
  19170. }
  19171. };
  19172. };
  19173. const createIrradianceContext = ( normalWorldNode ) => {
  19174. return {
  19175. getUV: () => {
  19176. return normalWorldNode;
  19177. },
  19178. getTextureLevel: () => {
  19179. return float( 1.0 );
  19180. }
  19181. };
  19182. };
  19183. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  19184. /**
  19185. * Node material version of {@link MeshStandardMaterial}.
  19186. *
  19187. * @augments NodeMaterial
  19188. */
  19189. class MeshStandardNodeMaterial extends NodeMaterial {
  19190. static get type() {
  19191. return 'MeshStandardNodeMaterial';
  19192. }
  19193. /**
  19194. * Constructs a new mesh standard node material.
  19195. *
  19196. * @param {Object} [parameters] - The configuration parameter.
  19197. */
  19198. constructor( parameters ) {
  19199. super();
  19200. /**
  19201. * This flag can be used for type testing.
  19202. *
  19203. * @type {boolean}
  19204. * @readonly
  19205. * @default true
  19206. */
  19207. this.isMeshStandardNodeMaterial = true;
  19208. /**
  19209. * Set to `true` because standard materials react on lights.
  19210. *
  19211. * @type {boolean}
  19212. * @default true
  19213. */
  19214. this.lights = true;
  19215. /**
  19216. * The emissive color of standard materials is by default inferred from the `emissive`,
  19217. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  19218. * overwrite the default and define the emissive color with a node instead.
  19219. *
  19220. * If you don't want to overwrite the emissive color but modify the existing
  19221. * value instead, use {@link materialEmissive}.
  19222. *
  19223. * @type {?Node<vec3>}
  19224. * @default null
  19225. */
  19226. this.emissiveNode = null;
  19227. /**
  19228. * The metalness of standard materials is by default inferred from the `metalness`,
  19229. * and `metalnessMap` properties. This node property allows to
  19230. * overwrite the default and define the metalness with a node instead.
  19231. *
  19232. * If you don't want to overwrite the metalness but modify the existing
  19233. * value instead, use {@link materialMetalness}.
  19234. *
  19235. * @type {?Node<float>}
  19236. * @default null
  19237. */
  19238. this.metalnessNode = null;
  19239. /**
  19240. * The roughness of standard materials is by default inferred from the `roughness`,
  19241. * and `roughnessMap` properties. This node property allows to
  19242. * overwrite the default and define the roughness with a node instead.
  19243. *
  19244. * If you don't want to overwrite the roughness but modify the existing
  19245. * value instead, use {@link materialRoughness}.
  19246. *
  19247. * @type {?Node<float>}
  19248. * @default null
  19249. */
  19250. this.roughnessNode = null;
  19251. this.setDefaultValues( _defaultValues$6 );
  19252. this.setValues( parameters );
  19253. }
  19254. /**
  19255. * Overwritten since this type of material uses {@link EnvironmentNode}
  19256. * to implement the PBR (PMREM based) environment mapping. Besides, the
  19257. * method honors `Scene.environment`.
  19258. *
  19259. * @param {NodeBuilder} builder - The current node builder.
  19260. * @return {?EnvironmentNode<vec3>} The environment node.
  19261. */
  19262. setupEnvironment( builder ) {
  19263. let envNode = super.setupEnvironment( builder );
  19264. if ( envNode === null && builder.environmentNode ) {
  19265. envNode = builder.environmentNode;
  19266. }
  19267. return envNode ? new EnvironmentNode( envNode ) : null;
  19268. }
  19269. /**
  19270. * Setups the lighting model.
  19271. *
  19272. * @return {PhysicalLightingModel} The lighting model.
  19273. */
  19274. setupLightingModel( /*builder*/ ) {
  19275. return new PhysicalLightingModel();
  19276. }
  19277. /**
  19278. * Setups the specular related node variables.
  19279. */
  19280. setupSpecular() {
  19281. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  19282. specularColor.assign( vec3( 0.04 ) );
  19283. specularColorBlended.assign( specularColorNode );
  19284. specularF90.assign( 1.0 );
  19285. }
  19286. /**
  19287. * Setups the standard specific node variables.
  19288. *
  19289. * @param {NodeBuilder} builder - The current node builder.
  19290. */
  19291. setupVariants() {
  19292. // METALNESS
  19293. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  19294. metalness.assign( metalnessNode );
  19295. // ROUGHNESS
  19296. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  19297. roughnessNode = getRoughness( { roughness: roughnessNode } );
  19298. roughness.assign( roughnessNode );
  19299. // SPECULAR COLOR
  19300. this.setupSpecular();
  19301. // DIFFUSE COLOR
  19302. diffuseContribution.assign( diffuseColor.rgb.mul( metalnessNode.oneMinus() ) );
  19303. }
  19304. copy( source ) {
  19305. this.emissiveNode = source.emissiveNode;
  19306. this.metalnessNode = source.metalnessNode;
  19307. this.roughnessNode = source.roughnessNode;
  19308. return super.copy( source );
  19309. }
  19310. }
  19311. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  19312. /**
  19313. * Node material version of {@link MeshPhysicalMaterial}.
  19314. *
  19315. * @augments MeshStandardNodeMaterial
  19316. */
  19317. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  19318. static get type() {
  19319. return 'MeshPhysicalNodeMaterial';
  19320. }
  19321. /**
  19322. * Constructs a new mesh physical node material.
  19323. *
  19324. * @param {Object} [parameters] - The configuration parameter.
  19325. */
  19326. constructor( parameters ) {
  19327. super();
  19328. /**
  19329. * This flag can be used for type testing.
  19330. *
  19331. * @type {boolean}
  19332. * @readonly
  19333. * @default true
  19334. */
  19335. this.isMeshPhysicalNodeMaterial = true;
  19336. /**
  19337. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  19338. * and `clearcoatMap` properties. This node property allows to overwrite the default
  19339. * and define the clearcoat with a node instead.
  19340. *
  19341. * If you don't want to overwrite the clearcoat but modify the existing
  19342. * value instead, use {@link materialClearcoat}.
  19343. *
  19344. * @type {?Node<float>}
  19345. * @default null
  19346. */
  19347. this.clearcoatNode = null;
  19348. /**
  19349. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  19350. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  19351. * and define the clearcoat roughness with a node instead.
  19352. *
  19353. * If you don't want to overwrite the clearcoat roughness but modify the existing
  19354. * value instead, use {@link materialClearcoatRoughness}.
  19355. *
  19356. * @type {?Node<float>}
  19357. * @default null
  19358. */
  19359. this.clearcoatRoughnessNode = null;
  19360. /**
  19361. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  19362. * property. This node property allows to overwrite the default
  19363. * and define the clearcoat normal with a node instead.
  19364. *
  19365. * If you don't want to overwrite the clearcoat normal but modify the existing
  19366. * value instead, use {@link materialClearcoatNormal}.
  19367. *
  19368. * @type {?Node<vec3>}
  19369. * @default null
  19370. */
  19371. this.clearcoatNormalNode = null;
  19372. /**
  19373. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  19374. * and `sheenColorMap` properties. This node property allows to overwrite the default
  19375. * and define the sheen with a node instead.
  19376. *
  19377. * If you don't want to overwrite the sheen but modify the existing
  19378. * value instead, use {@link materialSheen}.
  19379. *
  19380. * @type {?Node<vec3>}
  19381. * @default null
  19382. */
  19383. this.sheenNode = null;
  19384. /**
  19385. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  19386. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  19387. * and define the sheen roughness with a node instead.
  19388. *
  19389. * If you don't want to overwrite the sheen roughness but modify the existing
  19390. * value instead, use {@link materialSheenRoughness}.
  19391. *
  19392. * @type {?Node<float>}
  19393. * @default null
  19394. */
  19395. this.sheenRoughnessNode = null;
  19396. /**
  19397. * The iridescence of physical materials is by default inferred from the `iridescence`
  19398. * property. This node property allows to overwrite the default
  19399. * and define the iridescence with a node instead.
  19400. *
  19401. * If you don't want to overwrite the iridescence but modify the existing
  19402. * value instead, use {@link materialIridescence}.
  19403. *
  19404. * @type {?Node<float>}
  19405. * @default null
  19406. */
  19407. this.iridescenceNode = null;
  19408. /**
  19409. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  19410. * property. This node property allows to overwrite the default
  19411. * and define the iridescence IOR with a node instead.
  19412. *
  19413. * If you don't want to overwrite the iridescence IOR but modify the existing
  19414. * value instead, use {@link materialIridescenceIOR}.
  19415. *
  19416. * @type {?Node<float>}
  19417. * @default null
  19418. */
  19419. this.iridescenceIORNode = null;
  19420. /**
  19421. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  19422. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  19423. * and define the iridescence thickness with a node instead.
  19424. *
  19425. * If you don't want to overwrite the iridescence thickness but modify the existing
  19426. * value instead, use {@link materialIridescenceThickness}.
  19427. *
  19428. * @type {?Node<float>}
  19429. * @default null
  19430. */
  19431. this.iridescenceThicknessNode = null;
  19432. /**
  19433. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  19434. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  19435. * and define the specular intensity with a node instead.
  19436. *
  19437. * If you don't want to overwrite the specular intensity but modify the existing
  19438. * value instead, use {@link materialSpecularIntensity}.
  19439. *
  19440. * @type {?Node<float>}
  19441. * @default null
  19442. */
  19443. this.specularIntensityNode = null;
  19444. /**
  19445. * The specular color of physical materials is by default inferred from the `specularColor`
  19446. * and `specularColorMap` properties. This node property allows to overwrite the default
  19447. * and define the specular color with a node instead.
  19448. *
  19449. * If you don't want to overwrite the specular color but modify the existing
  19450. * value instead, use {@link materialSpecularColor}.
  19451. *
  19452. * @type {?Node<vec3>}
  19453. * @default null
  19454. */
  19455. this.specularColorNode = null;
  19456. /**
  19457. * The ior of physical materials is by default inferred from the `ior`
  19458. * property. This node property allows to overwrite the default
  19459. * and define the ior with a node instead.
  19460. *
  19461. * If you don't want to overwrite the ior but modify the existing
  19462. * value instead, use {@link materialIOR}.
  19463. *
  19464. * @type {?Node<float>}
  19465. * @default null
  19466. */
  19467. this.iorNode = null;
  19468. /**
  19469. * The transmission of physical materials is by default inferred from the `transmission` and
  19470. * `transmissionMap` properties. This node property allows to overwrite the default
  19471. * and define the transmission with a node instead.
  19472. *
  19473. * If you don't want to overwrite the transmission but modify the existing
  19474. * value instead, use {@link materialTransmission}.
  19475. *
  19476. * @type {?Node<float>}
  19477. * @default null
  19478. */
  19479. this.transmissionNode = null;
  19480. /**
  19481. * The thickness of physical materials is by default inferred from the `thickness` and
  19482. * `thicknessMap` properties. This node property allows to overwrite the default
  19483. * and define the thickness with a node instead.
  19484. *
  19485. * If you don't want to overwrite the thickness but modify the existing
  19486. * value instead, use {@link materialThickness}.
  19487. *
  19488. * @type {?Node<float>}
  19489. * @default null
  19490. */
  19491. this.thicknessNode = null;
  19492. /**
  19493. * The attenuation distance of physical materials is by default inferred from the
  19494. * `attenuationDistance` property. This node property allows to overwrite the default
  19495. * and define the attenuation distance with a node instead.
  19496. *
  19497. * If you don't want to overwrite the attenuation distance but modify the existing
  19498. * value instead, use {@link materialAttenuationDistance}.
  19499. *
  19500. * @type {?Node<float>}
  19501. * @default null
  19502. */
  19503. this.attenuationDistanceNode = null;
  19504. /**
  19505. * The attenuation color of physical materials is by default inferred from the
  19506. * `attenuationColor` property. This node property allows to overwrite the default
  19507. * and define the attenuation color with a node instead.
  19508. *
  19509. * If you don't want to overwrite the attenuation color but modify the existing
  19510. * value instead, use {@link materialAttenuationColor}.
  19511. *
  19512. * @type {?Node<vec3>}
  19513. * @default null
  19514. */
  19515. this.attenuationColorNode = null;
  19516. /**
  19517. * The dispersion of physical materials is by default inferred from the
  19518. * `dispersion` property. This node property allows to overwrite the default
  19519. * and define the dispersion with a node instead.
  19520. *
  19521. * If you don't want to overwrite the dispersion but modify the existing
  19522. * value instead, use {@link materialDispersion}.
  19523. *
  19524. * @type {?Node<float>}
  19525. * @default null
  19526. */
  19527. this.dispersionNode = null;
  19528. /**
  19529. * The anisotropy of physical materials is by default inferred from the
  19530. * `anisotropy` property. This node property allows to overwrite the default
  19531. * and define the anisotropy with a node instead.
  19532. *
  19533. * If you don't want to overwrite the anisotropy but modify the existing
  19534. * value instead, use {@link materialAnisotropy}.
  19535. *
  19536. * @type {?Node<float>}
  19537. * @default null
  19538. */
  19539. this.anisotropyNode = null;
  19540. this.setDefaultValues( _defaultValues$5 );
  19541. this.setValues( parameters );
  19542. }
  19543. /**
  19544. * Whether the lighting model should use clearcoat or not.
  19545. *
  19546. * @type {boolean}
  19547. * @default true
  19548. */
  19549. get useClearcoat() {
  19550. return this.clearcoat > 0 || this.clearcoatNode !== null;
  19551. }
  19552. /**
  19553. * Whether the lighting model should use iridescence or not.
  19554. *
  19555. * @type {boolean}
  19556. * @default true
  19557. */
  19558. get useIridescence() {
  19559. return this.iridescence > 0 || this.iridescenceNode !== null;
  19560. }
  19561. /**
  19562. * Whether the lighting model should use sheen or not.
  19563. *
  19564. * @type {boolean}
  19565. * @default true
  19566. */
  19567. get useSheen() {
  19568. return this.sheen > 0 || this.sheenNode !== null;
  19569. }
  19570. /**
  19571. * Whether the lighting model should use anisotropy or not.
  19572. *
  19573. * @type {boolean}
  19574. * @default true
  19575. */
  19576. get useAnisotropy() {
  19577. return this.anisotropy > 0 || this.anisotropyNode !== null;
  19578. }
  19579. /**
  19580. * Whether the lighting model should use transmission or not.
  19581. *
  19582. * @type {boolean}
  19583. * @default true
  19584. */
  19585. get useTransmission() {
  19586. return this.transmission > 0 || this.transmissionNode !== null;
  19587. }
  19588. /**
  19589. * Whether the lighting model should use dispersion or not.
  19590. *
  19591. * @type {boolean}
  19592. * @default true
  19593. */
  19594. get useDispersion() {
  19595. return this.dispersion > 0 || this.dispersionNode !== null;
  19596. }
  19597. /**
  19598. * Setups the specular related node variables.
  19599. */
  19600. setupSpecular() {
  19601. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  19602. ior.assign( iorNode );
  19603. specularColor.assign( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ) );
  19604. specularColorBlended.assign( mix( specularColor, diffuseColor.rgb, metalness ) );
  19605. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  19606. }
  19607. /**
  19608. * Setups the lighting model.
  19609. *
  19610. * @return {PhysicalLightingModel} The lighting model.
  19611. */
  19612. setupLightingModel( /*builder*/ ) {
  19613. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  19614. }
  19615. /**
  19616. * Setups the physical specific node variables.
  19617. *
  19618. * @param {NodeBuilder} builder - The current node builder.
  19619. */
  19620. setupVariants( builder ) {
  19621. super.setupVariants( builder );
  19622. // CLEARCOAT
  19623. if ( this.useClearcoat ) {
  19624. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  19625. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  19626. clearcoat.assign( clearcoatNode );
  19627. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  19628. }
  19629. // SHEEN
  19630. if ( this.useSheen ) {
  19631. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  19632. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  19633. sheen.assign( sheenNode );
  19634. sheenRoughness.assign( sheenRoughnessNode );
  19635. }
  19636. // IRIDESCENCE
  19637. if ( this.useIridescence ) {
  19638. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  19639. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  19640. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  19641. iridescence.assign( iridescenceNode );
  19642. iridescenceIOR.assign( iridescenceIORNode );
  19643. iridescenceThickness.assign( iridescenceThicknessNode );
  19644. }
  19645. // ANISOTROPY
  19646. if ( this.useAnisotropy ) {
  19647. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  19648. anisotropy.assign( anisotropyV.length() );
  19649. If( anisotropy.equal( 0.0 ), () => {
  19650. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  19651. } ).Else( () => {
  19652. anisotropyV.divAssign( vec2( anisotropy ) );
  19653. anisotropy.assign( anisotropy.saturate() );
  19654. } );
  19655. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  19656. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  19657. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  19658. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  19659. }
  19660. // TRANSMISSION
  19661. if ( this.useTransmission ) {
  19662. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  19663. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  19664. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  19665. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  19666. transmission.assign( transmissionNode );
  19667. thickness.assign( thicknessNode );
  19668. attenuationDistance.assign( attenuationDistanceNode );
  19669. attenuationColor.assign( attenuationColorNode );
  19670. if ( this.useDispersion ) {
  19671. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  19672. dispersion.assign( dispersionNode );
  19673. }
  19674. }
  19675. }
  19676. /**
  19677. * Setups the clearcoat normal node.
  19678. *
  19679. * @return {Node<vec3>} The clearcoat normal.
  19680. */
  19681. setupClearcoatNormal() {
  19682. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  19683. }
  19684. setup( builder ) {
  19685. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  19686. super.setup( builder );
  19687. }
  19688. copy( source ) {
  19689. this.clearcoatNode = source.clearcoatNode;
  19690. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  19691. this.clearcoatNormalNode = source.clearcoatNormalNode;
  19692. this.sheenNode = source.sheenNode;
  19693. this.sheenRoughnessNode = source.sheenRoughnessNode;
  19694. this.iridescenceNode = source.iridescenceNode;
  19695. this.iridescenceIORNode = source.iridescenceIORNode;
  19696. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  19697. this.specularIntensityNode = source.specularIntensityNode;
  19698. this.specularColorNode = source.specularColorNode;
  19699. this.iorNode = source.iorNode;
  19700. this.transmissionNode = source.transmissionNode;
  19701. this.thicknessNode = source.thicknessNode;
  19702. this.attenuationDistanceNode = source.attenuationDistanceNode;
  19703. this.attenuationColorNode = source.attenuationColorNode;
  19704. this.dispersionNode = source.dispersionNode;
  19705. this.anisotropyNode = source.anisotropyNode;
  19706. return super.copy( source );
  19707. }
  19708. }
  19709. /**
  19710. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  19711. *
  19712. * @augments PhysicalLightingModel
  19713. */
  19714. class SSSLightingModel extends PhysicalLightingModel {
  19715. /**
  19716. * Constructs a new physical lighting model.
  19717. *
  19718. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  19719. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  19720. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  19721. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  19722. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  19723. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  19724. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  19725. */
  19726. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  19727. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  19728. /**
  19729. * Whether the lighting model should use SSS or not.
  19730. *
  19731. * @type {boolean}
  19732. * @default false
  19733. */
  19734. this.useSSS = sss;
  19735. }
  19736. /**
  19737. * Extends the default implementation with a SSS term.
  19738. *
  19739. * Reference: [Approximating Translucency for a Fast, Cheap and Convincing Subsurface Scattering Look](https://colinbarrebrisebois.com/2011/03/07/gdc-2011-approximating-translucency-for-a-fast-cheap-and-convincing-subsurface-scattering-look/)
  19740. *
  19741. * @param {Object} input - The input data.
  19742. * @param {NodeBuilder} builder - The current node builder.
  19743. */
  19744. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19745. if ( this.useSSS === true ) {
  19746. const material = builder.material;
  19747. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  19748. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  19749. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  19750. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  19751. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  19752. }
  19753. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  19754. }
  19755. }
  19756. /**
  19757. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  19758. * that implements a Subsurface scattering (SSS) term.
  19759. *
  19760. * @augments MeshPhysicalNodeMaterial
  19761. */
  19762. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  19763. static get type() {
  19764. return 'MeshSSSNodeMaterial';
  19765. }
  19766. /**
  19767. * Constructs a new mesh SSS node material.
  19768. *
  19769. * @param {Object} [parameters] - The configuration parameter.
  19770. */
  19771. constructor( parameters ) {
  19772. super( parameters );
  19773. /**
  19774. * Represents the thickness color.
  19775. *
  19776. * @type {?Node<vec3>}
  19777. * @default null
  19778. */
  19779. this.thicknessColorNode = null;
  19780. /**
  19781. * Represents the distortion factor.
  19782. *
  19783. * @type {?Node<float>}
  19784. */
  19785. this.thicknessDistortionNode = float( 0.1 );
  19786. /**
  19787. * Represents the thickness ambient factor.
  19788. *
  19789. * @type {?Node<float>}
  19790. */
  19791. this.thicknessAmbientNode = float( 0.0 );
  19792. /**
  19793. * Represents the thickness attenuation.
  19794. *
  19795. * @type {?Node<float>}
  19796. */
  19797. this.thicknessAttenuationNode = float( .1 );
  19798. /**
  19799. * Represents the thickness power.
  19800. *
  19801. * @type {?Node<float>}
  19802. */
  19803. this.thicknessPowerNode = float( 2.0 );
  19804. /**
  19805. * Represents the thickness scale.
  19806. *
  19807. * @type {?Node<float>}
  19808. */
  19809. this.thicknessScaleNode = float( 10.0 );
  19810. }
  19811. /**
  19812. * Whether the lighting model should use SSS or not.
  19813. *
  19814. * @type {boolean}
  19815. * @default true
  19816. */
  19817. get useSSS() {
  19818. return this.thicknessColorNode !== null;
  19819. }
  19820. /**
  19821. * Setups the lighting model.
  19822. *
  19823. * @return {SSSLightingModel} The lighting model.
  19824. */
  19825. setupLightingModel( /*builder*/ ) {
  19826. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  19827. }
  19828. copy( source ) {
  19829. this.thicknessColorNode = source.thicknessColorNode;
  19830. this.thicknessDistortionNode = source.thicknessDistortionNode;
  19831. this.thicknessAmbientNode = source.thicknessAmbientNode;
  19832. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  19833. this.thicknessPowerNode = source.thicknessPowerNode;
  19834. this.thicknessScaleNode = source.thicknessScaleNode;
  19835. return super.copy( source );
  19836. }
  19837. }
  19838. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  19839. // dotNL will be from -1.0 to 1.0
  19840. const dotNL = normal.dot( lightDirection );
  19841. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  19842. if ( builder.material.gradientMap ) {
  19843. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  19844. return vec3( gradientMap.r );
  19845. } else {
  19846. const fw = coord.fwidth().mul( 0.5 );
  19847. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  19848. }
  19849. } );
  19850. /**
  19851. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  19852. *
  19853. * @augments LightingModel
  19854. */
  19855. class ToonLightingModel extends LightingModel {
  19856. /**
  19857. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  19858. * reduced to a small number of discrete shades to create a comic-like, flat look.
  19859. *
  19860. * @param {Object} lightData - The light data.
  19861. * @param {NodeBuilder} builder - The current node builder.
  19862. */
  19863. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19864. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  19865. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  19866. }
  19867. /**
  19868. * Implements the indirect lighting.
  19869. *
  19870. * @param {NodeBuilder} builder - The current node builder.
  19871. */
  19872. indirect( builder ) {
  19873. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  19874. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  19875. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  19876. }
  19877. }
  19878. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  19879. /**
  19880. * Node material version of {@link MeshToonMaterial}.
  19881. *
  19882. * @augments NodeMaterial
  19883. */
  19884. class MeshToonNodeMaterial extends NodeMaterial {
  19885. static get type() {
  19886. return 'MeshToonNodeMaterial';
  19887. }
  19888. /**
  19889. * Constructs a new mesh toon node material.
  19890. *
  19891. * @param {Object} [parameters] - The configuration parameter.
  19892. */
  19893. constructor( parameters ) {
  19894. super();
  19895. /**
  19896. * This flag can be used for type testing.
  19897. *
  19898. * @type {boolean}
  19899. * @readonly
  19900. * @default true
  19901. */
  19902. this.isMeshToonNodeMaterial = true;
  19903. /**
  19904. * Set to `true` because toon materials react on lights.
  19905. *
  19906. * @type {boolean}
  19907. * @default true
  19908. */
  19909. this.lights = true;
  19910. this.setDefaultValues( _defaultValues$4 );
  19911. this.setValues( parameters );
  19912. }
  19913. /**
  19914. * Setups the lighting model.
  19915. *
  19916. * @return {ToonLightingModel} The lighting model.
  19917. */
  19918. setupLightingModel( /*builder*/ ) {
  19919. return new ToonLightingModel();
  19920. }
  19921. }
  19922. /**
  19923. * TSL function for creating a matcap uv node.
  19924. *
  19925. * Can be used to compute texture coordinates for projecting a
  19926. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  19927. *
  19928. * @tsl
  19929. * @function
  19930. * @returns {Node<vec2>} The matcap UV coordinates.
  19931. */
  19932. const matcapUV = /*@__PURE__*/ Fn( () => {
  19933. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  19934. const y = positionViewDirection.cross( x );
  19935. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  19936. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  19937. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  19938. /**
  19939. * Node material version of {@link MeshMatcapMaterial}.
  19940. *
  19941. * @augments NodeMaterial
  19942. */
  19943. class MeshMatcapNodeMaterial extends NodeMaterial {
  19944. static get type() {
  19945. return 'MeshMatcapNodeMaterial';
  19946. }
  19947. /**
  19948. * Constructs a new mesh normal node material.
  19949. *
  19950. * @param {Object} [parameters] - The configuration parameter.
  19951. */
  19952. constructor( parameters ) {
  19953. super();
  19954. /**
  19955. * This flag can be used for type testing.
  19956. *
  19957. * @type {boolean}
  19958. * @readonly
  19959. * @default true
  19960. */
  19961. this.isMeshMatcapNodeMaterial = true;
  19962. this.setDefaultValues( _defaultValues$3 );
  19963. this.setValues( parameters );
  19964. }
  19965. /**
  19966. * Setups the matcap specific node variables.
  19967. *
  19968. * @param {NodeBuilder} builder - The current node builder.
  19969. */
  19970. setupVariants( builder ) {
  19971. const uv = matcapUV;
  19972. let matcapColor;
  19973. if ( builder.material.matcap ) {
  19974. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  19975. } else {
  19976. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  19977. }
  19978. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  19979. }
  19980. }
  19981. /**
  19982. * Applies a rotation to the given position node.
  19983. *
  19984. * @augments TempNode
  19985. */
  19986. class RotateNode extends TempNode {
  19987. static get type() {
  19988. return 'RotateNode';
  19989. }
  19990. /**
  19991. * Constructs a new rotate node.
  19992. *
  19993. * @param {Node} positionNode - The position node.
  19994. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19995. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19996. */
  19997. constructor( positionNode, rotationNode ) {
  19998. super();
  19999. /**
  20000. * The position node.
  20001. *
  20002. * @type {Node}
  20003. */
  20004. this.positionNode = positionNode;
  20005. /**
  20006. * Represents the rotation that is applied to the position node.
  20007. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  20008. *
  20009. * @type {Node}
  20010. */
  20011. this.rotationNode = rotationNode;
  20012. }
  20013. /**
  20014. * The type of the {@link RotateNode#positionNode} defines the node's type.
  20015. *
  20016. * @param {NodeBuilder} builder - The current node builder.
  20017. * @return {string} The node's type.
  20018. */
  20019. generateNodeType( builder ) {
  20020. return this.positionNode.getNodeType( builder );
  20021. }
  20022. setup( builder ) {
  20023. const { rotationNode, positionNode } = this;
  20024. const nodeType = this.getNodeType( builder );
  20025. if ( nodeType === 'vec2' ) {
  20026. const cosAngle = rotationNode.cos();
  20027. const sinAngle = rotationNode.sin();
  20028. const rotationMatrix = mat2(
  20029. cosAngle, sinAngle,
  20030. sinAngle.negate(), cosAngle
  20031. );
  20032. return rotationMatrix.mul( positionNode );
  20033. } else {
  20034. const rotation = rotationNode;
  20035. 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 ) );
  20036. 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 ) );
  20037. 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 ) );
  20038. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  20039. }
  20040. }
  20041. }
  20042. /**
  20043. * TSL function for creating a rotate node.
  20044. *
  20045. * @tsl
  20046. * @function
  20047. * @param {Node} positionNode - The position node.
  20048. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  20049. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  20050. * @returns {RotateNode}
  20051. */
  20052. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  20053. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  20054. /**
  20055. * Node material version of {@link SpriteMaterial}.
  20056. *
  20057. * @augments NodeMaterial
  20058. */
  20059. class SpriteNodeMaterial extends NodeMaterial {
  20060. static get type() {
  20061. return 'SpriteNodeMaterial';
  20062. }
  20063. /**
  20064. * Constructs a new sprite node material.
  20065. *
  20066. * @param {Object} [parameters] - The configuration parameter.
  20067. */
  20068. constructor( parameters ) {
  20069. super();
  20070. /**
  20071. * This flag can be used for type testing.
  20072. *
  20073. * @type {boolean}
  20074. * @readonly
  20075. * @default true
  20076. */
  20077. this.isSpriteNodeMaterial = true;
  20078. this._useSizeAttenuation = true;
  20079. /**
  20080. * This property makes it possible to define the position of the sprite with a
  20081. * node. That can be useful when the material is used with instanced rendering
  20082. * and node data are defined with an instanced attribute node:
  20083. * ```js
  20084. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  20085. * material.positionNode = instancedBufferAttribute( positionAttribute );
  20086. * ```
  20087. * Another possibility is to compute the instanced data with a compute shader:
  20088. * ```js
  20089. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  20090. * particleMaterial.positionNode = positionBuffer.toAttribute();
  20091. * ```
  20092. *
  20093. * @type {?Node<vec2>}
  20094. * @default null
  20095. */
  20096. this.positionNode = null;
  20097. /**
  20098. * The rotation of sprite materials is by default inferred from the `rotation`,
  20099. * property. This node property allows to overwrite the default and define
  20100. * the rotation with a node instead.
  20101. *
  20102. * If you don't want to overwrite the rotation but modify the existing
  20103. * value instead, use {@link materialRotation}.
  20104. *
  20105. * @type {?Node<float>}
  20106. * @default null
  20107. */
  20108. this.rotationNode = null;
  20109. /**
  20110. * This node property provides an additional way to scale sprites next to
  20111. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  20112. * is multiplied with the scale value of this node in the vertex shader.
  20113. *
  20114. * @type {?Node<vec2>}
  20115. * @default null
  20116. */
  20117. this.scaleNode = null;
  20118. /**
  20119. * In Sprites, the transparent property is enabled by default.
  20120. *
  20121. * @type {boolean}
  20122. * @default true
  20123. */
  20124. this.transparent = true;
  20125. this.setDefaultValues( _defaultValues$2 );
  20126. this.setValues( parameters );
  20127. }
  20128. /**
  20129. * Setups the position node in view space. This method implements
  20130. * the sprite specific vertex shader.
  20131. *
  20132. * @param {NodeBuilder} builder - The current node builder.
  20133. * @return {Node<vec3>} The position in view space.
  20134. */
  20135. setupPositionView( builder ) {
  20136. const { object, camera } = builder;
  20137. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  20138. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  20139. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  20140. if ( scaleNode !== null ) {
  20141. scale = scale.mul( vec2( scaleNode ) );
  20142. }
  20143. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  20144. scale = scale.mul( mvPosition.z.negate() );
  20145. }
  20146. let alignedPosition = positionGeometry.xy;
  20147. if ( object.center && object.center.isVector2 === true ) {
  20148. const center = reference$1( 'center', 'vec2', object );
  20149. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  20150. }
  20151. alignedPosition = alignedPosition.mul( scale );
  20152. const rotation = float( rotationNode || materialRotation );
  20153. const rotatedPosition = rotate( alignedPosition, rotation );
  20154. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  20155. }
  20156. copy( source ) {
  20157. this.positionNode = source.positionNode;
  20158. this.rotationNode = source.rotationNode;
  20159. this.scaleNode = source.scaleNode;
  20160. return super.copy( source );
  20161. }
  20162. /**
  20163. * Whether to use size attenuation or not.
  20164. *
  20165. * @type {boolean}
  20166. * @default true
  20167. */
  20168. get sizeAttenuation() {
  20169. return this._useSizeAttenuation;
  20170. }
  20171. set sizeAttenuation( value ) {
  20172. if ( this._useSizeAttenuation !== value ) {
  20173. this._useSizeAttenuation = value;
  20174. this.needsUpdate = true;
  20175. }
  20176. }
  20177. }
  20178. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  20179. const _size$4 = /*@__PURE__*/ new Vector2();
  20180. /**
  20181. * Node material version of {@link PointsMaterial}.
  20182. *
  20183. * This material can be used in two ways:
  20184. *
  20185. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  20186. * with a pixel size of `1`, it's not possible to define a size.
  20187. *
  20188. * ```js
  20189. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  20190. * ```
  20191. *
  20192. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  20193. * see {@link PointsNodeMaterial#sizeNode}.
  20194. *
  20195. * ```js
  20196. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  20197. * ```
  20198. *
  20199. * @augments SpriteNodeMaterial
  20200. */
  20201. class PointsNodeMaterial extends SpriteNodeMaterial {
  20202. static get type() {
  20203. return 'PointsNodeMaterial';
  20204. }
  20205. /**
  20206. * Constructs a new points node material.
  20207. *
  20208. * @param {Object} [parameters] - The configuration parameter.
  20209. */
  20210. constructor( parameters ) {
  20211. super();
  20212. /**
  20213. * This node property provides an additional way to set the point size.
  20214. *
  20215. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  20216. * this node has no effect when the material is used with {@link Points} and a WebGPU
  20217. * backend. If an application wants to render points with a size larger than 1 pixel,
  20218. * the material should be used with {@link Sprite} and instancing.
  20219. *
  20220. * @type {?Node<vec2>}
  20221. * @default null
  20222. */
  20223. this.sizeNode = null;
  20224. /**
  20225. * This flag can be used for type testing.
  20226. *
  20227. * @type {boolean}
  20228. * @readonly
  20229. * @default true
  20230. */
  20231. this.isPointsNodeMaterial = true;
  20232. this.setDefaultValues( _defaultValues$1 );
  20233. this.setValues( parameters );
  20234. }
  20235. setupPositionView() {
  20236. const { positionNode } = this;
  20237. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  20238. }
  20239. setupVertexSprite( builder ) {
  20240. const { material, camera } = builder;
  20241. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  20242. let mvp = super.setupVertex( builder );
  20243. // skip further processing if the material is not a node material
  20244. if ( material.isNodeMaterial !== true ) {
  20245. return mvp;
  20246. }
  20247. // point size
  20248. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  20249. pointSize = pointSize.mul( screenDPR );
  20250. // size attenuation
  20251. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  20252. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  20253. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  20254. }
  20255. // scale
  20256. if ( scaleNode && scaleNode.isNode ) {
  20257. pointSize = pointSize.mul( vec2( scaleNode ) );
  20258. }
  20259. // compute offset
  20260. let offset = positionGeometry.xy;
  20261. // apply rotation
  20262. if ( rotationNode && rotationNode.isNode ) {
  20263. const rotation = float( rotationNode );
  20264. offset = rotate( offset, rotation );
  20265. }
  20266. // account for point size
  20267. offset = offset.mul( pointSize );
  20268. // scale by viewport size
  20269. offset = offset.div( viewportSize.div( 2 ) );
  20270. // compensate for the perspective divide
  20271. offset = offset.mul( mvp.w );
  20272. // add offset
  20273. mvp = mvp.add( vec4( offset, 0, 0 ) );
  20274. return mvp;
  20275. }
  20276. setupVertex( builder ) {
  20277. if ( builder.object.isPoints ) {
  20278. return super.setupVertex( builder );
  20279. } else {
  20280. return this.setupVertexSprite( builder );
  20281. }
  20282. }
  20283. /**
  20284. * Whether alpha to coverage should be used or not.
  20285. *
  20286. * @type {boolean}
  20287. * @default true
  20288. */
  20289. get alphaToCoverage() {
  20290. return this._useAlphaToCoverage;
  20291. }
  20292. set alphaToCoverage( value ) {
  20293. if ( this._useAlphaToCoverage !== value ) {
  20294. this._useAlphaToCoverage = value;
  20295. this.needsUpdate = true;
  20296. }
  20297. }
  20298. }
  20299. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  20300. const size = renderer.getSize( _size$4 ); // logical units
  20301. this.value = 0.5 * size.y;
  20302. } );
  20303. /**
  20304. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  20305. *
  20306. * @augments LightingModel
  20307. */
  20308. class ShadowMaskModel extends LightingModel {
  20309. /**
  20310. * Constructs a new shadow mask model.
  20311. */
  20312. constructor() {
  20313. super();
  20314. /**
  20315. * The shadow mask node.
  20316. *
  20317. * @type {Node}
  20318. */
  20319. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  20320. }
  20321. /**
  20322. * Only used to save the shadow mask.
  20323. *
  20324. * @param {Object} input - The input data.
  20325. */
  20326. direct( { lightNode } ) {
  20327. if ( lightNode.shadowNode !== null ) {
  20328. this.shadowNode.mulAssign( lightNode.shadowNode );
  20329. }
  20330. }
  20331. /**
  20332. * Uses the shadow mask to produce the final color.
  20333. *
  20334. * @param {NodeBuilder} builder - The current node builder.
  20335. */
  20336. finish( { context } ) {
  20337. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  20338. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  20339. }
  20340. }
  20341. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  20342. /**
  20343. * Node material version of {@link ShadowMaterial}.
  20344. *
  20345. * @augments NodeMaterial
  20346. */
  20347. class ShadowNodeMaterial extends NodeMaterial {
  20348. static get type() {
  20349. return 'ShadowNodeMaterial';
  20350. }
  20351. /**
  20352. * Constructs a new shadow node material.
  20353. *
  20354. * @param {Object} [parameters] - The configuration parameter.
  20355. */
  20356. constructor( parameters ) {
  20357. super();
  20358. /**
  20359. * This flag can be used for type testing.
  20360. *
  20361. * @type {boolean}
  20362. * @readonly
  20363. * @default true
  20364. */
  20365. this.isShadowNodeMaterial = true;
  20366. /**
  20367. * Set to `true` because so it's possible to implement
  20368. * the shadow mask effect.
  20369. *
  20370. * @type {boolean}
  20371. * @default true
  20372. */
  20373. this.lights = true;
  20374. /**
  20375. * Overwritten since shadow materials are transparent
  20376. * by default.
  20377. *
  20378. * @type {boolean}
  20379. * @default true
  20380. */
  20381. this.transparent = true;
  20382. this.setDefaultValues( _defaultValues );
  20383. this.setValues( parameters );
  20384. }
  20385. /**
  20386. * Setups the lighting model.
  20387. *
  20388. * @return {ShadowMaskModel} The lighting model.
  20389. */
  20390. setupLightingModel( /*builder*/ ) {
  20391. return new ShadowMaskModel();
  20392. }
  20393. }
  20394. const scatteringDensity = property( 'vec3' );
  20395. const linearDepthRay = property( 'vec3' );
  20396. const outgoingRayLight = property( 'vec3' );
  20397. /**
  20398. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  20399. * This model calculates the scattering and transmittance of light through a volumetric medium.
  20400. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  20401. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  20402. *
  20403. * @augments LightingModel
  20404. */
  20405. class VolumetricLightingModel extends LightingModel {
  20406. constructor() {
  20407. super();
  20408. }
  20409. start( builder ) {
  20410. const { material } = builder;
  20411. const startPos = property( 'vec3' );
  20412. const endPos = property( 'vec3' );
  20413. // This approach dynamically changes the direction of the ray,
  20414. // 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.
  20415. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  20416. startPos.assign( cameraPosition );
  20417. endPos.assign( positionWorld );
  20418. } ).Else( () => {
  20419. startPos.assign( positionWorld );
  20420. endPos.assign( cameraPosition );
  20421. } );
  20422. //
  20423. const viewVector = endPos.sub( startPos );
  20424. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  20425. const stepSize = viewVector.length().div( steps ).toVar();
  20426. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  20427. const distTravelled = float( 0.0 ).toVar();
  20428. const transmittance = vec3( 1 ).toVar();
  20429. if ( material.offsetNode ) {
  20430. // reduce banding
  20431. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  20432. }
  20433. Loop( steps, () => {
  20434. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  20435. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  20436. if ( material.depthNode !== null ) {
  20437. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  20438. builder.context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  20439. }
  20440. builder.context.positionWorld = positionRay;
  20441. builder.context.shadowPositionWorld = positionRay;
  20442. builder.context.positionView = positionViewRay;
  20443. scatteringDensity.assign( 0 );
  20444. let scatteringNode;
  20445. if ( material.scatteringNode ) {
  20446. scatteringNode = material.scatteringNode( {
  20447. positionRay
  20448. } );
  20449. }
  20450. super.start( builder );
  20451. if ( scatteringNode ) {
  20452. scatteringDensity.mulAssign( scatteringNode );
  20453. }
  20454. // beer's law
  20455. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  20456. transmittance.mulAssign( falloff );
  20457. // move along the ray
  20458. distTravelled.addAssign( stepSize );
  20459. } );
  20460. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  20461. }
  20462. scatteringLight( lightColor, builder ) {
  20463. const sceneDepthNode = builder.context.sceneDepthNode;
  20464. if ( sceneDepthNode ) {
  20465. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  20466. scatteringDensity.addAssign( lightColor );
  20467. } );
  20468. } else {
  20469. scatteringDensity.addAssign( lightColor );
  20470. }
  20471. }
  20472. direct( { lightNode, lightColor }, builder ) {
  20473. // Ignore lights with infinite distance
  20474. if ( lightNode.light.distance === undefined ) return;
  20475. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  20476. const directLight = lightColor.xyz.toVar();
  20477. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  20478. this.scatteringLight( directLight, builder );
  20479. }
  20480. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  20481. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  20482. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  20483. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  20484. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  20485. const P = builder.context.positionView;
  20486. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  20487. this.scatteringLight( directLight, builder );
  20488. }
  20489. finish( builder ) {
  20490. builder.context.outgoingLight.assign( outgoingRayLight );
  20491. }
  20492. }
  20493. /**
  20494. * Volume node material.
  20495. *
  20496. * @augments NodeMaterial
  20497. */
  20498. class VolumeNodeMaterial extends NodeMaterial {
  20499. static get type() {
  20500. return 'VolumeNodeMaterial';
  20501. }
  20502. /**
  20503. * Constructs a new volume node material.
  20504. *
  20505. * @param {Object} [parameters] - The configuration parameter.
  20506. */
  20507. constructor( parameters ) {
  20508. super();
  20509. /**
  20510. * This flag can be used for type testing.
  20511. *
  20512. * @type {boolean}
  20513. * @readonly
  20514. * @default true
  20515. */
  20516. this.isVolumeNodeMaterial = true;
  20517. /**
  20518. * Number of steps used for raymarching.
  20519. *
  20520. * @type {number}
  20521. * @default 25
  20522. */
  20523. this.steps = 25;
  20524. /**
  20525. * Offsets the distance a ray has been traveled through a volume.
  20526. * Can be used to implement dithering to reduce banding.
  20527. *
  20528. * @type {Node<float>}
  20529. * @default null
  20530. */
  20531. this.offsetNode = null;
  20532. /**
  20533. * Node used for scattering calculations.
  20534. *
  20535. * @type {Function|FunctionNode<vec4>}
  20536. * @default null
  20537. */
  20538. this.scatteringNode = null;
  20539. this.lights = true;
  20540. this.transparent = true;
  20541. this.side = BackSide;
  20542. this.depthTest = false;
  20543. this.depthWrite = false;
  20544. this.setValues( parameters );
  20545. }
  20546. setupLightingModel() {
  20547. return new VolumetricLightingModel();
  20548. }
  20549. }
  20550. /**
  20551. * This module manages the internal animation loop of the renderer.
  20552. *
  20553. * @private
  20554. */
  20555. class Animation {
  20556. /**
  20557. * Constructs a new animation loop management component.
  20558. *
  20559. * @param {Renderer} renderer - A reference to the main renderer.
  20560. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  20561. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20562. */
  20563. constructor( renderer, nodes, info ) {
  20564. /**
  20565. * A reference to the main renderer.
  20566. *
  20567. * @type {Renderer}
  20568. */
  20569. this.renderer = renderer;
  20570. /**
  20571. * Renderer component for managing nodes related logic.
  20572. *
  20573. * @type {NodeManager}
  20574. */
  20575. this.nodes = nodes;
  20576. /**
  20577. * Renderer component for managing metrics and monitoring data.
  20578. *
  20579. * @type {Info}
  20580. */
  20581. this.info = info;
  20582. /**
  20583. * A reference to the context from `requestAnimationFrame()` can
  20584. * be called (usually `window`).
  20585. *
  20586. * @type {?(Window|XRSession)}
  20587. */
  20588. this._context = typeof self !== 'undefined' ? self : null;
  20589. /**
  20590. * The user-defined animation loop.
  20591. *
  20592. * @type {?Function}
  20593. * @default null
  20594. */
  20595. this._animationLoop = null;
  20596. /**
  20597. * The requestId which is returned from the `requestAnimationFrame()` call.
  20598. * Can be used to cancel the stop the animation loop.
  20599. *
  20600. * @type {?number}
  20601. * @default null
  20602. */
  20603. this._requestId = null;
  20604. }
  20605. /**
  20606. * Starts the internal animation loop.
  20607. */
  20608. start() {
  20609. const update = ( time, xrFrame ) => {
  20610. this._requestId = this._context.requestAnimationFrame( update );
  20611. if ( this.info.autoReset === true ) this.info.reset();
  20612. this.nodes.nodeFrame.update();
  20613. this.info.frame = this.nodes.nodeFrame.frameId;
  20614. this.renderer._inspector.begin();
  20615. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  20616. this.renderer._inspector.finish();
  20617. };
  20618. update();
  20619. }
  20620. /**
  20621. * Stops the internal animation loop.
  20622. */
  20623. stop() {
  20624. if ( this._context !== null ) this._context.cancelAnimationFrame( this._requestId );
  20625. this._requestId = null;
  20626. }
  20627. /**
  20628. * Returns the user-level animation loop.
  20629. *
  20630. * @return {?Function} The animation loop.
  20631. */
  20632. getAnimationLoop() {
  20633. return this._animationLoop;
  20634. }
  20635. /**
  20636. * Defines the user-level animation loop.
  20637. *
  20638. * @param {?Function} callback - The animation loop.
  20639. */
  20640. setAnimationLoop( callback ) {
  20641. this._animationLoop = callback;
  20642. }
  20643. /**
  20644. * Returns the animation context.
  20645. *
  20646. * @return {Window|XRSession} The animation context.
  20647. */
  20648. getContext() {
  20649. return this._context;
  20650. }
  20651. /**
  20652. * Defines the context in which `requestAnimationFrame()` is executed.
  20653. *
  20654. * @param {Window|XRSession} context - The context to set.
  20655. */
  20656. setContext( context ) {
  20657. this._context = context;
  20658. }
  20659. /**
  20660. * Frees all internal resources and stops the animation loop.
  20661. */
  20662. dispose() {
  20663. this.stop();
  20664. }
  20665. }
  20666. /**
  20667. * Data structure for the renderer. It allows defining values
  20668. * with chained, hierarchical keys. Keys are meant to be
  20669. * objects since the module internally works with Weak Maps
  20670. * for performance reasons.
  20671. *
  20672. * @private
  20673. */
  20674. class ChainMap {
  20675. /**
  20676. * Constructs a new Chain Map.
  20677. */
  20678. constructor() {
  20679. /**
  20680. * A map of Weak Maps by their key length.
  20681. *
  20682. * @type {Object<number, WeakMap>}
  20683. */
  20684. this.weakMaps = {};
  20685. }
  20686. /**
  20687. * Returns the Weak Map for the given keys.
  20688. *
  20689. * @param {Array<Object>} keys - List of keys.
  20690. * @return {WeakMap} The weak map.
  20691. */
  20692. _getWeakMap( keys ) {
  20693. const length = keys.length;
  20694. let weakMap = this.weakMaps[ length ];
  20695. if ( weakMap === undefined ) {
  20696. weakMap = new WeakMap();
  20697. this.weakMaps[ length ] = weakMap;
  20698. }
  20699. return weakMap;
  20700. }
  20701. /**
  20702. * Returns the value for the given array of keys.
  20703. *
  20704. * @param {Array<Object>} keys - List of keys.
  20705. * @return {any} The value. Returns `undefined` if no value was found.
  20706. */
  20707. get( keys ) {
  20708. let map = this._getWeakMap( keys );
  20709. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20710. map = map.get( keys[ i ] );
  20711. if ( map === undefined ) return undefined;
  20712. }
  20713. return map.get( keys[ keys.length - 1 ] );
  20714. }
  20715. /**
  20716. * Sets the value for the given keys.
  20717. *
  20718. * @param {Array<Object>} keys - List of keys.
  20719. * @param {any} value - The value to set.
  20720. * @return {ChainMap} A reference to this Chain Map.
  20721. */
  20722. set( keys, value ) {
  20723. let map = this._getWeakMap( keys );
  20724. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20725. const key = keys[ i ];
  20726. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  20727. map = map.get( key );
  20728. }
  20729. map.set( keys[ keys.length - 1 ], value );
  20730. return this;
  20731. }
  20732. /**
  20733. * Deletes a value for the given keys.
  20734. *
  20735. * @param {Array<Object>} keys - The keys.
  20736. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  20737. */
  20738. delete( keys ) {
  20739. let map = this._getWeakMap( keys );
  20740. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20741. map = map.get( keys[ i ] );
  20742. if ( map === undefined ) return false;
  20743. }
  20744. return map.delete( keys[ keys.length - 1 ] );
  20745. }
  20746. }
  20747. let _id$a = 0;
  20748. function getKeys( obj ) {
  20749. const keys = Object.keys( obj );
  20750. let proto = Object.getPrototypeOf( obj );
  20751. while ( proto ) {
  20752. const descriptors = Object.getOwnPropertyDescriptors( proto );
  20753. for ( const key in descriptors ) {
  20754. if ( descriptors[ key ] !== undefined ) {
  20755. const descriptor = descriptors[ key ];
  20756. if ( descriptor && typeof descriptor.get === 'function' ) {
  20757. keys.push( key );
  20758. }
  20759. }
  20760. }
  20761. proto = Object.getPrototypeOf( proto );
  20762. }
  20763. return keys;
  20764. }
  20765. /**
  20766. * A render object is the renderer's representation of single entity that gets drawn
  20767. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  20768. * scene since render objects also depend from the used material, the current render context
  20769. * and the current scene's lighting.
  20770. *
  20771. * In general, the basic process of the renderer is:
  20772. *
  20773. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  20774. * - Process the render lists by calling one or more render commands for each render item.
  20775. * - For each render command, request a render object and perform the draw.
  20776. *
  20777. * The module provides an interface to get data required for the draw command like the actual
  20778. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  20779. * creating render objects should only be done when necessary.
  20780. *
  20781. * @private
  20782. */
  20783. class RenderObject {
  20784. /**
  20785. * Constructs a new render object.
  20786. *
  20787. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  20788. * @param {Geometries} geometries - Renderer component for managing geometries.
  20789. * @param {Renderer} renderer - The renderer.
  20790. * @param {Object3D} object - The 3D object.
  20791. * @param {Material} material - The 3D object's material.
  20792. * @param {Scene} scene - The scene the 3D object belongs to.
  20793. * @param {Camera} camera - The camera the object should be rendered with.
  20794. * @param {LightsNode} lightsNode - The lights node.
  20795. * @param {RenderContext} renderContext - The render context.
  20796. * @param {ClippingContext} clippingContext - The clipping context.
  20797. */
  20798. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  20799. this.id = _id$a ++;
  20800. /**
  20801. * Renderer component for managing nodes related logic.
  20802. *
  20803. * @type {NodeManager}
  20804. * @private
  20805. */
  20806. this._nodes = nodes;
  20807. /**
  20808. * Renderer component for managing geometries.
  20809. *
  20810. * @type {Geometries}
  20811. * @private
  20812. */
  20813. this._geometries = geometries;
  20814. /**
  20815. * The renderer.
  20816. *
  20817. * @type {Renderer}
  20818. */
  20819. this.renderer = renderer;
  20820. /**
  20821. * The 3D object.
  20822. *
  20823. * @type {Object3D}
  20824. */
  20825. this.object = object;
  20826. /**
  20827. * The 3D object's material.
  20828. *
  20829. * @type {Material}
  20830. */
  20831. this.material = material;
  20832. /**
  20833. * The scene the 3D object belongs to.
  20834. *
  20835. * @type {Scene}
  20836. */
  20837. this.scene = scene;
  20838. /**
  20839. * The camera the 3D object should be rendered with.
  20840. *
  20841. * @type {Camera}
  20842. */
  20843. this.camera = camera;
  20844. /**
  20845. * The lights node.
  20846. *
  20847. * @type {LightsNode}
  20848. */
  20849. this.lightsNode = lightsNode;
  20850. /**
  20851. * The render context.
  20852. *
  20853. * @type {RenderContext}
  20854. */
  20855. this.context = renderContext;
  20856. /**
  20857. * The 3D object's geometry.
  20858. *
  20859. * @type {BufferGeometry}
  20860. */
  20861. this.geometry = object.geometry;
  20862. /**
  20863. * The render object's version.
  20864. *
  20865. * @type {number}
  20866. */
  20867. this.version = material.version;
  20868. /**
  20869. * The draw range of the geometry.
  20870. *
  20871. * @type {?Object}
  20872. * @default null
  20873. */
  20874. this.drawRange = null;
  20875. /**
  20876. * An array holding the buffer attributes
  20877. * of the render object. This entails attribute
  20878. * definitions on geometry and node level.
  20879. *
  20880. * @type {?Array<BufferAttribute>}
  20881. * @default null
  20882. */
  20883. this.attributes = null;
  20884. /**
  20885. * An object holding the version of the
  20886. * attributes. The keys are the attribute names
  20887. * and the values are the attribute versions.
  20888. *
  20889. * @type {?Object<string, number>}
  20890. * @default null
  20891. */
  20892. this.attributesId = null;
  20893. /**
  20894. * A reference to a render pipeline the render
  20895. * object is processed with.
  20896. *
  20897. * @type {RenderPipeline}
  20898. * @default null
  20899. */
  20900. this.pipeline = null;
  20901. /**
  20902. * Only relevant for objects using
  20903. * multiple materials. This represents a group entry
  20904. * from the respective `BufferGeometry`.
  20905. *
  20906. * @type {?{start: number, count: number}}
  20907. * @default null
  20908. */
  20909. this.group = null;
  20910. /**
  20911. * An array holding the vertex buffers which can
  20912. * be buffer attributes but also interleaved buffers.
  20913. *
  20914. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  20915. * @default null
  20916. */
  20917. this.vertexBuffers = null;
  20918. /**
  20919. * The parameters for the draw command.
  20920. *
  20921. * @type {?Object}
  20922. * @default null
  20923. */
  20924. this.drawParams = null;
  20925. /**
  20926. * If this render object is used inside a render bundle,
  20927. * this property points to the respective bundle group.
  20928. *
  20929. * @type {?BundleGroup}
  20930. * @default null
  20931. */
  20932. this.bundle = null;
  20933. /**
  20934. * The clipping context.
  20935. *
  20936. * @type {ClippingContext}
  20937. */
  20938. this.clippingContext = clippingContext;
  20939. /**
  20940. * The clipping context's cache key.
  20941. *
  20942. * @type {string}
  20943. */
  20944. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  20945. /**
  20946. * The initial node cache key.
  20947. *
  20948. * @type {number}
  20949. */
  20950. this.initialNodesCacheKey = this.getDynamicCacheKey();
  20951. /**
  20952. * The initial cache key.
  20953. *
  20954. * @type {number}
  20955. */
  20956. this.initialCacheKey = this.getCacheKey();
  20957. /**
  20958. * The node builder state.
  20959. *
  20960. * @type {?NodeBuilderState}
  20961. * @private
  20962. * @default null
  20963. */
  20964. this._nodeBuilderState = null;
  20965. /**
  20966. * An array of bindings.
  20967. *
  20968. * @type {?Array<BindGroup>}
  20969. * @private
  20970. * @default null
  20971. */
  20972. this._bindings = null;
  20973. /**
  20974. * Reference to the node material observer.
  20975. *
  20976. * @type {?NodeMaterialObserver}
  20977. * @private
  20978. * @default null
  20979. */
  20980. this._monitor = null;
  20981. /**
  20982. * An event listener which is defined by `RenderObjects`. It performs
  20983. * clean up tasks when `dispose()` on this render object.
  20984. *
  20985. * @method
  20986. */
  20987. this.onDispose = null;
  20988. /**
  20989. * This flag can be used for type testing.
  20990. *
  20991. * @type {boolean}
  20992. * @readonly
  20993. * @default true
  20994. */
  20995. this.isRenderObject = true;
  20996. /**
  20997. * An event listener which is executed when `dispose()` is called on
  20998. * the material of this render object.
  20999. *
  21000. * @method
  21001. */
  21002. this.onMaterialDispose = () => {
  21003. this.dispose();
  21004. };
  21005. /**
  21006. * An event listener which is executed when `dispose()` is called on
  21007. * the geometry of this render object.
  21008. *
  21009. * @method
  21010. */
  21011. this.onGeometryDispose = () => {
  21012. // clear geometry cache attributes
  21013. this.attributes = null;
  21014. this.attributesId = null;
  21015. };
  21016. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  21017. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  21018. }
  21019. /**
  21020. * Updates the clipping context.
  21021. *
  21022. * @param {ClippingContext} context - The clipping context to set.
  21023. */
  21024. updateClipping( context ) {
  21025. this.clippingContext = context;
  21026. }
  21027. /**
  21028. * Whether the clipping requires an update or not.
  21029. *
  21030. * @type {boolean}
  21031. * @readonly
  21032. */
  21033. get clippingNeedsUpdate() {
  21034. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  21035. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  21036. return true;
  21037. }
  21038. /**
  21039. * The number of clipping planes defined in context of hardware clipping.
  21040. *
  21041. * @type {number}
  21042. * @readonly
  21043. */
  21044. get hardwareClippingPlanes() {
  21045. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  21046. }
  21047. /**
  21048. * Returns the node builder state of this render object.
  21049. *
  21050. * @return {NodeBuilderState} The node builder state.
  21051. */
  21052. getNodeBuilderState() {
  21053. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  21054. }
  21055. /**
  21056. * Returns the node material observer of this render object.
  21057. *
  21058. * @return {NodeMaterialObserver} The node material observer.
  21059. */
  21060. getMonitor() {
  21061. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  21062. }
  21063. /**
  21064. * Returns an array of bind groups of this render object.
  21065. *
  21066. * @return {Array<BindGroup>} The bindings.
  21067. */
  21068. getBindings() {
  21069. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  21070. }
  21071. /**
  21072. * Returns a binding group by group name of this render object.
  21073. *
  21074. * @param {string} name - The name of the binding group.
  21075. * @return {?BindGroup} The bindings.
  21076. */
  21077. getBindingGroup( name ) {
  21078. for ( const bindingGroup of this.getBindings() ) {
  21079. if ( bindingGroup.name === name ) {
  21080. return bindingGroup;
  21081. }
  21082. }
  21083. }
  21084. /**
  21085. * Returns the index of the render object's geometry.
  21086. *
  21087. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21088. */
  21089. getIndex() {
  21090. return this._geometries.getIndex( this );
  21091. }
  21092. /**
  21093. * Returns the indirect buffer attribute.
  21094. *
  21095. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21096. */
  21097. getIndirect() {
  21098. return this._geometries.getIndirect( this );
  21099. }
  21100. /**
  21101. * Returns the byte offset into the indirect attribute buffer.
  21102. *
  21103. * @return {number|Array<number>} The byte offset into the indirect attribute buffer.
  21104. */
  21105. getIndirectOffset() {
  21106. return this._geometries.getIndirectOffset( this );
  21107. }
  21108. /**
  21109. * Returns an array that acts as a key for identifying the render object in a chain map.
  21110. *
  21111. * @return {Array<Object>} An array with object references.
  21112. */
  21113. getChainArray() {
  21114. return [ this.object, this.material, this.context, this.lightsNode ];
  21115. }
  21116. /**
  21117. * This method is used when the geometry of a 3D object has been exchanged and the
  21118. * respective render object now requires an update.
  21119. *
  21120. * @param {BufferGeometry} geometry - The geometry to set.
  21121. */
  21122. setGeometry( geometry ) {
  21123. this.geometry = geometry;
  21124. this.attributes = null;
  21125. this.attributesId = null;
  21126. }
  21127. /**
  21128. * Returns the buffer attributes of the render object. The returned array holds
  21129. * attribute definitions on geometry and node level.
  21130. *
  21131. * @return {Array<BufferAttribute>} An array with buffer attributes.
  21132. */
  21133. getAttributes() {
  21134. if ( this.attributes !== null ) return this.attributes;
  21135. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  21136. const geometry = this.geometry;
  21137. const attributes = [];
  21138. const vertexBuffers = new Set();
  21139. const attributesId = {};
  21140. for ( const nodeAttribute of nodeAttributes ) {
  21141. let attribute;
  21142. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  21143. // node attribute
  21144. attribute = nodeAttribute.node.attribute;
  21145. } else {
  21146. // geometry attribute
  21147. attribute = geometry.getAttribute( nodeAttribute.name );
  21148. attributesId[ nodeAttribute.name ] = attribute.id;
  21149. }
  21150. if ( attribute === undefined ) continue;
  21151. attributes.push( attribute );
  21152. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  21153. vertexBuffers.add( bufferAttribute );
  21154. }
  21155. this.attributes = attributes;
  21156. this.attributesId = attributesId;
  21157. this.vertexBuffers = Array.from( vertexBuffers.values() );
  21158. return attributes;
  21159. }
  21160. /**
  21161. * Returns the vertex buffers of the render object.
  21162. *
  21163. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  21164. */
  21165. getVertexBuffers() {
  21166. if ( this.vertexBuffers === null ) this.getAttributes();
  21167. return this.vertexBuffers;
  21168. }
  21169. /**
  21170. * Returns the draw parameters for the render object.
  21171. *
  21172. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  21173. */
  21174. getDrawParameters() {
  21175. const { object, material, geometry, group, drawRange } = this;
  21176. const drawParams = this.drawParams || ( this.drawParams = {
  21177. vertexCount: 0,
  21178. firstVertex: 0,
  21179. instanceCount: 0,
  21180. firstInstance: 0
  21181. } );
  21182. const index = this.getIndex();
  21183. const hasIndex = ( index !== null );
  21184. let instanceCount = 1;
  21185. if ( geometry.isInstancedBufferGeometry === true ) {
  21186. instanceCount = geometry.instanceCount;
  21187. } else if ( object.count !== undefined ) {
  21188. instanceCount = Math.max( 0, object.count );
  21189. }
  21190. if ( instanceCount === 0 ) return null;
  21191. drawParams.instanceCount = instanceCount;
  21192. if ( object.isBatchedMesh === true ) return drawParams;
  21193. let rangeFactor = 1;
  21194. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  21195. rangeFactor = 2;
  21196. }
  21197. let firstVertex = drawRange.start * rangeFactor;
  21198. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  21199. if ( group !== null ) {
  21200. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  21201. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  21202. }
  21203. const position = geometry.attributes.position;
  21204. let itemCount = Infinity;
  21205. if ( hasIndex ) {
  21206. itemCount = index.count;
  21207. } else if ( position !== undefined && position !== null ) {
  21208. itemCount = position.count;
  21209. }
  21210. firstVertex = Math.max( firstVertex, 0 );
  21211. lastVertex = Math.min( lastVertex, itemCount );
  21212. const count = lastVertex - firstVertex;
  21213. if ( count < 0 || count === Infinity ) return null;
  21214. drawParams.vertexCount = count;
  21215. drawParams.firstVertex = firstVertex;
  21216. return drawParams;
  21217. }
  21218. /**
  21219. * Returns the render object's geometry cache key.
  21220. *
  21221. * The geometry cache key is part of the material cache key.
  21222. *
  21223. * @return {string} The geometry cache key.
  21224. */
  21225. getGeometryCacheKey() {
  21226. const { geometry } = this;
  21227. let cacheKey = '';
  21228. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  21229. const attribute = geometry.attributes[ name ];
  21230. cacheKey += name + ',';
  21231. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  21232. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  21233. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  21234. if ( attribute.normalized ) cacheKey += 'n,';
  21235. }
  21236. // structural equality isn't sufficient for morph targets since the
  21237. // data are maintained in textures. only if the targets are all equal
  21238. // the texture and thus the instance of `MorphNode` can be shared.
  21239. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  21240. const targets = geometry.morphAttributes[ name ];
  21241. cacheKey += 'morph-' + name + ',';
  21242. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  21243. const attribute = targets[ i ];
  21244. cacheKey += attribute.id + ',';
  21245. }
  21246. }
  21247. if ( geometry.index ) {
  21248. cacheKey += 'index,';
  21249. }
  21250. return cacheKey;
  21251. }
  21252. /**
  21253. * Returns the render object's material cache key.
  21254. *
  21255. * The material cache key is part of the render object cache key.
  21256. *
  21257. * @return {number} The material cache key.
  21258. */
  21259. getMaterialCacheKey() {
  21260. const { object, material, renderer } = this;
  21261. let cacheKey = material.customProgramCacheKey();
  21262. for ( const property of getKeys( material ) ) {
  21263. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  21264. const value = material[ property ];
  21265. let valueKey;
  21266. if ( value !== null ) {
  21267. // some material values require a formatting
  21268. const type = typeof value;
  21269. if ( type === 'number' ) {
  21270. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  21271. } else if ( type === 'object' ) {
  21272. valueKey = '{';
  21273. if ( value.isTexture ) {
  21274. valueKey += value.mapping;
  21275. // WebGPU must honor the sampler data because they are part of the bindings
  21276. if ( renderer.backend.isWebGPUBackend === true ) {
  21277. valueKey += value.magFilter;
  21278. valueKey += value.minFilter;
  21279. valueKey += value.wrapS;
  21280. valueKey += value.wrapT;
  21281. valueKey += value.wrapR;
  21282. }
  21283. }
  21284. valueKey += '}';
  21285. } else {
  21286. valueKey = String( value );
  21287. }
  21288. } else {
  21289. valueKey = String( value );
  21290. }
  21291. cacheKey += /*property + ':' +*/ valueKey + ',';
  21292. }
  21293. cacheKey += this.clippingContextCacheKey + ',';
  21294. if ( object.geometry ) {
  21295. cacheKey += this.getGeometryCacheKey();
  21296. }
  21297. if ( object.skeleton ) {
  21298. cacheKey += object.skeleton.bones.length + ',';
  21299. }
  21300. if ( object.isBatchedMesh ) {
  21301. cacheKey += object._matricesTexture.uuid + ',';
  21302. if ( object._colorsTexture !== null ) {
  21303. cacheKey += object._colorsTexture.uuid + ',';
  21304. }
  21305. }
  21306. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  21307. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  21308. cacheKey += object.uuid + ',';
  21309. }
  21310. cacheKey += this.context.id + ',';
  21311. cacheKey += object.receiveShadow + ',';
  21312. return hashString( cacheKey );
  21313. }
  21314. /**
  21315. * Whether the geometry requires an update or not.
  21316. *
  21317. * @type {boolean}
  21318. * @readonly
  21319. */
  21320. get needsGeometryUpdate() {
  21321. if ( this.geometry.id !== this.object.geometry.id ) return true;
  21322. if ( this.attributes !== null ) {
  21323. const attributesId = this.attributesId;
  21324. for ( const name in attributesId ) {
  21325. const attribute = this.geometry.getAttribute( name );
  21326. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  21327. return true;
  21328. }
  21329. }
  21330. }
  21331. return false;
  21332. }
  21333. /**
  21334. * Whether the render object requires an update or not.
  21335. *
  21336. * Note: There are two distinct places where render objects are checked for an update.
  21337. *
  21338. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  21339. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  21340. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  21341. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  21342. * a need for a refresh due to material, geometry or object related value changes.
  21343. *
  21344. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  21345. * that performs the 'needsUpdate' check.
  21346. *
  21347. * @type {boolean}
  21348. * @readonly
  21349. */
  21350. get needsUpdate() {
  21351. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  21352. }
  21353. /**
  21354. * Returns the dynamic cache key which represents a key that is computed per draw command.
  21355. *
  21356. * @return {number} The cache key.
  21357. */
  21358. getDynamicCacheKey() {
  21359. let cacheKey = 0;
  21360. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  21361. // the renderer is inside a shadow pass.
  21362. if ( this.material.isShadowPassMaterial !== true ) {
  21363. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  21364. }
  21365. if ( this.camera.isArrayCamera ) {
  21366. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  21367. }
  21368. if ( this.object.receiveShadow ) {
  21369. cacheKey = hash$1( cacheKey, 1 );
  21370. }
  21371. cacheKey = hash$1( cacheKey, this.renderer.contextNode.id, this.renderer.contextNode.version );
  21372. return cacheKey;
  21373. }
  21374. /**
  21375. * Returns the render object's cache key.
  21376. *
  21377. * @return {number} The cache key.
  21378. */
  21379. getCacheKey() {
  21380. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  21381. }
  21382. /**
  21383. * Frees internal resources.
  21384. */
  21385. dispose() {
  21386. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  21387. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  21388. this.onDispose();
  21389. }
  21390. }
  21391. const _chainKeys$3 = [];
  21392. /**
  21393. * This module manages the render objects of the renderer.
  21394. *
  21395. * @private
  21396. */
  21397. class RenderObjects {
  21398. /**
  21399. * Constructs a new render object management component.
  21400. *
  21401. * @param {Renderer} renderer - The renderer.
  21402. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  21403. * @param {Geometries} geometries - Renderer component for managing geometries.
  21404. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  21405. * @param {Bindings} bindings - Renderer component for managing bindings.
  21406. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21407. */
  21408. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  21409. /**
  21410. * The renderer.
  21411. *
  21412. * @type {Renderer}
  21413. */
  21414. this.renderer = renderer;
  21415. /**
  21416. * Renderer component for managing nodes related logic.
  21417. *
  21418. * @type {NodeManager}
  21419. */
  21420. this.nodes = nodes;
  21421. /**
  21422. * Renderer component for managing geometries.
  21423. *
  21424. * @type {Geometries}
  21425. */
  21426. this.geometries = geometries;
  21427. /**
  21428. * Renderer component for managing pipelines.
  21429. *
  21430. * @type {Pipelines}
  21431. */
  21432. this.pipelines = pipelines;
  21433. /**
  21434. * Renderer component for managing bindings.
  21435. *
  21436. * @type {Bindings}
  21437. */
  21438. this.bindings = bindings;
  21439. /**
  21440. * Renderer component for managing metrics and monitoring data.
  21441. *
  21442. * @type {Info}
  21443. */
  21444. this.info = info;
  21445. /**
  21446. * A dictionary that manages render contexts in chain maps
  21447. * for each pass ID.
  21448. *
  21449. * @type {Object<string,ChainMap>}
  21450. */
  21451. this.chainMaps = {};
  21452. }
  21453. /**
  21454. * Returns a render object for the given object and state data.
  21455. *
  21456. * @param {Object3D} object - The 3D object.
  21457. * @param {Material} material - The 3D object's material.
  21458. * @param {Scene} scene - The scene the 3D object belongs to.
  21459. * @param {Camera} camera - The camera the 3D object should be rendered with.
  21460. * @param {LightsNode} lightsNode - The lights node.
  21461. * @param {RenderContext} renderContext - The render context.
  21462. * @param {ClippingContext} clippingContext - The clipping context.
  21463. * @param {string} [passId] - An optional ID for identifying the pass.
  21464. * @return {RenderObject} The render object.
  21465. */
  21466. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21467. const chainMap = this.getChainMap( passId );
  21468. // set chain keys
  21469. _chainKeys$3[ 0 ] = object;
  21470. _chainKeys$3[ 1 ] = material;
  21471. _chainKeys$3[ 2 ] = renderContext;
  21472. _chainKeys$3[ 3 ] = lightsNode;
  21473. //
  21474. let renderObject = chainMap.get( _chainKeys$3 );
  21475. if ( renderObject === undefined ) {
  21476. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21477. chainMap.set( _chainKeys$3, renderObject );
  21478. } else {
  21479. // update references
  21480. renderObject.camera = camera;
  21481. //
  21482. renderObject.updateClipping( clippingContext );
  21483. if ( renderObject.needsGeometryUpdate ) {
  21484. renderObject.setGeometry( object.geometry );
  21485. }
  21486. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21487. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21488. renderObject.dispose();
  21489. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21490. } else {
  21491. renderObject.version = material.version;
  21492. }
  21493. }
  21494. }
  21495. // reset chain array
  21496. _chainKeys$3[ 0 ] = null;
  21497. _chainKeys$3[ 1 ] = null;
  21498. _chainKeys$3[ 2 ] = null;
  21499. _chainKeys$3[ 3 ] = null;
  21500. //
  21501. return renderObject;
  21502. }
  21503. /**
  21504. * Returns a chain map for the given pass ID.
  21505. *
  21506. * @param {string} [passId='default'] - The pass ID.
  21507. * @return {ChainMap} The chain map.
  21508. */
  21509. getChainMap( passId = 'default' ) {
  21510. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21511. }
  21512. /**
  21513. * Frees internal resources.
  21514. */
  21515. dispose() {
  21516. this.chainMaps = {};
  21517. }
  21518. /**
  21519. * Factory method for creating render objects with the given list of parameters.
  21520. *
  21521. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  21522. * @param {Geometries} geometries - Renderer component for managing geometries.
  21523. * @param {Renderer} renderer - The renderer.
  21524. * @param {Object3D} object - The 3D object.
  21525. * @param {Material} material - The object's material.
  21526. * @param {Scene} scene - The scene the 3D object belongs to.
  21527. * @param {Camera} camera - The camera the object should be rendered with.
  21528. * @param {LightsNode} lightsNode - The lights node.
  21529. * @param {RenderContext} renderContext - The render context.
  21530. * @param {ClippingContext} clippingContext - The clipping context.
  21531. * @param {string} [passId] - An optional ID for identifying the pass.
  21532. * @return {RenderObject} The render object.
  21533. */
  21534. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21535. const chainMap = this.getChainMap( passId );
  21536. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  21537. renderObject.onDispose = () => {
  21538. this.pipelines.delete( renderObject );
  21539. this.bindings.deleteForRender( renderObject );
  21540. this.nodes.delete( renderObject );
  21541. chainMap.delete( renderObject.getChainArray() );
  21542. };
  21543. return renderObject;
  21544. }
  21545. }
  21546. /**
  21547. * Data structure for the renderer. It is intended to manage
  21548. * data of objects in dictionaries.
  21549. *
  21550. * @private
  21551. */
  21552. class DataMap {
  21553. /**
  21554. * Constructs a new data map.
  21555. */
  21556. constructor() {
  21557. /**
  21558. * `DataMap` internally uses a weak map
  21559. * to manage its data.
  21560. *
  21561. * @type {WeakMap<Object, Object>}
  21562. */
  21563. this.data = new WeakMap();
  21564. }
  21565. /**
  21566. * Returns the dictionary for the given object.
  21567. *
  21568. * @param {Object} object - The object.
  21569. * @return {Object} The dictionary.
  21570. */
  21571. get( object ) {
  21572. let map = this.data.get( object );
  21573. if ( map === undefined ) {
  21574. map = {};
  21575. this.data.set( object, map );
  21576. }
  21577. return map;
  21578. }
  21579. /**
  21580. * Deletes the dictionary for the given object.
  21581. *
  21582. * @param {Object} object - The object.
  21583. * @return {?Object} The deleted dictionary.
  21584. */
  21585. delete( object ) {
  21586. let map = null;
  21587. if ( this.data.has( object ) ) {
  21588. map = this.data.get( object );
  21589. this.data.delete( object );
  21590. }
  21591. return map;
  21592. }
  21593. /**
  21594. * Returns `true` if the given object has a dictionary defined.
  21595. *
  21596. * @param {Object} object - The object to test.
  21597. * @return {boolean} Whether a dictionary is defined or not.
  21598. */
  21599. has( object ) {
  21600. return this.data.has( object );
  21601. }
  21602. /**
  21603. * Frees internal resources.
  21604. */
  21605. dispose() {
  21606. this.data = new WeakMap();
  21607. }
  21608. }
  21609. const AttributeType = {
  21610. VERTEX: 1,
  21611. INDEX: 2,
  21612. STORAGE: 3,
  21613. INDIRECT: 4
  21614. };
  21615. // size of a chunk in bytes (STD140 layout)
  21616. const GPU_CHUNK_BYTES = 16;
  21617. // @TODO: Move to src/constants.js
  21618. const BlendColorFactor = 211;
  21619. const OneMinusBlendColorFactor = 212;
  21620. /**
  21621. * This renderer module manages geometry attributes.
  21622. *
  21623. * @private
  21624. * @augments DataMap
  21625. */
  21626. class Attributes extends DataMap {
  21627. /**
  21628. * Constructs a new attribute management component.
  21629. *
  21630. * @param {Backend} backend - The renderer's backend.
  21631. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21632. */
  21633. constructor( backend, info ) {
  21634. super();
  21635. /**
  21636. * The renderer's backend.
  21637. *
  21638. * @type {Backend}
  21639. */
  21640. this.backend = backend;
  21641. /**
  21642. * Renderer component for managing metrics and monitoring data.
  21643. *
  21644. * @type {Info}
  21645. */
  21646. this.info = info;
  21647. }
  21648. /**
  21649. * Deletes the data for the given attribute.
  21650. *
  21651. * @param {BufferAttribute} attribute - The attribute.
  21652. * @return {?Object} The deleted attribute data.
  21653. */
  21654. delete( attribute ) {
  21655. const attributeData = super.delete( attribute );
  21656. if ( attributeData !== null ) {
  21657. this.backend.destroyAttribute( attribute );
  21658. this.info.destroyAttribute( attribute );
  21659. }
  21660. return attributeData;
  21661. }
  21662. /**
  21663. * Updates the given attribute. This method creates attribute buffers
  21664. * for new attributes and updates data for existing ones.
  21665. *
  21666. * @param {BufferAttribute} attribute - The attribute to update.
  21667. * @param {number} type - The attribute type.
  21668. */
  21669. update( attribute, type ) {
  21670. const data = this.get( attribute );
  21671. if ( data.version === undefined ) {
  21672. if ( type === AttributeType.VERTEX ) {
  21673. this.backend.createAttribute( attribute );
  21674. this.info.createAttribute( attribute );
  21675. } else if ( type === AttributeType.INDEX ) {
  21676. this.backend.createIndexAttribute( attribute );
  21677. this.info.createIndexAttribute( attribute );
  21678. } else if ( type === AttributeType.STORAGE ) {
  21679. this.backend.createStorageAttribute( attribute );
  21680. this.info.createStorageAttribute( attribute );
  21681. } else if ( type === AttributeType.INDIRECT ) {
  21682. this.backend.createIndirectStorageAttribute( attribute );
  21683. this.info.createIndirectStorageAttribute( attribute );
  21684. }
  21685. data.version = this._getBufferAttribute( attribute ).version;
  21686. } else {
  21687. const bufferAttribute = this._getBufferAttribute( attribute );
  21688. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21689. this.backend.updateAttribute( attribute );
  21690. data.version = bufferAttribute.version;
  21691. }
  21692. }
  21693. }
  21694. /**
  21695. * Utility method for handling interleaved buffer attributes correctly.
  21696. * To process them, their `InterleavedBuffer` is returned.
  21697. *
  21698. * @param {BufferAttribute} attribute - The attribute.
  21699. * @return {BufferAttribute|InterleavedBuffer}
  21700. */
  21701. _getBufferAttribute( attribute ) {
  21702. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21703. return attribute;
  21704. }
  21705. }
  21706. /**
  21707. * Returns the wireframe version for the given geometry.
  21708. *
  21709. * @private
  21710. * @function
  21711. * @param {BufferGeometry} geometry - The geometry.
  21712. * @return {number} The version.
  21713. */
  21714. function getWireframeVersion( geometry ) {
  21715. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21716. }
  21717. /**
  21718. * Returns the wireframe ID for the given geometry.
  21719. *
  21720. * @private
  21721. * @function
  21722. * @param {BufferGeometry} geometry - The geometry.
  21723. * @return {number} The ID.
  21724. */
  21725. function getWireframeId( geometry ) {
  21726. return ( geometry.index !== null ) ? geometry.index.id : geometry.attributes.position.id;
  21727. }
  21728. /**
  21729. * Returns a wireframe index attribute for the given geometry.
  21730. *
  21731. * @private
  21732. * @function
  21733. * @param {BufferGeometry} geometry - The geometry.
  21734. * @return {BufferAttribute} The wireframe index attribute.
  21735. */
  21736. function getWireframeIndex( geometry ) {
  21737. const indices = [];
  21738. const geometryIndex = geometry.index;
  21739. const geometryPosition = geometry.attributes.position;
  21740. if ( geometryIndex !== null ) {
  21741. const array = geometryIndex.array;
  21742. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21743. const a = array[ i + 0 ];
  21744. const b = array[ i + 1 ];
  21745. const c = array[ i + 2 ];
  21746. indices.push( a, b, b, c, c, a );
  21747. }
  21748. } else {
  21749. const array = geometryPosition.array;
  21750. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21751. const a = i + 0;
  21752. const b = i + 1;
  21753. const c = i + 2;
  21754. indices.push( a, b, b, c, c, a );
  21755. }
  21756. }
  21757. const attribute = new ( geometryPosition.count >= 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21758. attribute.version = getWireframeVersion( geometry );
  21759. attribute.__id = getWireframeId( geometry );
  21760. return attribute;
  21761. }
  21762. /**
  21763. * This renderer module manages geometries.
  21764. *
  21765. * @private
  21766. * @augments DataMap
  21767. */
  21768. class Geometries extends DataMap {
  21769. /**
  21770. * Constructs a new geometry management component.
  21771. *
  21772. * @param {Attributes} attributes - Renderer component for managing attributes.
  21773. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21774. */
  21775. constructor( attributes, info ) {
  21776. super();
  21777. /**
  21778. * Renderer component for managing attributes.
  21779. *
  21780. * @type {Attributes}
  21781. */
  21782. this.attributes = attributes;
  21783. /**
  21784. * Renderer component for managing metrics and monitoring data.
  21785. *
  21786. * @type {Info}
  21787. */
  21788. this.info = info;
  21789. /**
  21790. * Weak Map for managing attributes for wireframe rendering.
  21791. *
  21792. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  21793. */
  21794. this.wireframes = new WeakMap();
  21795. /**
  21796. * This Weak Map is used to make sure buffer attributes are
  21797. * updated only once per render call.
  21798. *
  21799. * @type {WeakMap<BufferAttribute,number>}
  21800. */
  21801. this.attributeCall = new WeakMap();
  21802. /**
  21803. * Stores the event listeners attached to geometries.
  21804. *
  21805. * @private
  21806. * @type {Map<BufferGeometry,Function>}
  21807. */
  21808. this._geometryDisposeListeners = new Map();
  21809. }
  21810. /**
  21811. * Returns `true` if the given render object has an initialized geometry.
  21812. *
  21813. * @param {RenderObject} renderObject - The render object.
  21814. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  21815. */
  21816. has( renderObject ) {
  21817. const geometry = renderObject.geometry;
  21818. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21819. }
  21820. /**
  21821. * Prepares the geometry of the given render object for rendering.
  21822. *
  21823. * @param {RenderObject} renderObject - The render object.
  21824. */
  21825. updateForRender( renderObject ) {
  21826. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21827. this.updateAttributes( renderObject );
  21828. }
  21829. /**
  21830. * Initializes the geometry of the given render object.
  21831. *
  21832. * @param {RenderObject} renderObject - The render object.
  21833. */
  21834. initGeometry( renderObject ) {
  21835. const geometry = renderObject.geometry;
  21836. const geometryData = this.get( geometry );
  21837. geometryData.initialized = true;
  21838. this.info.memory.geometries ++;
  21839. const onDispose = () => {
  21840. this.info.memory.geometries --;
  21841. const index = geometry.index;
  21842. const geometryAttributes = renderObject.getAttributes();
  21843. if ( index !== null ) {
  21844. this.attributes.delete( index );
  21845. }
  21846. for ( const geometryAttribute of geometryAttributes ) {
  21847. this.attributes.delete( geometryAttribute );
  21848. }
  21849. const wireframeAttribute = this.wireframes.get( geometry );
  21850. if ( wireframeAttribute !== undefined ) {
  21851. this.attributes.delete( wireframeAttribute );
  21852. }
  21853. geometry.removeEventListener( 'dispose', onDispose );
  21854. this._geometryDisposeListeners.delete( geometry );
  21855. };
  21856. geometry.addEventListener( 'dispose', onDispose );
  21857. // see #31798 why tracking separate remove listeners is required right now
  21858. // TODO: Re-evaluate how onDispose() is managed in this component
  21859. this._geometryDisposeListeners.set( geometry, onDispose );
  21860. }
  21861. /**
  21862. * Updates the geometry attributes of the given render object.
  21863. *
  21864. * @param {RenderObject} renderObject - The render object.
  21865. */
  21866. updateAttributes( renderObject ) {
  21867. // attributes
  21868. const attributes = renderObject.getAttributes();
  21869. for ( const attribute of attributes ) {
  21870. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21871. this.updateAttribute( attribute, AttributeType.STORAGE );
  21872. } else {
  21873. this.updateAttribute( attribute, AttributeType.VERTEX );
  21874. }
  21875. }
  21876. // indexes
  21877. const index = this.getIndex( renderObject );
  21878. if ( index !== null ) {
  21879. this.updateAttribute( index, AttributeType.INDEX );
  21880. }
  21881. // indirect
  21882. const indirect = renderObject.geometry.indirect;
  21883. if ( indirect !== null ) {
  21884. this.updateAttribute( indirect, AttributeType.INDIRECT );
  21885. }
  21886. }
  21887. /**
  21888. * Updates the given attribute.
  21889. *
  21890. * @param {BufferAttribute} attribute - The attribute to update.
  21891. * @param {number} type - The attribute type.
  21892. */
  21893. updateAttribute( attribute, type ) {
  21894. const callId = this.info.render.calls;
  21895. if ( ! attribute.isInterleavedBufferAttribute ) {
  21896. if ( this.attributeCall.get( attribute ) !== callId ) {
  21897. this.attributes.update( attribute, type );
  21898. this.attributeCall.set( attribute, callId );
  21899. }
  21900. } else {
  21901. if ( this.attributeCall.get( attribute ) === undefined ) {
  21902. this.attributes.update( attribute, type );
  21903. this.attributeCall.set( attribute, callId );
  21904. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21905. this.attributes.update( attribute, type );
  21906. this.attributeCall.set( attribute.data, callId );
  21907. this.attributeCall.set( attribute, callId );
  21908. }
  21909. }
  21910. }
  21911. /**
  21912. * Returns the indirect buffer attribute of the given render object.
  21913. *
  21914. * @param {RenderObject} renderObject - The render object.
  21915. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21916. */
  21917. getIndirect( renderObject ) {
  21918. return renderObject.geometry.indirect;
  21919. }
  21920. /**
  21921. * Returns the byte offset into the indirect attribute buffer of the given render object.
  21922. *
  21923. * @param {RenderObject} renderObject - The render object.
  21924. * @return {number} The byte offset into the indirect attribute buffer.
  21925. */
  21926. getIndirectOffset( renderObject ) {
  21927. return renderObject.geometry.indirectOffset;
  21928. }
  21929. /**
  21930. * Returns the index of the given render object's geometry. This is implemented
  21931. * in a method to return a wireframe index if necessary.
  21932. *
  21933. * @param {RenderObject} renderObject - The render object.
  21934. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21935. */
  21936. getIndex( renderObject ) {
  21937. const { geometry, material } = renderObject;
  21938. let index = geometry.index;
  21939. if ( material.wireframe === true ) {
  21940. const wireframes = this.wireframes;
  21941. let wireframeAttribute = wireframes.get( geometry );
  21942. if ( wireframeAttribute === undefined ) {
  21943. wireframeAttribute = getWireframeIndex( geometry );
  21944. wireframes.set( geometry, wireframeAttribute );
  21945. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) || wireframeAttribute.__id !== getWireframeId( geometry ) ) {
  21946. this.attributes.delete( wireframeAttribute );
  21947. wireframeAttribute = getWireframeIndex( geometry );
  21948. wireframes.set( geometry, wireframeAttribute );
  21949. }
  21950. index = wireframeAttribute;
  21951. }
  21952. return index;
  21953. }
  21954. dispose() {
  21955. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  21956. geometry.removeEventListener( 'dispose', onDispose );
  21957. }
  21958. this._geometryDisposeListeners.clear();
  21959. }
  21960. }
  21961. /**
  21962. * This renderer module provides a series of statistical information
  21963. * about the GPU memory and the rendering process. Useful for debugging
  21964. * and monitoring.
  21965. */
  21966. class Info {
  21967. /**
  21968. * Constructs a new info component.
  21969. */
  21970. constructor() {
  21971. /**
  21972. * Whether frame related metrics should automatically
  21973. * be resetted or not. This property should be set to `false`
  21974. * by apps which manage their own animation loop. They must
  21975. * then call `renderer.info.reset()` once per frame manually.
  21976. *
  21977. * @type {boolean}
  21978. * @default true
  21979. */
  21980. this.autoReset = true;
  21981. /**
  21982. * The current frame ID. This ID is managed
  21983. * by `NodeFrame`.
  21984. *
  21985. * @type {number}
  21986. * @readonly
  21987. * @default 0
  21988. */
  21989. this.frame = 0;
  21990. /**
  21991. * The number of render calls since the
  21992. * app has been started.
  21993. *
  21994. * @type {number}
  21995. * @readonly
  21996. * @default 0
  21997. */
  21998. this.calls = 0;
  21999. /**
  22000. * Render related metrics.
  22001. *
  22002. * @type {Object}
  22003. * @readonly
  22004. * @property {number} calls - The number of render calls since the app has been started.
  22005. * @property {number} frameCalls - The number of render calls of the current frame.
  22006. * @property {number} drawCalls - The number of draw calls of the current frame.
  22007. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  22008. * @property {number} points - The number of rendered point primitives of the current frame.
  22009. * @property {number} lines - The number of rendered line primitives of the current frame.
  22010. * @property {number} timestamp - The timestamp of the frame.
  22011. */
  22012. this.render = {
  22013. calls: 0,
  22014. frameCalls: 0,
  22015. drawCalls: 0,
  22016. triangles: 0,
  22017. points: 0,
  22018. lines: 0,
  22019. timestamp: 0,
  22020. };
  22021. /**
  22022. * Compute related metrics.
  22023. *
  22024. * @type {Object}
  22025. * @readonly
  22026. * @property {number} calls - The number of compute calls since the app has been started.
  22027. * @property {number} frameCalls - The number of compute calls of the current frame.
  22028. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  22029. */
  22030. this.compute = {
  22031. calls: 0,
  22032. frameCalls: 0,
  22033. timestamp: 0
  22034. };
  22035. /**
  22036. * Memory related metrics.
  22037. *
  22038. * @type {Object}
  22039. * @readonly
  22040. * @property {number} geometries - The number of active geometries.
  22041. * @property {number} textures - The number of active textures.
  22042. * @property {number} attributes - The number of active attributes.
  22043. * @property {number} indexAttributes - The number of active index attributes.
  22044. * @property {number} storageAttributes - The number of active storage attributes.
  22045. * @property {number} indirectStorageAttributes - The number of active indirect storage attributes.
  22046. * @property {number} programs - The number of active programs.
  22047. * @property {number} renderTargets - The number of active renderTargets.
  22048. * @property {number} total - The total memory size in bytes.
  22049. * @property {number} texturesSize - The memory size of active textures in bytes.
  22050. * @property {number} attributesSize - The memory size of active attributes in bytes.
  22051. * @property {number} indexAttributesSize - The memory size of active index attributes in bytes.
  22052. * @property {number} storageAttributesSize - The memory size of active storage attributes in bytes.
  22053. * @property {number} indirectStorageAttributesSize - The memory size of active indirect storage attributes in bytes.
  22054. * @property {number} programsSize - The memory size of active programs in bytes.
  22055. */
  22056. this.memory = {
  22057. geometries: 0,
  22058. textures: 0,
  22059. attributes: 0,
  22060. indexAttributes: 0,
  22061. storageAttributes: 0,
  22062. indirectStorageAttributes: 0,
  22063. programs: 0,
  22064. renderTargets: 0,
  22065. total: 0,
  22066. texturesSize: 0,
  22067. attributesSize: 0,
  22068. indexAttributesSize: 0,
  22069. storageAttributesSize: 0,
  22070. indirectStorageAttributesSize: 0,
  22071. programsSize: 0
  22072. };
  22073. /**
  22074. * Map for storing calculated byte sizes of tracked objects.
  22075. *
  22076. * @type {Map<Object, number>}
  22077. * @private
  22078. */
  22079. this.memoryMap = new Map();
  22080. }
  22081. /**
  22082. * This method should be executed per draw call and updates the corresponding metrics.
  22083. *
  22084. * @param {Object3D} object - The 3D object that is going to be rendered.
  22085. * @param {number} count - The vertex or index count.
  22086. * @param {number} instanceCount - The instance count.
  22087. */
  22088. update( object, count, instanceCount ) {
  22089. this.render.drawCalls ++;
  22090. if ( object.isMesh || object.isSprite ) {
  22091. this.render.triangles += instanceCount * ( count / 3 );
  22092. } else if ( object.isPoints ) {
  22093. this.render.points += instanceCount * count;
  22094. } else if ( object.isLineSegments ) {
  22095. this.render.lines += instanceCount * ( count / 2 );
  22096. } else if ( object.isLine ) {
  22097. this.render.lines += instanceCount * ( count - 1 );
  22098. } else {
  22099. error( 'WebGPUInfo: Unknown object type.' );
  22100. }
  22101. }
  22102. /**
  22103. * Resets frame related metrics.
  22104. */
  22105. reset() {
  22106. this.render.drawCalls = 0;
  22107. this.render.frameCalls = 0;
  22108. this.compute.frameCalls = 0;
  22109. this.render.triangles = 0;
  22110. this.render.points = 0;
  22111. this.render.lines = 0;
  22112. }
  22113. /**
  22114. * Performs a complete reset of the object.
  22115. */
  22116. dispose() {
  22117. this.reset();
  22118. this.calls = 0;
  22119. this.render.calls = 0;
  22120. this.compute.calls = 0;
  22121. this.render.timestamp = 0;
  22122. this.compute.timestamp = 0;
  22123. for ( const prop in this.memory ) {
  22124. this.memory[ prop ] = 0;
  22125. }
  22126. this.memoryMap.clear();
  22127. }
  22128. /**
  22129. * Tracks texture memory explicitly, updating counts and byte tracking.
  22130. *
  22131. * @param {Texture} texture
  22132. */
  22133. createTexture( texture ) {
  22134. const size = this._getTextureMemorySize( texture );
  22135. this.memoryMap.set( texture, size );
  22136. this.memory.textures ++;
  22137. this.memory.total += size;
  22138. this.memory.texturesSize += size;
  22139. }
  22140. /**
  22141. * Tracks texture memory explicitly, updating counts and byte tracking.
  22142. *
  22143. * @param {Texture} texture
  22144. */
  22145. destroyTexture( texture ) {
  22146. const size = this.memoryMap.get( texture ) || 0;
  22147. this.memoryMap.delete( texture );
  22148. this.memory.textures --;
  22149. this.memory.total -= size;
  22150. this.memory.texturesSize -= size;
  22151. }
  22152. /**
  22153. * Tracks attribute memory explicitly, updating counts and byte tracking.
  22154. *
  22155. * @param {BufferAttribute} attribute
  22156. * @param {string} type - type of attribute
  22157. * @private
  22158. */
  22159. _createAttribute( attribute, type ) {
  22160. const size = this._getAttributeMemorySize( attribute );
  22161. this.memoryMap.set( attribute, { size, type } );
  22162. this.memory[ type ] ++;
  22163. this.memory.total += size;
  22164. this.memory[ type + 'Size' ] += size;
  22165. }
  22166. /**
  22167. * Tracks a regular attribute memory explicitly.
  22168. *
  22169. * @param {BufferAttribute} attribute - The attribute to track.
  22170. */
  22171. createAttribute( attribute ) {
  22172. this._createAttribute( attribute, 'attributes' );
  22173. }
  22174. /**
  22175. * Tracks an index attribute memory explicitly.
  22176. *
  22177. * @param {BufferAttribute} attribute - The index attribute to track.
  22178. */
  22179. createIndexAttribute( attribute ) {
  22180. this._createAttribute( attribute, 'indexAttributes' );
  22181. }
  22182. /**
  22183. * Tracks a storage attribute memory explicitly.
  22184. *
  22185. * @param {BufferAttribute} attribute - The storage attribute to track.
  22186. */
  22187. createStorageAttribute( attribute ) {
  22188. this._createAttribute( attribute, 'storageAttributes' );
  22189. }
  22190. /**
  22191. * Tracks an indirect storage attribute memory explicitly.
  22192. *
  22193. * @param {BufferAttribute} attribute - The indirect storage attribute to track.
  22194. */
  22195. createIndirectStorageAttribute( attribute ) {
  22196. this._createAttribute( attribute, 'indirectStorageAttributes' );
  22197. }
  22198. /**
  22199. * Tracks attribute memory explicitly, updating counts and byte tracking.
  22200. *
  22201. * @param {BufferAttribute} attribute
  22202. */
  22203. destroyAttribute( attribute ) {
  22204. const data = this.memoryMap.get( attribute );
  22205. if ( data ) {
  22206. this.memoryMap.delete( attribute );
  22207. this.memory[ data.type ] --;
  22208. this.memory.total -= data.size;
  22209. this.memory[ data.type + 'Size' ] -= data.size;
  22210. }
  22211. }
  22212. /**
  22213. * Tracks program memory explicitly, updating counts and byte tracking.
  22214. *
  22215. * @param {ProgrammableStage} program - The program to track.
  22216. */
  22217. createProgram( program ) {
  22218. const size = program.code.length; // Approx size
  22219. this.memoryMap.set( program, size );
  22220. this.memory.programs ++;
  22221. this.memory.total += size;
  22222. this.memory.programsSize += size;
  22223. }
  22224. /**
  22225. * Tracks program memory explicitly, updating counts and byte tracking.
  22226. *
  22227. * @param {Object} program - The program to track.
  22228. */
  22229. destroyProgram( program ) {
  22230. const size = this.memoryMap.get( program ) || 0;
  22231. this.memoryMap.delete( program );
  22232. this.memory.programs --;
  22233. this.memory.total -= size;
  22234. this.memory.programsSize -= size;
  22235. }
  22236. /**
  22237. * Calculates the memory size of a texture in bytes.
  22238. *
  22239. * @param {Texture} texture - The texture to calculate the size for.
  22240. * @return {number} The calculated size in bytes.
  22241. * @private
  22242. */
  22243. _getTextureMemorySize( texture ) {
  22244. if ( texture.isCompressedTexture ) {
  22245. return 1; // Fallback estimate since exact format decompressed isn't readily available without format maps
  22246. }
  22247. let bytesPerChannel = 1;
  22248. if ( texture.type === ByteType || texture.type === UnsignedByteType ) bytesPerChannel = 1;
  22249. else if ( texture.type === ShortType || texture.type === UnsignedShortType || texture.type === HalfFloatType ) bytesPerChannel = 2;
  22250. else if ( texture.type === IntType || texture.type === UnsignedIntType || texture.type === FloatType ) bytesPerChannel = 4;
  22251. let channels = 4; // RGBA default
  22252. if ( texture.format === AlphaFormat || texture.format === RedFormat || texture.format === RedIntegerFormat || texture.format === DepthFormat || texture.format === DepthStencilFormat ) channels = 1;
  22253. else if ( texture.format === RGBFormat ) channels = 3;
  22254. let bytesPerPixel = bytesPerChannel * channels;
  22255. // Packed overrides
  22256. if ( texture.type === UnsignedShort4444Type || texture.type === UnsignedShort5551Type ) bytesPerPixel = 2;
  22257. else if ( texture.type === UnsignedInt248Type || texture.type === UnsignedInt5999Type || texture.type === UnsignedInt101111Type ) bytesPerPixel = 4;
  22258. const width = texture.width || 1;
  22259. const height = texture.height || 1;
  22260. const depth = texture.isCubeTexture ? 6 : ( texture.depth || 1 );
  22261. let size = width * height * depth * bytesPerPixel;
  22262. const mipmaps = texture.mipmaps;
  22263. if ( mipmaps && mipmaps.length > 0 ) {
  22264. let mipmapSize = 0;
  22265. for ( let i = 0; i < mipmaps.length; i ++ ) {
  22266. const mipmap = mipmaps[ i ];
  22267. if ( mipmap.data ) {
  22268. mipmapSize += mipmap.data.byteLength;
  22269. } else {
  22270. const mipWidth = mipmap.width || Math.max( 1, width >> i );
  22271. const mipHeight = mipmap.height || Math.max( 1, height >> i );
  22272. mipmapSize += mipWidth * mipHeight * depth * bytesPerPixel;
  22273. }
  22274. }
  22275. size += mipmapSize;
  22276. } else if ( texture.generateMipmaps ) {
  22277. size = size * 1.333; // MiP chain approximation
  22278. }
  22279. return Math.round( size );
  22280. }
  22281. /**
  22282. * Calculates the memory size of an attribute in bytes.
  22283. *
  22284. * @param {BufferAttribute} attribute - The attribute to calculate the size for.
  22285. * @return {number} The calculated size in bytes.
  22286. * @private
  22287. */
  22288. _getAttributeMemorySize( attribute ) {
  22289. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  22290. if ( attribute.array ) {
  22291. return attribute.array.byteLength;
  22292. } else if ( attribute.count && attribute.itemSize ) {
  22293. return attribute.count * attribute.itemSize * 4; // Assume Float32
  22294. }
  22295. return 0;
  22296. }
  22297. }
  22298. /**
  22299. * Abstract class for representing pipelines.
  22300. *
  22301. * @private
  22302. * @abstract
  22303. */
  22304. class Pipeline {
  22305. /**
  22306. * Constructs a new pipeline.
  22307. *
  22308. * @param {string} cacheKey - The pipeline's cache key.
  22309. */
  22310. constructor( cacheKey ) {
  22311. /**
  22312. * The pipeline's cache key.
  22313. *
  22314. * @type {string}
  22315. */
  22316. this.cacheKey = cacheKey;
  22317. /**
  22318. * How often the pipeline is currently in use.
  22319. *
  22320. * @type {number}
  22321. * @default 0
  22322. */
  22323. this.usedTimes = 0;
  22324. }
  22325. }
  22326. /**
  22327. * Class for representing render pipelines.
  22328. *
  22329. * @private
  22330. * @augments Pipeline
  22331. */
  22332. class RenderObjectPipeline extends Pipeline {
  22333. /**
  22334. * Constructs a new render object pipeline.
  22335. *
  22336. * @param {string} cacheKey - The pipeline's cache key.
  22337. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  22338. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  22339. */
  22340. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  22341. super( cacheKey );
  22342. /**
  22343. * The pipeline's vertex shader.
  22344. *
  22345. * @type {ProgrammableStage}
  22346. */
  22347. this.vertexProgram = vertexProgram;
  22348. /**
  22349. * The pipeline's fragment shader.
  22350. *
  22351. * @type {ProgrammableStage}
  22352. */
  22353. this.fragmentProgram = fragmentProgram;
  22354. }
  22355. }
  22356. /**
  22357. * Class for representing compute pipelines.
  22358. *
  22359. * @private
  22360. * @augments Pipeline
  22361. */
  22362. class ComputePipeline extends Pipeline {
  22363. /**
  22364. * Constructs a new compute pipeline.
  22365. *
  22366. * @param {string} cacheKey - The pipeline's cache key.
  22367. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  22368. */
  22369. constructor( cacheKey, computeProgram ) {
  22370. super( cacheKey );
  22371. /**
  22372. * The pipeline's compute shader.
  22373. *
  22374. * @type {ProgrammableStage}
  22375. */
  22376. this.computeProgram = computeProgram;
  22377. /**
  22378. * This flag can be used for type testing.
  22379. *
  22380. * @type {boolean}
  22381. * @readonly
  22382. * @default true
  22383. */
  22384. this.isComputePipeline = true;
  22385. }
  22386. }
  22387. let _id$9 = 0;
  22388. /**
  22389. * Class for representing programmable stages which are vertex,
  22390. * fragment or compute shaders. Unlike fixed-function states (like blending),
  22391. * they represent the programmable part of a pipeline.
  22392. *
  22393. * @private
  22394. */
  22395. class ProgrammableStage {
  22396. /**
  22397. * Constructs a new programmable stage.
  22398. *
  22399. * @param {string} code - The shader code.
  22400. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  22401. * @param {string} name - The name of the shader.
  22402. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22403. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22404. */
  22405. constructor( code, stage, name, transforms = null, attributes = null ) {
  22406. /**
  22407. * The id of the programmable stage.
  22408. *
  22409. * @type {number}
  22410. */
  22411. this.id = _id$9 ++;
  22412. /**
  22413. * The shader code.
  22414. *
  22415. * @type {string}
  22416. */
  22417. this.code = code;
  22418. /**
  22419. * The type of stage.
  22420. *
  22421. * @type {string}
  22422. */
  22423. this.stage = stage;
  22424. /**
  22425. * The name of the stage.
  22426. * This is used for debugging purposes.
  22427. *
  22428. * @type {string}
  22429. */
  22430. this.name = name;
  22431. /**
  22432. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22433. *
  22434. * @type {?Array<Object>}
  22435. */
  22436. this.transforms = transforms;
  22437. /**
  22438. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22439. *
  22440. * @type {?Array<Object>}
  22441. */
  22442. this.attributes = attributes;
  22443. /**
  22444. * How often the programmable stage is currently in use.
  22445. *
  22446. * @type {number}
  22447. * @default 0
  22448. */
  22449. this.usedTimes = 0;
  22450. }
  22451. }
  22452. /**
  22453. * This renderer module manages the pipelines of the renderer.
  22454. *
  22455. * @private
  22456. * @augments DataMap
  22457. */
  22458. class Pipelines extends DataMap {
  22459. /**
  22460. * Constructs a new pipeline management component.
  22461. *
  22462. * @param {Backend} backend - The renderer's backend.
  22463. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  22464. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22465. */
  22466. constructor( backend, nodes, info ) {
  22467. super();
  22468. /**
  22469. * The renderer's backend.
  22470. *
  22471. * @type {Backend}
  22472. */
  22473. this.backend = backend;
  22474. /**
  22475. * Renderer component for managing nodes related logic.
  22476. *
  22477. * @type {NodeManager}
  22478. */
  22479. this.nodes = nodes;
  22480. /**
  22481. * Renderer component for managing metrics and monitoring data.
  22482. *
  22483. * @type {Info}
  22484. */
  22485. this.info = info;
  22486. /**
  22487. * A references to the bindings management component.
  22488. * This reference will be set inside the `Bindings`
  22489. * constructor.
  22490. *
  22491. * @type {?Bindings}
  22492. * @default null
  22493. */
  22494. this.bindings = null;
  22495. /**
  22496. * Internal cache for maintaining pipelines.
  22497. * The key of the map is a cache key, the value the pipeline.
  22498. *
  22499. * @type {Map<string,Pipeline>}
  22500. */
  22501. this.caches = new Map();
  22502. /**
  22503. * This dictionary maintains for each shader stage type (vertex,
  22504. * fragment and compute) the programmable stage objects which
  22505. * represent the actual shader code.
  22506. *
  22507. * @type {Object<string,Map<string, ProgrammableStage>>}
  22508. */
  22509. this.programs = {
  22510. vertex: new Map(),
  22511. fragment: new Map(),
  22512. compute: new Map()
  22513. };
  22514. }
  22515. /**
  22516. * Returns a compute pipeline for the given compute node.
  22517. *
  22518. * @param {Node} computeNode - The compute node.
  22519. * @param {Array<BindGroup>} bindings - The bindings.
  22520. * @return {ComputePipeline} The compute pipeline.
  22521. */
  22522. getForCompute( computeNode, bindings ) {
  22523. const { backend } = this;
  22524. const data = this.get( computeNode );
  22525. if ( this._needsComputeUpdate( computeNode ) ) {
  22526. const previousPipeline = data.pipeline;
  22527. if ( previousPipeline ) {
  22528. previousPipeline.usedTimes --;
  22529. previousPipeline.computeProgram.usedTimes --;
  22530. }
  22531. // get shader
  22532. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  22533. // programmable stage
  22534. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  22535. if ( stageCompute === undefined ) {
  22536. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  22537. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  22538. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  22539. backend.createProgram( stageCompute );
  22540. this.info.createProgram( stageCompute );
  22541. }
  22542. // determine compute pipeline
  22543. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  22544. let pipeline = this.caches.get( cacheKey );
  22545. if ( pipeline === undefined ) {
  22546. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22547. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  22548. }
  22549. // keep track of all used times
  22550. pipeline.usedTimes ++;
  22551. stageCompute.usedTimes ++;
  22552. //
  22553. data.version = computeNode.version;
  22554. data.pipeline = pipeline;
  22555. }
  22556. return data.pipeline;
  22557. }
  22558. /**
  22559. * Returns a render pipeline for the given render object.
  22560. *
  22561. * @param {RenderObject} renderObject - The render object.
  22562. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  22563. * @return {RenderObjectPipeline} The render pipeline.
  22564. */
  22565. getForRender( renderObject, promises = null ) {
  22566. const { backend } = this;
  22567. const data = this.get( renderObject );
  22568. if ( this._needsRenderUpdate( renderObject ) ) {
  22569. const previousPipeline = data.pipeline;
  22570. if ( previousPipeline ) {
  22571. previousPipeline.usedTimes --;
  22572. previousPipeline.vertexProgram.usedTimes --;
  22573. previousPipeline.fragmentProgram.usedTimes --;
  22574. }
  22575. // get shader
  22576. const nodeBuilderState = renderObject.getNodeBuilderState();
  22577. const name = renderObject.material ? renderObject.material.name : '';
  22578. // programmable stages
  22579. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  22580. if ( stageVertex === undefined ) {
  22581. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  22582. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  22583. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  22584. backend.createProgram( stageVertex );
  22585. this.info.createProgram( stageVertex );
  22586. }
  22587. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  22588. if ( stageFragment === undefined ) {
  22589. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  22590. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  22591. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  22592. backend.createProgram( stageFragment );
  22593. this.info.createProgram( stageFragment );
  22594. }
  22595. // determine render pipeline
  22596. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22597. let pipeline = this.caches.get( cacheKey );
  22598. if ( pipeline === undefined ) {
  22599. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22600. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  22601. } else {
  22602. renderObject.pipeline = pipeline;
  22603. }
  22604. // keep track of all used times
  22605. pipeline.usedTimes ++;
  22606. stageVertex.usedTimes ++;
  22607. stageFragment.usedTimes ++;
  22608. //
  22609. data.pipeline = pipeline;
  22610. }
  22611. return data.pipeline;
  22612. }
  22613. /**
  22614. * Checks if the render pipeline for the given render object is ready for drawing.
  22615. * Returns false if the GPU pipeline is still being compiled asynchronously.
  22616. *
  22617. * @param {RenderObject} renderObject - The render object.
  22618. * @return {boolean} True if the pipeline is ready for drawing.
  22619. */
  22620. isReady( renderObject ) {
  22621. const data = this.get( renderObject );
  22622. const pipeline = data.pipeline;
  22623. if ( pipeline === undefined ) return false;
  22624. const pipelineData = this.backend.get( pipeline );
  22625. return pipelineData.pipeline !== undefined && pipelineData.pipeline !== null;
  22626. }
  22627. /**
  22628. * Deletes the pipeline for the given render object.
  22629. *
  22630. * @param {RenderObject} object - The render object.
  22631. * @return {?Object} The deleted dictionary.
  22632. */
  22633. delete( object ) {
  22634. const pipeline = this.get( object ).pipeline;
  22635. if ( pipeline ) {
  22636. // pipeline
  22637. pipeline.usedTimes --;
  22638. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  22639. // programs
  22640. if ( pipeline.isComputePipeline ) {
  22641. pipeline.computeProgram.usedTimes --;
  22642. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  22643. } else {
  22644. pipeline.fragmentProgram.usedTimes --;
  22645. pipeline.vertexProgram.usedTimes --;
  22646. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  22647. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  22648. }
  22649. }
  22650. return super.delete( object );
  22651. }
  22652. /**
  22653. * Frees internal resources.
  22654. */
  22655. dispose() {
  22656. super.dispose();
  22657. this.caches = new Map();
  22658. this.programs = {
  22659. vertex: new Map(),
  22660. fragment: new Map(),
  22661. compute: new Map()
  22662. };
  22663. }
  22664. /**
  22665. * Updates the pipeline for the given render object.
  22666. *
  22667. * @param {RenderObject} renderObject - The render object.
  22668. */
  22669. updateForRender( renderObject ) {
  22670. this.getForRender( renderObject );
  22671. }
  22672. /**
  22673. * Returns a compute pipeline for the given parameters.
  22674. *
  22675. * @private
  22676. * @param {Node} computeNode - The compute node.
  22677. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  22678. * @param {string} cacheKey - The cache key.
  22679. * @param {Array<BindGroup>} bindings - The bindings.
  22680. * @return {ComputePipeline} The compute pipeline.
  22681. */
  22682. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  22683. // check for existing pipeline
  22684. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  22685. let pipeline = this.caches.get( cacheKey );
  22686. if ( pipeline === undefined ) {
  22687. pipeline = new ComputePipeline( cacheKey, stageCompute );
  22688. this.caches.set( cacheKey, pipeline );
  22689. this.backend.createComputePipeline( pipeline, bindings );
  22690. }
  22691. return pipeline;
  22692. }
  22693. /**
  22694. * Returns a render pipeline for the given parameters.
  22695. *
  22696. * @private
  22697. * @param {RenderObject} renderObject - The render object.
  22698. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22699. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22700. * @param {string} cacheKey - The cache key.
  22701. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  22702. * @return {RenderObjectPipeline} The render pipeline.
  22703. */
  22704. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22705. // check for existing pipeline
  22706. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22707. let pipeline = this.caches.get( cacheKey );
  22708. if ( pipeline === undefined ) {
  22709. pipeline = new RenderObjectPipeline( cacheKey, stageVertex, stageFragment );
  22710. this.caches.set( cacheKey, pipeline );
  22711. renderObject.pipeline = pipeline;
  22712. // The `promises` array is `null` by default and only set to an empty array when
  22713. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  22714. // pending promises that resolve when the render pipelines are ready for rendering.
  22715. this.backend.createRenderPipeline( renderObject, promises );
  22716. }
  22717. return pipeline;
  22718. }
  22719. /**
  22720. * Computes a cache key representing a compute pipeline.
  22721. *
  22722. * @private
  22723. * @param {Node} computeNode - The compute node.
  22724. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  22725. * @return {string} The cache key.
  22726. */
  22727. _getComputeCacheKey( computeNode, stageCompute ) {
  22728. return computeNode.id + ',' + stageCompute.id;
  22729. }
  22730. /**
  22731. * Computes a cache key representing a render pipeline.
  22732. *
  22733. * @private
  22734. * @param {RenderObject} renderObject - The render object.
  22735. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22736. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22737. * @return {string} The cache key.
  22738. */
  22739. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22740. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22741. }
  22742. /**
  22743. * Releases the given pipeline.
  22744. *
  22745. * @private
  22746. * @param {Pipeline} pipeline - The pipeline to release.
  22747. */
  22748. _releasePipeline( pipeline ) {
  22749. this.caches.delete( pipeline.cacheKey );
  22750. }
  22751. /**
  22752. * Releases the shader program.
  22753. *
  22754. * @private
  22755. * @param {Object} program - The shader program to release.
  22756. */
  22757. _releaseProgram( program ) {
  22758. const code = program.code;
  22759. const stage = program.stage;
  22760. this.programs[ stage ].delete( code );
  22761. this.info.destroyProgram( program );
  22762. }
  22763. /**
  22764. * Returns `true` if the compute pipeline for the given compute node requires an update.
  22765. *
  22766. * @private
  22767. * @param {Node} computeNode - The compute node.
  22768. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  22769. */
  22770. _needsComputeUpdate( computeNode ) {
  22771. const data = this.get( computeNode );
  22772. return data.pipeline === undefined || data.version !== computeNode.version;
  22773. }
  22774. /**
  22775. * Returns `true` if the render pipeline for the given render object requires an update.
  22776. *
  22777. * @private
  22778. * @param {RenderObject} renderObject - The render object.
  22779. * @return {boolean} Whether the render object for the given render object requires an update or not.
  22780. */
  22781. _needsRenderUpdate( renderObject ) {
  22782. const data = this.get( renderObject );
  22783. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22784. }
  22785. }
  22786. /**
  22787. * This renderer module manages the bindings of the renderer.
  22788. *
  22789. * @private
  22790. * @augments DataMap
  22791. */
  22792. class Bindings extends DataMap {
  22793. /**
  22794. * Constructs a new bindings management component.
  22795. *
  22796. * @param {Backend} backend - The renderer's backend.
  22797. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  22798. * @param {Textures} textures - Renderer component for managing textures.
  22799. * @param {Attributes} attributes - Renderer component for managing attributes.
  22800. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  22801. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22802. */
  22803. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22804. super();
  22805. /**
  22806. * The renderer's backend.
  22807. *
  22808. * @type {Backend}
  22809. */
  22810. this.backend = backend;
  22811. /**
  22812. * Renderer component for managing textures.
  22813. *
  22814. * @type {Textures}
  22815. */
  22816. this.textures = textures;
  22817. /**
  22818. * Renderer component for managing pipelines.
  22819. *
  22820. * @type {Pipelines}
  22821. */
  22822. this.pipelines = pipelines;
  22823. /**
  22824. * Renderer component for managing attributes.
  22825. *
  22826. * @type {Attributes}
  22827. */
  22828. this.attributes = attributes;
  22829. /**
  22830. * Renderer component for managing nodes related logic.
  22831. *
  22832. * @type {NodeManager}
  22833. */
  22834. this.nodes = nodes;
  22835. /**
  22836. * Renderer component for managing metrics and monitoring data.
  22837. *
  22838. * @type {Info}
  22839. */
  22840. this.info = info;
  22841. this.pipelines.bindings = this; // assign bindings to pipelines
  22842. }
  22843. /**
  22844. * Returns the bind groups for the given render object.
  22845. *
  22846. * @param {RenderObject} renderObject - The render object.
  22847. * @return {Array<BindGroup>} The bind groups.
  22848. */
  22849. getForRender( renderObject ) {
  22850. const bindings = renderObject.getBindings();
  22851. for ( const bindGroup of bindings ) {
  22852. const groupData = this.get( bindGroup );
  22853. if ( groupData.bindGroup === undefined ) {
  22854. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22855. this._init( bindGroup );
  22856. this.backend.createBindings( bindGroup, bindings, 0 );
  22857. groupData.bindGroup = bindGroup;
  22858. }
  22859. }
  22860. return bindings;
  22861. }
  22862. /**
  22863. * Returns the bind groups for the given compute node.
  22864. *
  22865. * @param {Node} computeNode - The compute node.
  22866. * @return {Array<BindGroup>} The bind groups.
  22867. */
  22868. getForCompute( computeNode ) {
  22869. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22870. for ( const bindGroup of bindings ) {
  22871. const groupData = this.get( bindGroup );
  22872. if ( groupData.bindGroup === undefined ) {
  22873. this._init( bindGroup );
  22874. this.backend.createBindings( bindGroup, bindings, 0 );
  22875. groupData.bindGroup = bindGroup;
  22876. }
  22877. }
  22878. return bindings;
  22879. }
  22880. /**
  22881. * Updates the bindings for the given compute node.
  22882. *
  22883. * @param {Node} computeNode - The compute node.
  22884. */
  22885. updateForCompute( computeNode ) {
  22886. this._updateBindings( this.getForCompute( computeNode ) );
  22887. }
  22888. /**
  22889. * Updates the bindings for the given render object.
  22890. *
  22891. * @param {RenderObject} renderObject - The render object.
  22892. */
  22893. updateForRender( renderObject ) {
  22894. this._updateBindings( this.getForRender( renderObject ) );
  22895. }
  22896. /**
  22897. * Deletes the bindings for the given compute node.
  22898. *
  22899. * @param {Node} computeNode - The compute node.
  22900. */
  22901. deleteForCompute( computeNode ) {
  22902. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22903. for ( const bindGroup of bindings ) {
  22904. this.backend.deleteBindGroupData( bindGroup );
  22905. this.delete( bindGroup );
  22906. }
  22907. }
  22908. /**
  22909. * Deletes the bindings for the given renderObject node.
  22910. *
  22911. * @param {RenderObject} renderObject - The renderObject.
  22912. */
  22913. deleteForRender( renderObject ) {
  22914. const bindings = renderObject.getBindings();
  22915. for ( const bindGroup of bindings ) {
  22916. this.backend.deleteBindGroupData( bindGroup );
  22917. this.delete( bindGroup );
  22918. }
  22919. }
  22920. /**
  22921. * Updates the given array of bindings.
  22922. *
  22923. * @param {Array<BindGroup>} bindings - The bind groups.
  22924. */
  22925. _updateBindings( bindings ) {
  22926. for ( const bindGroup of bindings ) {
  22927. this._update( bindGroup, bindings );
  22928. }
  22929. }
  22930. /**
  22931. * Initializes the given bind group.
  22932. *
  22933. * @param {BindGroup} bindGroup - The bind group to initialize.
  22934. */
  22935. _init( bindGroup ) {
  22936. for ( const binding of bindGroup.bindings ) {
  22937. if ( binding.isSampledTexture ) {
  22938. this.textures.updateTexture( binding.texture );
  22939. } else if ( binding.isSampler ) {
  22940. this.textures.updateSampler( binding.texture );
  22941. } else if ( binding.isStorageBuffer ) {
  22942. const attribute = binding.attribute;
  22943. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22944. this.attributes.update( attribute, attributeType );
  22945. }
  22946. }
  22947. }
  22948. /**
  22949. * Updates the given bind group.
  22950. *
  22951. * @param {BindGroup} bindGroup - The bind group to update.
  22952. * @param {Array<BindGroup>} bindings - The bind groups.
  22953. */
  22954. _update( bindGroup, bindings ) {
  22955. const { backend } = this;
  22956. let needsBindingsUpdate = false;
  22957. let cacheBindings = true;
  22958. let cacheIndex = 0;
  22959. let version = 0;
  22960. // iterate over all bindings and check if buffer updates or a new binding group is required
  22961. for ( const binding of bindGroup.bindings ) {
  22962. const updatedGroup = this.nodes.updateGroup( binding );
  22963. // every uniforms group is a uniform buffer. So if no update is required,
  22964. // we move one with the next binding. Otherwise the next if block will update the group.
  22965. if ( updatedGroup === false ) continue;
  22966. //
  22967. if ( binding.isStorageBuffer ) {
  22968. const attribute = binding.attribute;
  22969. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22970. const bindingData = backend.get( binding );
  22971. this.attributes.update( attribute, attributeType );
  22972. if ( bindingData.attribute !== attribute ) {
  22973. bindingData.attribute = attribute;
  22974. needsBindingsUpdate = true;
  22975. }
  22976. }
  22977. if ( binding.isUniformBuffer ) {
  22978. const updated = binding.update();
  22979. if ( updated ) {
  22980. backend.updateBinding( binding );
  22981. }
  22982. } else if ( binding.isSampledTexture ) {
  22983. const updated = binding.update();
  22984. // get the texture data after the update, to sync the texture reference from node
  22985. const texture = binding.texture;
  22986. const texturesTextureData = this.textures.get( texture );
  22987. if ( updated ) {
  22988. // version: update the texture data or create a new one
  22989. this.textures.updateTexture( texture );
  22990. // generation: update the bindings if the binding refers to a different texture object
  22991. if ( binding.generation !== texturesTextureData.generation ) {
  22992. binding.generation = texturesTextureData.generation;
  22993. needsBindingsUpdate = true;
  22994. }
  22995. // keep track which bind groups refer to the current texture (this is needed for dispose)
  22996. texturesTextureData.bindGroups.add( bindGroup );
  22997. }
  22998. const textureData = backend.get( texture );
  22999. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  23000. cacheBindings = false;
  23001. } else {
  23002. cacheIndex = cacheIndex * 10 + texture.id;
  23003. version += texture.version;
  23004. }
  23005. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  23006. const textureData = this.get( texture );
  23007. if ( binding.store === true ) {
  23008. textureData.needsMipmap = true;
  23009. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  23010. this.backend.generateMipmaps( texture );
  23011. textureData.needsMipmap = false;
  23012. }
  23013. }
  23014. } else if ( binding.isSampler ) {
  23015. const updated = binding.update();
  23016. if ( updated ) {
  23017. const samplerKey = this.textures.updateSampler( binding.texture );
  23018. if ( binding.samplerKey !== samplerKey ) {
  23019. binding.samplerKey = samplerKey;
  23020. needsBindingsUpdate = true;
  23021. }
  23022. }
  23023. }
  23024. if ( binding.isBuffer && binding.updateRanges.length > 0 ) {
  23025. binding.clearUpdateRanges();
  23026. }
  23027. }
  23028. if ( needsBindingsUpdate === true ) {
  23029. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  23030. }
  23031. }
  23032. }
  23033. /**
  23034. * Default sorting function for opaque render items.
  23035. *
  23036. * @private
  23037. * @function
  23038. * @param {Object} a - The first render item.
  23039. * @param {Object} b - The second render item.
  23040. * @return {number} A numeric value which defines the sort order.
  23041. */
  23042. function painterSortStable( a, b ) {
  23043. if ( a.groupOrder !== b.groupOrder ) {
  23044. return a.groupOrder - b.groupOrder;
  23045. } else if ( a.renderOrder !== b.renderOrder ) {
  23046. return a.renderOrder - b.renderOrder;
  23047. } else if ( a.z !== b.z ) {
  23048. return a.z - b.z;
  23049. } else {
  23050. return a.id - b.id;
  23051. }
  23052. }
  23053. /**
  23054. * Default sorting function for transparent render items.
  23055. *
  23056. * @private
  23057. * @function
  23058. * @param {Object} a - The first render item.
  23059. * @param {Object} b - The second render item.
  23060. * @return {number} A numeric value which defines the sort order.
  23061. */
  23062. function reversePainterSortStable( a, b ) {
  23063. if ( a.groupOrder !== b.groupOrder ) {
  23064. return a.groupOrder - b.groupOrder;
  23065. } else if ( a.renderOrder !== b.renderOrder ) {
  23066. return a.renderOrder - b.renderOrder;
  23067. } else if ( a.z !== b.z ) {
  23068. return b.z - a.z;
  23069. } else {
  23070. return a.id - b.id;
  23071. }
  23072. }
  23073. /**
  23074. * Returns `true` if the given transparent material requires a double pass.
  23075. *
  23076. * @private
  23077. * @function
  23078. * @param {Material} material - The transparent material.
  23079. * @return {boolean} Whether the given material requires a double pass or not.
  23080. */
  23081. function needsDoublePass( material ) {
  23082. const hasTransmission = material.transmission > 0 || ( material.transmissionNode && material.transmissionNode.isNode );
  23083. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  23084. }
  23085. /**
  23086. * When the renderer analyzes the scene at the beginning of a render call,
  23087. * it stores 3D object for further processing in render lists. Depending on the
  23088. * properties of a 3D objects (like their transformation or material state), the
  23089. * objects are maintained in ordered lists for the actual rendering.
  23090. *
  23091. * Render lists are unique per scene and camera combination.
  23092. *
  23093. * @private
  23094. * @augments Pipeline
  23095. */
  23096. class RenderList {
  23097. /**
  23098. * Constructs a render list.
  23099. *
  23100. * @param {Lighting} lighting - The lighting management component.
  23101. * @param {Scene} scene - The scene.
  23102. * @param {Camera} camera - The camera the scene is rendered with.
  23103. */
  23104. constructor( lighting, scene, camera ) {
  23105. /**
  23106. * 3D objects are transformed into render items and stored in this array.
  23107. *
  23108. * @type {Array<Object>}
  23109. */
  23110. this.renderItems = [];
  23111. /**
  23112. * The current render items index.
  23113. *
  23114. * @type {number}
  23115. * @default 0
  23116. */
  23117. this.renderItemsIndex = 0;
  23118. /**
  23119. * A list with opaque render items.
  23120. *
  23121. * @type {Array<Object>}
  23122. */
  23123. this.opaque = [];
  23124. /**
  23125. * A list with transparent render items which require
  23126. * double pass rendering (e.g. transmissive objects).
  23127. *
  23128. * @type {Array<Object>}
  23129. */
  23130. this.transparentDoublePass = [];
  23131. /**
  23132. * A list with transparent render items.
  23133. *
  23134. * @type {Array<Object>}
  23135. */
  23136. this.transparent = [];
  23137. /**
  23138. * A list with transparent render bundle data.
  23139. *
  23140. * @type {Array<Object>}
  23141. */
  23142. this.bundles = [];
  23143. /**
  23144. * The render list's lights node. This node is later
  23145. * relevant for the actual analytical light nodes which
  23146. * compute the scene's lighting in the shader.
  23147. *
  23148. * @type {LightsNode}
  23149. */
  23150. this.lightsNode = lighting.getNode( scene, camera );
  23151. /**
  23152. * The scene's lights stored in an array. This array
  23153. * is used to setup the lights node.
  23154. *
  23155. * @type {Array<Light>}
  23156. */
  23157. this.lightsArray = [];
  23158. /**
  23159. * The scene.
  23160. *
  23161. * @type {Scene}
  23162. */
  23163. this.scene = scene;
  23164. /**
  23165. * The camera the scene is rendered with.
  23166. *
  23167. * @type {Camera}
  23168. */
  23169. this.camera = camera;
  23170. /**
  23171. * How many objects perform occlusion query tests.
  23172. *
  23173. * @type {number}
  23174. * @default 0
  23175. */
  23176. this.occlusionQueryCount = 0;
  23177. }
  23178. /**
  23179. * This method is called right at the beginning of a render call
  23180. * before the scene is analyzed. It prepares the internal data
  23181. * structures for the upcoming render lists generation.
  23182. *
  23183. * @return {RenderList} A reference to this render list.
  23184. */
  23185. begin() {
  23186. this.renderItemsIndex = 0;
  23187. this.opaque.length = 0;
  23188. this.transparentDoublePass.length = 0;
  23189. this.transparent.length = 0;
  23190. this.bundles.length = 0;
  23191. this.lightsArray.length = 0;
  23192. this.occlusionQueryCount = 0;
  23193. return this;
  23194. }
  23195. /**
  23196. * Returns a render item for the giving render item state. The state is defined
  23197. * by a series of object-related parameters.
  23198. *
  23199. * The method avoids object creation by holding render items and reusing them in
  23200. * subsequent render calls (just with different property values).
  23201. *
  23202. * @param {Object3D} object - The 3D object.
  23203. * @param {BufferGeometry} geometry - The 3D object's geometry.
  23204. * @param {Material} material - The 3D object's material.
  23205. * @param {number} groupOrder - The current group order.
  23206. * @param {number} z - Th 3D object's depth value (z value in clip space).
  23207. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  23208. * @param {ClippingContext} clippingContext - The current clipping context.
  23209. * @return {Object} The render item.
  23210. */
  23211. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  23212. let renderItem = this.renderItems[ this.renderItemsIndex ];
  23213. if ( renderItem === undefined ) {
  23214. renderItem = {
  23215. id: object.id,
  23216. object: object,
  23217. geometry: geometry,
  23218. material: material,
  23219. groupOrder: groupOrder,
  23220. renderOrder: object.renderOrder,
  23221. z: z,
  23222. group: group,
  23223. clippingContext: clippingContext
  23224. };
  23225. this.renderItems[ this.renderItemsIndex ] = renderItem;
  23226. } else {
  23227. renderItem.id = object.id;
  23228. renderItem.object = object;
  23229. renderItem.geometry = geometry;
  23230. renderItem.material = material;
  23231. renderItem.groupOrder = groupOrder;
  23232. renderItem.renderOrder = object.renderOrder;
  23233. renderItem.z = z;
  23234. renderItem.group = group;
  23235. renderItem.clippingContext = clippingContext;
  23236. }
  23237. this.renderItemsIndex ++;
  23238. return renderItem;
  23239. }
  23240. /**
  23241. * Pushes the given object as a render item to the internal render lists.
  23242. * The selected lists depend on the object properties.
  23243. *
  23244. * @param {Object3D} object - The 3D object.
  23245. * @param {BufferGeometry} geometry - The 3D object's geometry.
  23246. * @param {Material} material - The 3D object's material.
  23247. * @param {number} groupOrder - The current group order.
  23248. * @param {number} z - Th 3D object's depth value (z value in clip space).
  23249. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  23250. * @param {ClippingContext} clippingContext - The current clipping context.
  23251. */
  23252. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  23253. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  23254. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  23255. if ( material.transparent === true || material.transmission > 0 ||
  23256. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  23257. ( material.backdropNode && material.backdropNode.isNode ) ) {
  23258. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  23259. this.transparent.push( renderItem );
  23260. } else {
  23261. this.opaque.push( renderItem );
  23262. }
  23263. }
  23264. /**
  23265. * Inserts the given object as a render item at the start of the internal render lists.
  23266. * The selected lists depend on the object properties.
  23267. *
  23268. * @param {Object3D} object - The 3D object.
  23269. * @param {BufferGeometry} geometry - The 3D object's geometry.
  23270. * @param {Material} material - The 3D object's material.
  23271. * @param {number} groupOrder - The current group order.
  23272. * @param {number} z - Th 3D object's depth value (z value in clip space).
  23273. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  23274. * @param {ClippingContext} clippingContext - The current clipping context.
  23275. */
  23276. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  23277. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  23278. if ( material.transparent === true || material.transmission > 0 ||
  23279. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  23280. ( material.backdropNode && material.backdropNode.isNode ) ) {
  23281. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  23282. this.transparent.unshift( renderItem );
  23283. } else {
  23284. this.opaque.unshift( renderItem );
  23285. }
  23286. }
  23287. /**
  23288. * Pushes render bundle group data into the render list.
  23289. *
  23290. * @param {Object} group - Bundle group data.
  23291. */
  23292. pushBundle( group ) {
  23293. this.bundles.push( group );
  23294. }
  23295. /**
  23296. * Pushes a light into the render list.
  23297. *
  23298. * @param {Light} light - The light.
  23299. */
  23300. pushLight( light ) {
  23301. this.lightsArray.push( light );
  23302. }
  23303. /**
  23304. * Sorts the internal render lists.
  23305. *
  23306. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  23307. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  23308. */
  23309. sort( customOpaqueSort, customTransparentSort ) {
  23310. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  23311. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  23312. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  23313. }
  23314. /**
  23315. * This method performs finalizing tasks right after the render lists
  23316. * have been generated.
  23317. */
  23318. finish() {
  23319. // update lights
  23320. this.lightsNode.setLights( this.lightsArray );
  23321. // Clear references from inactive renderItems in the list
  23322. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  23323. const renderItem = this.renderItems[ i ];
  23324. if ( renderItem.id === null ) break;
  23325. renderItem.id = null;
  23326. renderItem.object = null;
  23327. renderItem.geometry = null;
  23328. renderItem.material = null;
  23329. renderItem.groupOrder = null;
  23330. renderItem.renderOrder = null;
  23331. renderItem.z = null;
  23332. renderItem.group = null;
  23333. renderItem.clippingContext = null;
  23334. }
  23335. }
  23336. }
  23337. const _chainKeys$2 = [];
  23338. /**
  23339. * This renderer module manages the render lists which are unique
  23340. * per scene and camera combination.
  23341. *
  23342. * @private
  23343. */
  23344. class RenderLists {
  23345. /**
  23346. * Constructs a render lists management component.
  23347. *
  23348. * @param {Lighting} lighting - The lighting management component.
  23349. */
  23350. constructor( lighting ) {
  23351. /**
  23352. * The lighting management component.
  23353. *
  23354. * @type {Lighting}
  23355. */
  23356. this.lighting = lighting;
  23357. /**
  23358. * The internal chain map which holds the render lists.
  23359. *
  23360. * @type {ChainMap}
  23361. */
  23362. this.lists = new ChainMap();
  23363. }
  23364. /**
  23365. * Returns a render list for the given scene and camera.
  23366. *
  23367. * @param {Scene} scene - The scene.
  23368. * @param {Camera} camera - The camera.
  23369. * @return {RenderList} The render list.
  23370. */
  23371. get( scene, camera ) {
  23372. const lists = this.lists;
  23373. _chainKeys$2[ 0 ] = scene;
  23374. _chainKeys$2[ 1 ] = camera;
  23375. let list = lists.get( _chainKeys$2 );
  23376. if ( list === undefined ) {
  23377. list = new RenderList( this.lighting, scene, camera );
  23378. lists.set( _chainKeys$2, list );
  23379. }
  23380. _chainKeys$2[ 0 ] = null;
  23381. _chainKeys$2[ 1 ] = null;
  23382. return list;
  23383. }
  23384. /**
  23385. * Frees all internal resources.
  23386. */
  23387. dispose() {
  23388. this.lists = new ChainMap();
  23389. }
  23390. }
  23391. let _id$8 = 0;
  23392. /**
  23393. * Any render or compute command is executed in a specific context that defines
  23394. * the state of the renderer and its backend. Typical examples for such context
  23395. * data are the current clear values or data from the active framebuffer. This
  23396. * module is used to represent these contexts as objects.
  23397. *
  23398. * @private
  23399. */
  23400. class RenderContext {
  23401. /**
  23402. * Constructs a new render context.
  23403. */
  23404. constructor() {
  23405. /**
  23406. * The context's ID.
  23407. *
  23408. * @type {number}
  23409. */
  23410. this.id = _id$8 ++;
  23411. /**
  23412. * The MRT configuration.
  23413. *
  23414. * @type {?MRTNode}
  23415. * @default null
  23416. */
  23417. this.mrt = null;
  23418. /**
  23419. * Whether the current active framebuffer has a color attachment.
  23420. *
  23421. * @type {boolean}
  23422. * @default true
  23423. */
  23424. this.color = true;
  23425. /**
  23426. * Whether the color attachment should be cleared or not.
  23427. *
  23428. * @type {boolean}
  23429. * @default true
  23430. */
  23431. this.clearColor = true;
  23432. /**
  23433. * The clear color value.
  23434. *
  23435. * @type {Object}
  23436. * @default true
  23437. */
  23438. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  23439. /**
  23440. * Whether the current active framebuffer has a depth attachment.
  23441. *
  23442. * @type {boolean}
  23443. * @default true
  23444. */
  23445. this.depth = true;
  23446. /**
  23447. * Whether the depth attachment should be cleared or not.
  23448. *
  23449. * @type {boolean}
  23450. * @default true
  23451. */
  23452. this.clearDepth = true;
  23453. /**
  23454. * The clear depth value.
  23455. *
  23456. * @type {number}
  23457. * @default 1
  23458. */
  23459. this.clearDepthValue = 1;
  23460. /**
  23461. * Whether the current active framebuffer has a stencil attachment.
  23462. *
  23463. * @type {boolean}
  23464. * @default false
  23465. */
  23466. this.stencil = false;
  23467. /**
  23468. * Whether the stencil attachment should be cleared or not.
  23469. *
  23470. * @type {boolean}
  23471. * @default true
  23472. */
  23473. this.clearStencil = true;
  23474. /**
  23475. * The clear stencil value.
  23476. *
  23477. * @type {number}
  23478. * @default 1
  23479. */
  23480. this.clearStencilValue = 1;
  23481. /**
  23482. * By default the viewport encloses the entire framebuffer If a smaller
  23483. * viewport is manually defined, this property is to `true` by the renderer.
  23484. *
  23485. * @type {boolean}
  23486. * @default false
  23487. */
  23488. this.viewport = false;
  23489. /**
  23490. * The viewport value. This value is in physical pixels meaning it incorporates
  23491. * the renderer's pixel ratio. The viewport property of render targets or
  23492. * the renderer is in logical pixels.
  23493. *
  23494. * @type {Vector4}
  23495. */
  23496. this.viewportValue = new Vector4();
  23497. /**
  23498. * When the scissor test is active and scissor rectangle smaller than the
  23499. * framebuffers dimensions, this property is to `true` by the renderer.
  23500. *
  23501. * @type {boolean}
  23502. * @default false
  23503. */
  23504. this.scissor = false;
  23505. /**
  23506. * The scissor rectangle.
  23507. *
  23508. * @type {Vector4}
  23509. */
  23510. this.scissorValue = new Vector4();
  23511. /**
  23512. * The active render target.
  23513. *
  23514. * @type {?RenderTarget}
  23515. * @default null
  23516. */
  23517. this.renderTarget = null;
  23518. /**
  23519. * The textures of the active render target.
  23520. * `null` when no render target is set.
  23521. *
  23522. * @type {?Array<Texture>}
  23523. * @default null
  23524. */
  23525. this.textures = null;
  23526. /**
  23527. * The depth texture of the active render target.
  23528. * `null` when no render target is set.
  23529. *
  23530. * @type {?DepthTexture}
  23531. * @default null
  23532. */
  23533. this.depthTexture = null;
  23534. /**
  23535. * The active cube face.
  23536. *
  23537. * @type {number}
  23538. * @default 0
  23539. */
  23540. this.activeCubeFace = 0;
  23541. /**
  23542. * The active mipmap level.
  23543. *
  23544. * @type {number}
  23545. * @default 0
  23546. */
  23547. this.activeMipmapLevel = 0;
  23548. /**
  23549. * The number of MSAA samples. This value is always `1` when
  23550. * MSAA isn't used.
  23551. *
  23552. * @type {number}
  23553. * @default 1
  23554. */
  23555. this.sampleCount = 1;
  23556. /**
  23557. * The active render target's width in physical pixels.
  23558. *
  23559. * @type {number}
  23560. * @default 0
  23561. */
  23562. this.width = 0;
  23563. /**
  23564. * The active render target's height in physical pixels.
  23565. *
  23566. * @type {number}
  23567. * @default 0
  23568. */
  23569. this.height = 0;
  23570. /**
  23571. * The occlusion query count.
  23572. *
  23573. * @type {number}
  23574. * @default 0
  23575. */
  23576. this.occlusionQueryCount = 0;
  23577. /**
  23578. * The current clipping context.
  23579. *
  23580. * @type {?ClippingContext}
  23581. * @default null
  23582. */
  23583. this.clippingContext = null;
  23584. /**
  23585. * The current camera.
  23586. *
  23587. * @type {?Camera}
  23588. * @default null
  23589. */
  23590. this.camera = null;
  23591. /**
  23592. * This flag can be used for type testing.
  23593. *
  23594. * @type {boolean}
  23595. * @readonly
  23596. * @default true
  23597. */
  23598. this.isRenderContext = true;
  23599. }
  23600. /**
  23601. * Returns the cache key of this render context.
  23602. *
  23603. * @return {number} The cache key.
  23604. */
  23605. getCacheKey() {
  23606. return getCacheKey( this );
  23607. }
  23608. }
  23609. /**
  23610. * Computes a cache key for the given render context. This key
  23611. * should identify the render target state so it is possible to
  23612. * configure the correct attachments in the respective backend.
  23613. *
  23614. * @param {RenderContext} renderContext - The render context.
  23615. * @return {number} The cache key.
  23616. */
  23617. function getCacheKey( renderContext ) {
  23618. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  23619. const values = [ activeCubeFace, activeMipmapLevel ];
  23620. for ( const texture of textures ) {
  23621. values.push( texture.id );
  23622. }
  23623. return hashArray( values );
  23624. }
  23625. /**
  23626. * This module manages the render contexts of the renderer.
  23627. *
  23628. * @private
  23629. */
  23630. class RenderContexts {
  23631. /**
  23632. * Constructs a new render context management component.
  23633. *
  23634. * @param {Renderer} renderer - The renderer.
  23635. */
  23636. constructor( renderer ) {
  23637. /**
  23638. * The renderer.
  23639. *
  23640. * @type {Renderer}
  23641. */
  23642. this.renderer = renderer;
  23643. /**
  23644. * A dictionary that manages render contexts.
  23645. *
  23646. * @type {Object<string,RenderContext>}
  23647. */
  23648. this._renderContexts = {};
  23649. }
  23650. /**
  23651. * Returns a render context for the given scene, camera and render target.
  23652. *
  23653. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  23654. * @param {?MRTNode} [mrt=null] - The MRT configuration
  23655. * @param {?number} [callDepth=0] - The call depth of the renderer.
  23656. * @return {RenderContext} The render context.
  23657. */
  23658. get( renderTarget = null, mrt = null, callDepth = 0 ) {
  23659. //
  23660. let attachmentState;
  23661. if ( renderTarget === null ) {
  23662. attachmentState = 'default';
  23663. } else {
  23664. const format = renderTarget.texture.format;
  23665. const type = renderTarget.texture.type;
  23666. const count = renderTarget.textures.length;
  23667. attachmentState = `${ count }:${ format }:${ type }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  23668. }
  23669. //
  23670. const mrtState = ( mrt !== null ) ? mrt.id : 'default';
  23671. //
  23672. const renderStateKey = attachmentState + '-' + mrtState + '-' + callDepth;
  23673. let renderState = this._renderContexts[ renderStateKey ];
  23674. if ( renderState === undefined ) {
  23675. renderState = new RenderContext();
  23676. renderState.mrt = mrt;
  23677. this._renderContexts[ renderStateKey ] = renderState;
  23678. }
  23679. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  23680. renderState.clearDepthValue = this.renderer.getClearDepth();
  23681. renderState.clearStencilValue = this.renderer.getClearStencil();
  23682. return renderState;
  23683. }
  23684. /**
  23685. * Frees internal resources.
  23686. */
  23687. dispose() {
  23688. this._renderContexts = {};
  23689. }
  23690. }
  23691. const _size$3 = /*@__PURE__*/ new Vector3();
  23692. /**
  23693. * This module manages the textures of the renderer.
  23694. *
  23695. * @private
  23696. * @augments DataMap
  23697. */
  23698. class Textures extends DataMap {
  23699. /**
  23700. * Constructs a new texture management component.
  23701. *
  23702. * @param {Renderer} renderer - The renderer.
  23703. * @param {Backend} backend - The renderer's backend.
  23704. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  23705. */
  23706. constructor( renderer, backend, info ) {
  23707. super();
  23708. /**
  23709. * The renderer.
  23710. *
  23711. * @type {Renderer}
  23712. */
  23713. this.renderer = renderer;
  23714. /**
  23715. * The backend.
  23716. *
  23717. * @type {Backend}
  23718. */
  23719. this.backend = backend;
  23720. /**
  23721. * Renderer component for managing metrics and monitoring data.
  23722. *
  23723. * @type {Info}
  23724. */
  23725. this.info = info;
  23726. }
  23727. /**
  23728. * Updates the given render target. Based on the given render target configuration,
  23729. * it updates the texture states representing the attachments of the framebuffer.
  23730. *
  23731. * @param {RenderTarget} renderTarget - The render target to update.
  23732. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  23733. */
  23734. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  23735. const renderTargetData = this.get( renderTarget );
  23736. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  23737. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  23738. const textures = renderTarget.textures;
  23739. const size = this.getSize( textures[ 0 ] );
  23740. const mipWidth = size.width >> activeMipmapLevel;
  23741. const mipHeight = size.height >> activeMipmapLevel;
  23742. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  23743. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  23744. let textureNeedsUpdate = false;
  23745. if ( depthTexture === undefined && useDepthTexture ) {
  23746. depthTexture = new DepthTexture();
  23747. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  23748. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  23749. depthTexture.image.width = mipWidth;
  23750. depthTexture.image.height = mipHeight;
  23751. depthTexture.image.depth = size.depth;
  23752. depthTexture.renderTarget = renderTarget;
  23753. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  23754. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  23755. }
  23756. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  23757. textureNeedsUpdate = true;
  23758. if ( depthTexture ) {
  23759. depthTexture.needsUpdate = true;
  23760. depthTexture.image.width = mipWidth;
  23761. depthTexture.image.height = mipHeight;
  23762. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  23763. }
  23764. }
  23765. renderTargetData.width = size.width;
  23766. renderTargetData.height = size.height;
  23767. renderTargetData.textures = textures;
  23768. renderTargetData.depthTexture = depthTexture || null;
  23769. renderTargetData.depth = renderTarget.depthBuffer;
  23770. renderTargetData.stencil = renderTarget.stencilBuffer;
  23771. renderTargetData.renderTarget = renderTarget;
  23772. if ( renderTargetData.sampleCount !== sampleCount ) {
  23773. textureNeedsUpdate = true;
  23774. if ( depthTexture ) {
  23775. depthTexture.needsUpdate = true;
  23776. }
  23777. renderTargetData.sampleCount = sampleCount;
  23778. }
  23779. //
  23780. const options = { sampleCount };
  23781. // XR render targets require no texture updates
  23782. if ( renderTarget.isXRRenderTarget !== true ) {
  23783. for ( let i = 0; i < textures.length; i ++ ) {
  23784. const texture = textures[ i ];
  23785. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  23786. this.updateTexture( texture, options );
  23787. }
  23788. if ( depthTexture ) {
  23789. this.updateTexture( depthTexture, options );
  23790. }
  23791. }
  23792. // dispose handler
  23793. if ( renderTargetData.initialized !== true ) {
  23794. renderTargetData.initialized = true;
  23795. this.info.memory.renderTargets ++;
  23796. // dispose
  23797. renderTargetData.onDispose = () => {
  23798. this._destroyRenderTarget( renderTarget );
  23799. };
  23800. renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );
  23801. }
  23802. }
  23803. /**
  23804. * Updates the given texture. Depending on the texture state, this method
  23805. * triggers the upload of texture data to the GPU memory. If the texture data are
  23806. * not yet ready for the upload, it uses default texture data for as a placeholder.
  23807. *
  23808. * @param {Texture} texture - The texture to update.
  23809. * @param {Object} [options={}] - The options.
  23810. */
  23811. updateTexture( texture, options = {} ) {
  23812. const textureData = this.get( texture );
  23813. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  23814. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  23815. const backend = this.backend;
  23816. if ( isRenderTarget && textureData.initialized === true ) {
  23817. // it's an update
  23818. backend.destroyTexture( texture );
  23819. }
  23820. //
  23821. if ( texture.isFramebufferTexture ) {
  23822. const renderTarget = this.renderer.getRenderTarget();
  23823. if ( renderTarget ) {
  23824. texture.type = renderTarget.texture.type;
  23825. } else {
  23826. texture.type = UnsignedByteType;
  23827. }
  23828. }
  23829. //
  23830. const { width, height, depth } = this.getSize( texture );
  23831. options.width = width;
  23832. options.height = height;
  23833. options.depth = depth;
  23834. options.needsMipmaps = this.needsMipmaps( texture );
  23835. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  23836. // TODO: Uniformly handle mipmap definitions
  23837. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  23838. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  23839. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  23840. //
  23841. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  23842. backend.createTexture( texture, options );
  23843. textureData.generation = texture.version;
  23844. } else {
  23845. if ( texture.version > 0 ) {
  23846. const image = texture.image;
  23847. if ( image === undefined ) {
  23848. warn( 'Renderer: Texture marked for update but image is undefined.' );
  23849. } else if ( image.complete === false ) {
  23850. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  23851. } else {
  23852. if ( texture.images ) {
  23853. const images = [];
  23854. for ( const image of texture.images ) {
  23855. images.push( image );
  23856. }
  23857. options.images = images;
  23858. } else {
  23859. options.image = image;
  23860. }
  23861. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  23862. backend.createTexture( texture, options );
  23863. textureData.isDefaultTexture = false;
  23864. textureData.generation = texture.version;
  23865. }
  23866. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  23867. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  23868. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  23869. backend.generateMipmaps( texture );
  23870. }
  23871. if ( texture.onUpdate ) texture.onUpdate( texture );
  23872. }
  23873. } else {
  23874. // async update
  23875. backend.createDefaultTexture( texture );
  23876. textureData.isDefaultTexture = true;
  23877. textureData.generation = texture.version;
  23878. }
  23879. }
  23880. // dispose handler
  23881. if ( textureData.initialized !== true ) {
  23882. textureData.initialized = true;
  23883. textureData.generation = texture.version;
  23884. textureData.bindGroups = new Set();
  23885. //
  23886. this.info.createTexture( texture );
  23887. //
  23888. if ( texture.isVideoTexture && ColorManagement.enabled === true && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  23889. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  23890. }
  23891. // dispose
  23892. textureData.onDispose = () => {
  23893. this._destroyTexture( texture );
  23894. };
  23895. texture.addEventListener( 'dispose', textureData.onDispose );
  23896. }
  23897. //
  23898. textureData.version = texture.version;
  23899. }
  23900. /**
  23901. * Updates the sampler for the given texture. This method has no effect
  23902. * for the WebGL backend since it has no concept of samplers. Texture
  23903. * parameters are configured with the `texParameter()` command for each
  23904. * texture.
  23905. *
  23906. * In WebGPU, samplers are objects like textures and it's possible to share
  23907. * them when the texture parameters match.
  23908. *
  23909. * @param {Texture} texture - The texture to update the sampler for.
  23910. * @return {string} The current sampler key.
  23911. */
  23912. updateSampler( texture ) {
  23913. return this.backend.updateSampler( texture );
  23914. }
  23915. /**
  23916. * Computes the size of the given texture and writes the result
  23917. * into the target vector. This vector is also returned by the
  23918. * method.
  23919. *
  23920. * If no texture data are available for the compute yet, the method
  23921. * returns default size values.
  23922. *
  23923. * @param {Texture} texture - The texture to compute the size for.
  23924. * @param {Vector3} target - The target vector.
  23925. * @return {Vector3} The target vector.
  23926. */
  23927. getSize( texture, target = _size$3 ) {
  23928. let image = texture.images ? texture.images[ 0 ] : texture.image;
  23929. if ( image ) {
  23930. if ( image.image !== undefined ) image = image.image;
  23931. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  23932. target.width = image.videoWidth || 1;
  23933. target.height = image.videoHeight || 1;
  23934. target.depth = 1;
  23935. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  23936. target.width = image.displayWidth || 1;
  23937. target.height = image.displayHeight || 1;
  23938. target.depth = 1;
  23939. } else {
  23940. target.width = image.width || 1;
  23941. target.height = image.height || 1;
  23942. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  23943. }
  23944. } else {
  23945. target.width = target.height = target.depth = 1;
  23946. }
  23947. return target;
  23948. }
  23949. /**
  23950. * Computes the number of mipmap levels for the given texture.
  23951. *
  23952. * @param {Texture} texture - The texture.
  23953. * @param {number} width - The texture's width.
  23954. * @param {number} height - The texture's height.
  23955. * @return {number} The number of mipmap levels.
  23956. */
  23957. getMipLevels( texture, width, height ) {
  23958. let mipLevelCount;
  23959. if ( texture.mipmaps.length > 0 ) {
  23960. mipLevelCount = texture.mipmaps.length;
  23961. } else {
  23962. if ( texture.isCompressedTexture === true ) {
  23963. // it is not possible to compute mipmaps for compressed textures. So
  23964. // when no mipmaps are defined in "texture.mipmaps", force a texture
  23965. // level of 1
  23966. mipLevelCount = 1;
  23967. } else {
  23968. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  23969. }
  23970. }
  23971. return mipLevelCount;
  23972. }
  23973. /**
  23974. * Returns `true` if the given texture makes use of mipmapping.
  23975. *
  23976. * @param {Texture} texture - The texture.
  23977. * @return {boolean} Whether mipmaps are required or not.
  23978. */
  23979. needsMipmaps( texture ) {
  23980. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  23981. }
  23982. /**
  23983. * Frees internal resources when the given render target isn't
  23984. * required anymore.
  23985. *
  23986. * @param {RenderTarget} renderTarget - The render target to destroy.
  23987. */
  23988. _destroyRenderTarget( renderTarget ) {
  23989. if ( this.has( renderTarget ) === true ) {
  23990. const renderTargetData = this.get( renderTarget );
  23991. const textures = renderTargetData.textures;
  23992. const depthTexture = renderTargetData.depthTexture;
  23993. //
  23994. renderTarget.removeEventListener( 'dispose', renderTargetData.onDispose );
  23995. //
  23996. for ( let i = 0; i < textures.length; i ++ ) {
  23997. this._destroyTexture( textures[ i ] );
  23998. }
  23999. if ( depthTexture ) {
  24000. this._destroyTexture( depthTexture );
  24001. }
  24002. this.delete( renderTarget );
  24003. this.backend.delete( renderTarget );
  24004. this.info.memory.renderTargets --;
  24005. }
  24006. }
  24007. /**
  24008. * Frees internal resource when the given texture isn't
  24009. * required anymore.
  24010. *
  24011. * @param {Texture} texture - The texture to destroy.
  24012. */
  24013. _destroyTexture( texture ) {
  24014. if ( this.has( texture ) === true ) {
  24015. const textureData = this.get( texture );
  24016. //
  24017. texture.removeEventListener( 'dispose', textureData.onDispose );
  24018. // if a texture is not ready for use, it falls back to a default texture so it's possible
  24019. // to use it for rendering. If a texture in this state is disposed, it's important to
  24020. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  24021. // other textures.
  24022. const isDefaultTexture = textureData.isDefaultTexture;
  24023. this.backend.destroyTexture( texture, isDefaultTexture );
  24024. // delete cached bind groups so they don't point to destroyed textures
  24025. if ( textureData.bindGroups ) {
  24026. for ( const bindGroup of textureData.bindGroups ) {
  24027. const bindingsData = this.backend.get( bindGroup );
  24028. bindingsData.groups = undefined;
  24029. bindingsData.versions = undefined;
  24030. }
  24031. }
  24032. this.delete( texture );
  24033. this.info.destroyTexture( texture );
  24034. }
  24035. }
  24036. }
  24037. /**
  24038. * A four-component version of {@link Color} which is internally
  24039. * used by the renderer to represents clear color with alpha as
  24040. * one object.
  24041. *
  24042. * @private
  24043. * @augments Color
  24044. */
  24045. class Color4 extends Color {
  24046. /**
  24047. * Constructs a new four-component color.
  24048. * You can also pass a single THREE.Color, hex or
  24049. * string argument to this constructor.
  24050. *
  24051. * @param {number|string} [r=1] - The red value.
  24052. * @param {number} [g=1] - The green value.
  24053. * @param {number} [b=1] - The blue value.
  24054. * @param {number} [a=1] - The alpha value.
  24055. */
  24056. constructor( r, g, b, a = 1 ) {
  24057. super( r, g, b );
  24058. this.a = a;
  24059. }
  24060. /**
  24061. * Overwrites the default to honor alpha.
  24062. * You can also pass a single THREE.Color, hex or
  24063. * string argument to this method.
  24064. *
  24065. * @param {number|string|Color} r - The red value.
  24066. * @param {number} [g] - The green value.
  24067. * @param {number} [b] - The blue value.
  24068. * @param {number} [a=1] - The alpha value.
  24069. * @return {Color4} A reference to this object.
  24070. */
  24071. set( r, g, b, a = 1 ) {
  24072. this.a = a;
  24073. return super.set( r, g, b );
  24074. }
  24075. /**
  24076. * Overwrites the default to honor alpha.
  24077. *
  24078. * @param {Color4} color - The color to copy.
  24079. * @return {Color4} A reference to this object.
  24080. */
  24081. copy( color ) {
  24082. if ( color.a !== undefined ) this.a = color.a;
  24083. return super.copy( color );
  24084. }
  24085. /**
  24086. * Overwrites the default to honor alpha.
  24087. *
  24088. * @return {Color4} The cloned color.
  24089. */
  24090. clone() {
  24091. return new this.constructor( this.r, this.g, this.b, this.a );
  24092. }
  24093. }
  24094. /**
  24095. * Special version of {@link PropertyNode} which is used for parameters.
  24096. *
  24097. * @augments PropertyNode
  24098. */
  24099. class ParameterNode extends PropertyNode {
  24100. static get type() {
  24101. return 'ParameterNode';
  24102. }
  24103. /**
  24104. * Constructs a new parameter node.
  24105. *
  24106. * @param {string} nodeType - The type of the node.
  24107. * @param {?string} [name=null] - The name of the parameter in the shader.
  24108. */
  24109. constructor( nodeType, name = null ) {
  24110. super( nodeType, name );
  24111. /**
  24112. * This flag can be used for type testing.
  24113. *
  24114. * @type {boolean}
  24115. * @readonly
  24116. * @default true
  24117. */
  24118. this.isParameterNode = true;
  24119. }
  24120. /**
  24121. * Gets the type of a member variable in the parameter node.
  24122. *
  24123. * @param {NodeBuilder} builder - The node builder.
  24124. * @param {string} name - The name of the member variable.
  24125. * @returns {string}
  24126. */
  24127. getMemberType( builder, name ) {
  24128. const type = this.getNodeType( builder );
  24129. const struct = builder.getStructTypeNode( type );
  24130. let memberType;
  24131. if ( struct !== null ) {
  24132. memberType = struct.getMemberType( builder, name );
  24133. } else {
  24134. error( `TSL: Member "${ name }" not found in struct "${ type }".`, new StackTrace() );
  24135. memberType = 'float';
  24136. }
  24137. return memberType;
  24138. }
  24139. getHash() {
  24140. return String( this.id );
  24141. }
  24142. generate() {
  24143. return this.name;
  24144. }
  24145. }
  24146. /**
  24147. * TSL function for creating a parameter node.
  24148. *
  24149. * @tsl
  24150. * @function
  24151. * @param {string} type - The type of the node.
  24152. * @param {?string} name - The name of the parameter in the shader.
  24153. * @returns {ParameterNode}
  24154. */
  24155. const parameter = ( type, name ) => new ParameterNode( type, name );
  24156. /**
  24157. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  24158. * They are usually needed in cases like `If`, `Else`.
  24159. *
  24160. * @augments Node
  24161. */
  24162. class StackNode extends Node {
  24163. static get type() {
  24164. return 'StackNode';
  24165. }
  24166. /**
  24167. * Constructs a new stack node.
  24168. *
  24169. * @param {?StackNode} [parent=null] - The parent stack node.
  24170. */
  24171. constructor( parent = null ) {
  24172. super();
  24173. /**
  24174. * List of nodes.
  24175. *
  24176. * @type {Array<Node>}
  24177. */
  24178. this.nodes = [];
  24179. /**
  24180. * The output node.
  24181. *
  24182. * @type {?Node}
  24183. * @default null
  24184. */
  24185. this.outputNode = null;
  24186. /**
  24187. * The parent stack node.
  24188. *
  24189. * @type {?StackNode}
  24190. * @default null
  24191. */
  24192. this.parent = parent;
  24193. /**
  24194. * The current conditional node.
  24195. *
  24196. * @private
  24197. * @type {ConditionalNode}
  24198. * @default null
  24199. */
  24200. this._currentCond = null;
  24201. /**
  24202. * The expression node. Only
  24203. * relevant for Switch/Case.
  24204. *
  24205. * @private
  24206. * @type {Node}
  24207. * @default null
  24208. */
  24209. this._expressionNode = null;
  24210. /**
  24211. * The current node being processed.
  24212. *
  24213. * @private
  24214. * @type {Node}
  24215. * @default null
  24216. */
  24217. this._currentNode = null;
  24218. /**
  24219. * This flag can be used for type testing.
  24220. *
  24221. * @type {boolean}
  24222. * @readonly
  24223. * @default true
  24224. */
  24225. this.isStackNode = true;
  24226. }
  24227. getElementType( builder ) {
  24228. return this.hasOutput( builder ) ? this.outputNode.getElementType( builder ) : 'void';
  24229. }
  24230. generateNodeType( builder ) {
  24231. return this.hasOutput( builder ) ? this.outputNode.getNodeType( builder ) : 'void';
  24232. }
  24233. getMemberType( builder, name ) {
  24234. return this.hasOutput( builder ) ? this.outputNode.getMemberType( builder, name ) : 'void';
  24235. }
  24236. /**
  24237. * Adds a node to this stack.
  24238. *
  24239. * @param {Node} node - The node to add.
  24240. * @param {number} [index=this.nodes.length] - The index where the node should be added.
  24241. * @return {StackNode} A reference to this stack node.
  24242. */
  24243. addToStack( node, index = this.nodes.length ) {
  24244. if ( node.isNode !== true ) {
  24245. error( 'TSL: Invalid node added to stack.', new StackTrace() );
  24246. return this;
  24247. }
  24248. this.nodes.splice( index, 0, node );
  24249. return this;
  24250. }
  24251. /**
  24252. * Adds a node to the stack before the current node.
  24253. *
  24254. * @param {Node} node - The node to add.
  24255. * @return {StackNode} A reference to this stack node.
  24256. */
  24257. addToStackBefore( node ) {
  24258. const index = this._currentNode ? this.nodes.indexOf( this._currentNode ) : 0;
  24259. return this.addToStack( node, index );
  24260. }
  24261. /**
  24262. * Represent an `if` statement in TSL.
  24263. *
  24264. * @param {Node} boolNode - Represents the condition.
  24265. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  24266. * @return {StackNode} A reference to this stack node.
  24267. */
  24268. If( boolNode, method ) {
  24269. const methodNode = new ShaderNode( method );
  24270. this._currentCond = select( boolNode, methodNode );
  24271. return this.addToStack( this._currentCond );
  24272. }
  24273. /**
  24274. * Represent an `elseif` statement in TSL.
  24275. *
  24276. * @param {Node} boolNode - Represents the condition.
  24277. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  24278. * @return {StackNode} A reference to this stack node.
  24279. */
  24280. ElseIf( boolNode, method ) {
  24281. const methodNode = new ShaderNode( method );
  24282. const ifNode = select( boolNode, methodNode );
  24283. this._currentCond.elseNode = ifNode;
  24284. this._currentCond = ifNode;
  24285. return this;
  24286. }
  24287. /**
  24288. * Represent an `else` statement in TSL.
  24289. *
  24290. * @param {Function} method - TSL code which is executed in the `else` case.
  24291. * @return {StackNode} A reference to this stack node.
  24292. */
  24293. Else( method ) {
  24294. this._currentCond.elseNode = new ShaderNode( method );
  24295. return this;
  24296. }
  24297. /**
  24298. * Represents a `switch` statement in TSL.
  24299. *
  24300. * @param {any} expression - Represents the expression.
  24301. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  24302. * @return {StackNode} A reference to this stack node.
  24303. */
  24304. Switch( expression ) {
  24305. this._expressionNode = nodeObject( expression );
  24306. return this;
  24307. }
  24308. /**
  24309. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  24310. * The last parameter must be the callback method that should be executed in the `true` case.
  24311. *
  24312. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  24313. * @return {StackNode} A reference to this stack node.
  24314. */
  24315. Case( ...params ) {
  24316. const caseNodes = [];
  24317. // extract case nodes from the parameter list
  24318. if ( params.length >= 2 ) {
  24319. for ( let i = 0; i < params.length - 1; i ++ ) {
  24320. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  24321. }
  24322. } else {
  24323. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.', new StackTrace() );
  24324. }
  24325. // extract method
  24326. const method = params[ params.length - 1 ];
  24327. const methodNode = new ShaderNode( method );
  24328. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  24329. let caseNode = caseNodes[ 0 ];
  24330. for ( let i = 1; i < caseNodes.length; i ++ ) {
  24331. caseNode = caseNode.or( caseNodes[ i ] );
  24332. }
  24333. // build condition
  24334. const condNode = select( caseNode, methodNode );
  24335. if ( this._currentCond === null ) {
  24336. this._currentCond = condNode;
  24337. return this.addToStack( this._currentCond );
  24338. } else {
  24339. this._currentCond.elseNode = condNode;
  24340. this._currentCond = condNode;
  24341. return this;
  24342. }
  24343. }
  24344. /**
  24345. * Represents the default code block of a Switch/Case statement.
  24346. *
  24347. * @param {Function} method - TSL code which is executed in the `else` case.
  24348. * @return {StackNode} A reference to this stack node.
  24349. */
  24350. Default( method ) {
  24351. this.Else( method );
  24352. return this;
  24353. }
  24354. setup( builder ) {
  24355. const nodeProperties = builder.getNodeProperties( this );
  24356. let index = 0;
  24357. for ( const childNode of this.getChildren() ) {
  24358. if ( childNode.isVarNode && childNode.isIntent( builder ) ) {
  24359. if ( childNode.isAssign( builder ) !== true ) {
  24360. continue;
  24361. }
  24362. }
  24363. nodeProperties[ 'node' + index ++ ] = childNode;
  24364. }
  24365. // return a outputNode if exists or null
  24366. return nodeProperties.outputNode || null;
  24367. }
  24368. hasOutput( builder ) {
  24369. return this.outputNode && this.outputNode.isNode && this.outputNode.getNodeType( builder ) !== 'void';
  24370. }
  24371. build( builder, ...params ) {
  24372. const previousStack = getCurrentStack();
  24373. const buildStage = builder.buildStage;
  24374. setCurrentStack( this );
  24375. builder.setActiveStack( this );
  24376. //
  24377. const buildNode = ( node ) => {
  24378. this._currentNode = node;
  24379. if ( node.isVarNode && node.isIntent( builder ) ) {
  24380. if ( node.isAssign( builder ) !== true ) {
  24381. return;
  24382. }
  24383. }
  24384. if ( buildStage === 'setup' ) {
  24385. node.build( builder );
  24386. } else if ( buildStage === 'analyze' ) {
  24387. node.build( builder, this );
  24388. } else if ( buildStage === 'generate' ) {
  24389. const stages = builder.getDataFromNode( node, 'any' ).stages;
  24390. const parents = stages && stages[ builder.shaderStage ];
  24391. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  24392. return; // skip var nodes that are only used in .toVarying()
  24393. }
  24394. node.build( builder, 'void' );
  24395. }
  24396. };
  24397. //
  24398. const nodes = [ ...this.nodes ];
  24399. for ( const node of nodes ) {
  24400. buildNode( node );
  24401. }
  24402. this._currentNode = null;
  24403. const newNodes = this.nodes.filter( ( node ) => nodes.indexOf( node ) === -1 );
  24404. for ( const node of newNodes ) {
  24405. buildNode( node );
  24406. }
  24407. //
  24408. let result;
  24409. if ( this.hasOutput( builder ) ) {
  24410. result = this.outputNode.build( builder, ...params );
  24411. } else {
  24412. result = super.build( builder, ...params );
  24413. }
  24414. setCurrentStack( previousStack );
  24415. builder.removeActiveStack( this );
  24416. return result;
  24417. }
  24418. }
  24419. /**
  24420. * TSL function for creating a stack node.
  24421. *
  24422. * @tsl
  24423. * @function
  24424. * @param {?StackNode} [parent=null] - The parent stack node.
  24425. * @returns {StackNode}
  24426. */
  24427. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  24428. /**
  24429. * Generates a layout for struct members.
  24430. * This function takes an object representing struct members and returns an array of member layouts.
  24431. * Each member layout includes the member's name, type, and whether it is atomic.
  24432. *
  24433. * @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.
  24434. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  24435. */
  24436. function getMembersLayout( members ) {
  24437. return Object.entries( members ).map( ( [ name, value ] ) => {
  24438. if ( typeof value === 'string' ) {
  24439. return { name, type: value, atomic: false };
  24440. }
  24441. return { name, type: value.type, atomic: value.atomic || false };
  24442. } );
  24443. }
  24444. /**
  24445. * Represents a struct type node in the node-based system.
  24446. * This class is used to define and manage the layout and types of struct members.
  24447. * It extends the base Node class and provides methods to get the length of the struct,
  24448. * retrieve member types, and generate the struct type for a builder.
  24449. *
  24450. * @augments Node
  24451. */
  24452. class StructTypeNode extends Node {
  24453. static get type() {
  24454. return 'StructTypeNode';
  24455. }
  24456. /**
  24457. * Creates an instance of StructTypeNode.
  24458. *
  24459. * @param {Object} membersLayout - The layout of the members for the struct.
  24460. * @param {?string} [name=null] - The optional name of the struct.
  24461. */
  24462. constructor( membersLayout, name = null ) {
  24463. super( 'struct' );
  24464. /**
  24465. * The layout of the members for the struct
  24466. *
  24467. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  24468. */
  24469. this.membersLayout = getMembersLayout( membersLayout );
  24470. /**
  24471. * The name of the struct.
  24472. *
  24473. * @type {?string}
  24474. * @default null
  24475. */
  24476. this.name = name;
  24477. /**
  24478. * This flag can be used for type testing.
  24479. *
  24480. * @type {boolean}
  24481. * @readonly
  24482. * @default true
  24483. */
  24484. this.isStructLayoutNode = true;
  24485. }
  24486. /**
  24487. * Returns the length of the struct.
  24488. * The length is calculated by summing the lengths of the struct's members.
  24489. *
  24490. * @returns {number} The length of the struct.
  24491. */
  24492. getLength() {
  24493. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  24494. let maxAlignment = 1; // maximum alignment value in this struct
  24495. let offset = 0; // global buffer offset in 4 byte elements
  24496. for ( const member of this.membersLayout ) {
  24497. const type = member.type;
  24498. const itemSize = getMemoryLengthFromType( type );
  24499. const alignment = getAlignmentFromType( type ) / BYTES_PER_ELEMENT;
  24500. maxAlignment = Math.max( maxAlignment, alignment );
  24501. const chunkOffset = offset % maxAlignment; // offset in the current chunk of maxAlignment elements
  24502. const overhang = chunkOffset % alignment; // distance from the last aligned offset
  24503. if ( overhang !== 0 ) {
  24504. offset += alignment - overhang; // move to next aligned offset
  24505. }
  24506. offset += itemSize;
  24507. }
  24508. return ( Math.ceil( offset / maxAlignment ) * maxAlignment ); // ensure length is a multiple of maxAlignment
  24509. }
  24510. getMemberType( builder, name ) {
  24511. const member = this.membersLayout.find( m => m.name === name );
  24512. return member ? member.type : 'void';
  24513. }
  24514. generateNodeType( builder ) {
  24515. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  24516. return structType.name;
  24517. }
  24518. setup( builder ) {
  24519. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  24520. builder.addInclude( this );
  24521. }
  24522. generate( builder ) {
  24523. return this.getNodeType( builder );
  24524. }
  24525. }
  24526. /**
  24527. * StructNode allows to create custom structures with multiple members.
  24528. * This can also be used to define structures in attribute and uniform data.
  24529. *
  24530. * ```js
  24531. * // Define a custom struct
  24532. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  24533. *
  24534. * // Create a new instance of the struct
  24535. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  24536. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  24537. *
  24538. * // Access the struct members
  24539. * const min = bb.get( 'min' );
  24540. *
  24541. * // Assign a new value to a member
  24542. * min.assign( vec3() );
  24543. * ```
  24544. * @augments Node
  24545. */
  24546. class StructNode extends Node {
  24547. static get type() {
  24548. return 'StructNode';
  24549. }
  24550. constructor( structTypeNode, values ) {
  24551. super( 'vec3' );
  24552. this.structTypeNode = structTypeNode;
  24553. this.values = values;
  24554. this.isStructNode = true;
  24555. }
  24556. generateNodeType( builder ) {
  24557. return this.structTypeNode.getNodeType( builder );
  24558. }
  24559. getMemberType( builder, name ) {
  24560. return this.structTypeNode.getMemberType( builder, name );
  24561. }
  24562. _getChildren() {
  24563. // Ensure struct type is the last child for correct code generation order
  24564. const children = super._getChildren();
  24565. const structTypeProperty = children.find( child => child.childNode === this.structTypeNode );
  24566. children.splice( children.indexOf( structTypeProperty ), 1 );
  24567. children.push( structTypeProperty );
  24568. return children;
  24569. }
  24570. generate( builder ) {
  24571. const nodeVar = builder.getVarFromNode( this );
  24572. const structType = nodeVar.type;
  24573. const propertyName = builder.getPropertyName( nodeVar );
  24574. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  24575. return nodeVar.name;
  24576. }
  24577. }
  24578. /**
  24579. * TSL function for creating a struct node.
  24580. *
  24581. * @tsl
  24582. * @function
  24583. * @param {Object} membersLayout - The layout of the struct members.
  24584. * @param {?string} [name=null] - The name of the struct.
  24585. * @returns {Function} The struct function.
  24586. */
  24587. const struct = ( membersLayout, name = null ) => {
  24588. const structLayout = new StructTypeNode( membersLayout, name );
  24589. const struct = ( ...params ) => {
  24590. let values = null;
  24591. if ( params.length > 0 ) {
  24592. if ( params[ 0 ].isNode ) {
  24593. values = {};
  24594. const names = Object.keys( membersLayout );
  24595. for ( let i = 0; i < params.length; i ++ ) {
  24596. values[ names[ i ] ] = params[ i ];
  24597. }
  24598. } else {
  24599. values = params[ 0 ];
  24600. }
  24601. }
  24602. return new StructNode( structLayout, values );
  24603. };
  24604. struct.layout = structLayout;
  24605. struct.isStruct = true;
  24606. return struct;
  24607. };
  24608. /**
  24609. * This node can be used to define multiple outputs in a shader programs.
  24610. *
  24611. * @augments Node
  24612. */
  24613. class OutputStructNode extends Node {
  24614. static get type() {
  24615. return 'OutputStructNode';
  24616. }
  24617. /**
  24618. * Constructs a new output struct node. The constructor can be invoked with an
  24619. * arbitrary number of nodes representing the members.
  24620. *
  24621. * @param {...Node} members - A parameter list of nodes.
  24622. */
  24623. constructor( ...members ) {
  24624. super();
  24625. /**
  24626. * An array of nodes which defines the output.
  24627. *
  24628. * @type {Array<Node>}
  24629. */
  24630. this.members = members;
  24631. /**
  24632. * This flag can be used for type testing.
  24633. *
  24634. * @type {boolean}
  24635. * @readonly
  24636. * @default true
  24637. */
  24638. this.isOutputStructNode = true;
  24639. }
  24640. generateNodeType( /*builder*/ ) {
  24641. return 'OutputType';
  24642. }
  24643. generate( builder ) {
  24644. const nodeData = builder.getDataFromNode( this );
  24645. if ( nodeData.membersLayout === undefined ) {
  24646. const members = this.members;
  24647. const membersLayout = [];
  24648. for ( let i = 0; i < members.length; i ++ ) {
  24649. const name = 'm' + i;
  24650. const type = members[ i ].getNodeType( builder );
  24651. membersLayout.push( { name, type, index: i } );
  24652. }
  24653. nodeData.membersLayout = membersLayout;
  24654. nodeData.structType = builder.getOutputStructTypeFromNode( this, nodeData.membersLayout );
  24655. }
  24656. //
  24657. const propertyName = builder.getOutputStructName();
  24658. const members = this.members;
  24659. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  24660. for ( let i = 0; i < members.length; i ++ ) {
  24661. const snippet = members[ i ].build( builder );
  24662. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  24663. }
  24664. return propertyName;
  24665. }
  24666. }
  24667. /**
  24668. * TSL function for creating an output struct node.
  24669. *
  24670. * @tsl
  24671. * @function
  24672. * @param {...Node} members - A parameter list of nodes.
  24673. * @returns {OutputStructNode}
  24674. */
  24675. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  24676. /**
  24677. * Represents blending configuration.
  24678. *
  24679. * This class encapsulates all blending-related properties that control how
  24680. * a material's colors are combined with the colors already in the frame buffer.
  24681. */
  24682. class BlendMode {
  24683. /**
  24684. * Constructs a new blending configuration.
  24685. *
  24686. * @param {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending|MaterialBlending)} [blending=NormalBlending] - The blending mode.
  24687. */
  24688. constructor( blending = NormalBlending ) {
  24689. /**
  24690. * Defines the blending type.
  24691. *
  24692. * It must be set to `CustomBlending` if custom blending properties like
  24693. * {@link BlendMode#blendSrc}, {@link BlendMode#blendDst} or {@link BlendMode#blendEquation}
  24694. * should have any effect.
  24695. *
  24696. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending|MaterialBlending)}
  24697. * @default NormalBlending
  24698. */
  24699. this.blending = blending;
  24700. /**
  24701. * Defines the blending source factor.
  24702. *
  24703. * This determines how the source (incoming) fragment color is factored before being added
  24704. * to the destination (existing) fragment color in the frame buffer.
  24705. *
  24706. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  24707. * @default SrcAlphaFactor
  24708. */
  24709. this.blendSrc = SrcAlphaFactor;
  24710. /**
  24711. * Defines the blending destination factor.
  24712. *
  24713. * This determines how the destination (existing) fragment color in the frame buffer
  24714. * is factored before being combined with the source (incoming) fragment color.
  24715. *
  24716. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  24717. * @default OneMinusSrcAlphaFactor
  24718. */
  24719. this.blendDst = OneMinusSrcAlphaFactor;
  24720. /**
  24721. * Defines the blending equation.
  24722. *
  24723. * This determines how the source and destination colors are combined.
  24724. *
  24725. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  24726. * @default AddEquation
  24727. */
  24728. this.blendEquation = AddEquation;
  24729. /**
  24730. * Defines the blending source alpha factor.
  24731. *
  24732. * When set, this allows separate control of the alpha channel's source blending factor.
  24733. * If `null`, {@link BlendMode#blendSrc} is used for the alpha channel as well.
  24734. *
  24735. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  24736. * @default null
  24737. */
  24738. this.blendSrcAlpha = null;
  24739. /**
  24740. * Defines the blending destination alpha factor.
  24741. *
  24742. * When set, this allows separate control of the alpha channel's destination blending factor.
  24743. * If `null`, {@link BlendMode#blendDst} is used for the alpha channel as well.
  24744. *
  24745. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  24746. * @default null
  24747. */
  24748. this.blendDstAlpha = null;
  24749. /**
  24750. * Defines the blending equation of the alpha channel.
  24751. *
  24752. * When set, this allows separate control of the alpha channel's blending equation.
  24753. * If `null`, {@link BlendMode#blendEquation} is used for the alpha channel as well.
  24754. *
  24755. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  24756. * @default null
  24757. */
  24758. this.blendEquationAlpha = null;
  24759. /**
  24760. * Defines whether to premultiply the alpha (transparency) value.
  24761. *
  24762. * If `true`, the RGB color of the texture or material is multiplied by its alpha value.
  24763. * This is useful for transparent textures/materials where the color data
  24764. * should already include the transparency information.
  24765. *
  24766. * @type {boolean}
  24767. * @default false
  24768. */
  24769. this.premultiplyAlpha = false;
  24770. }
  24771. /**
  24772. * Copies the blending properties from the given source to this instance.
  24773. *
  24774. * @param {BlendMode} source - The blending configuration to copy from.
  24775. * @return {BlendMode} A reference to this instance.
  24776. */
  24777. copy( source ) {
  24778. this.blending = source.blending;
  24779. this.blendSrc = source.blendSrc;
  24780. this.blendDst = source.blendDst;
  24781. this.blendEquation = source.blendEquation;
  24782. this.blendSrcAlpha = source.blendSrcAlpha;
  24783. this.blendDstAlpha = source.blendDstAlpha;
  24784. this.blendEquationAlpha = source.blendEquationAlpha;
  24785. this.premultiplyAlpha = source.premultiplyAlpha;
  24786. return this;
  24787. }
  24788. /**
  24789. * Returns a clone of this blending configuration.
  24790. *
  24791. * @return {BlendMode} A new Blending instance with the same properties.
  24792. */
  24793. clone() {
  24794. return new this.constructor().copy( this );
  24795. }
  24796. }
  24797. // Predefined blend modes for MRT nodes.
  24798. const _noBlending = /**@__PURE__*/ new BlendMode( NoBlending );
  24799. const _materialBlending = /**@__PURE__*/ new BlendMode( MaterialBlending );
  24800. /**
  24801. * Returns the MRT texture index for the given name.
  24802. *
  24803. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  24804. * @param {string} name - The name of the MRT texture which index is requested.
  24805. * @return {number} The texture index.
  24806. */
  24807. function getTextureIndex( textures, name ) {
  24808. for ( let i = 0; i < textures.length; i ++ ) {
  24809. if ( textures[ i ].name === name ) {
  24810. return i;
  24811. }
  24812. }
  24813. return -1;
  24814. }
  24815. /**
  24816. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  24817. * post-processing is shown below:
  24818. * ```js
  24819. * const mrtNode = mrt( {
  24820. * output: output,
  24821. * normal: normalView
  24822. * } ) ;
  24823. * ```
  24824. * The MRT output is defined as a dictionary.
  24825. *
  24826. * @augments OutputStructNode
  24827. */
  24828. class MRTNode extends OutputStructNode {
  24829. static get type() {
  24830. return 'MRTNode';
  24831. }
  24832. /**
  24833. * Constructs a new output struct node.
  24834. *
  24835. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  24836. */
  24837. constructor( outputNodes ) {
  24838. super();
  24839. /**
  24840. * A dictionary representing the MRT outputs. The key
  24841. * is the name of the output, the value the node which produces
  24842. * the output result.
  24843. *
  24844. * @type {Object<string, Node>}
  24845. */
  24846. this.outputNodes = outputNodes;
  24847. /**
  24848. * A dictionary storing the blend modes for each output.
  24849. *
  24850. * @type {Object<string, BlendMode>}
  24851. */
  24852. this.blendModes = {
  24853. output: _materialBlending
  24854. };
  24855. /**
  24856. * This flag can be used for type testing.
  24857. *
  24858. * @type {boolean}
  24859. * @readonly
  24860. * @default true
  24861. */
  24862. this.isMRTNode = true;
  24863. }
  24864. /**
  24865. * Sets the blend mode for the given output name.
  24866. *
  24867. * @param {string} name - The name of the output.
  24868. * @param {BlendMode} blend - The blending mode.
  24869. * @return {MRTNode} The current MRT node.
  24870. */
  24871. setBlendMode( name, blend ) {
  24872. this.blendModes[ name ] = blend;
  24873. return this;
  24874. }
  24875. /**
  24876. * Returns the blend mode for the given output name.
  24877. *
  24878. * @param {string} name - The name of the output.
  24879. * @return {BlendMode} The blend mode.
  24880. */
  24881. getBlendMode( name ) {
  24882. return this.blendModes[ name ] || _noBlending;
  24883. }
  24884. /**
  24885. * Returns `true` if the MRT node has an output with the given name.
  24886. *
  24887. * @param {string} name - The name of the output.
  24888. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  24889. */
  24890. has( name ) {
  24891. return this.outputNodes[ name ] !== undefined;
  24892. }
  24893. /**
  24894. * Returns the output node for the given name.
  24895. *
  24896. * @param {string} name - The name of the output.
  24897. * @return {Node} The output node.
  24898. */
  24899. get( name ) {
  24900. return this.outputNodes[ name ];
  24901. }
  24902. /**
  24903. * Merges the outputs of the given MRT node with the outputs of this node.
  24904. *
  24905. * @param {MRTNode} mrtNode - The MRT to merge.
  24906. * @return {MRTNode} A new MRT node with merged outputs..
  24907. */
  24908. merge( mrtNode ) {
  24909. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  24910. const blendings = { ...this.blendModes, ...mrtNode.blendModes };
  24911. const mrtTarget = mrt( outputs );
  24912. mrtTarget.blendings = blendings;
  24913. return mrtTarget;
  24914. }
  24915. setup( builder ) {
  24916. const outputNodes = this.outputNodes;
  24917. const mrt = builder.renderer.getRenderTarget();
  24918. const members = [];
  24919. const textures = mrt.textures;
  24920. for ( const name in outputNodes ) {
  24921. const index = getTextureIndex( textures, name );
  24922. members[ index ] = vec4( outputNodes[ name ] );
  24923. }
  24924. this.members = members;
  24925. return super.setup( builder );
  24926. }
  24927. }
  24928. /**
  24929. * TSL function for creating a MRT node.
  24930. *
  24931. * @tsl
  24932. * @function
  24933. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  24934. * @returns {MRTNode}
  24935. */
  24936. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  24937. /**
  24938. * This node represents an operation that reinterprets the bit representation of a value
  24939. * in one type as a value in another type.
  24940. *
  24941. * @augments TempNode
  24942. */
  24943. class BitcastNode extends TempNode {
  24944. static get type() {
  24945. return 'BitcastNode';
  24946. }
  24947. /**
  24948. * Constructs a new bitcast node.
  24949. *
  24950. * @param {Node} valueNode - The value to convert.
  24951. * @param {string} conversionType - The type to convert to.
  24952. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  24953. */
  24954. constructor( valueNode, conversionType, inputType = null ) {
  24955. super();
  24956. /**
  24957. * The data to bitcast to a new type.
  24958. *
  24959. * @type {Node}
  24960. */
  24961. this.valueNode = valueNode;
  24962. /**
  24963. * The type the value will be converted to.
  24964. *
  24965. * @type {string}
  24966. */
  24967. this.conversionType = conversionType;
  24968. /**
  24969. * The expected input data type of the bitcast operation.
  24970. *
  24971. *
  24972. * @type {string}
  24973. * @default null
  24974. */
  24975. this.inputType = inputType;
  24976. /**
  24977. * This flag can be used for type testing.
  24978. *
  24979. * @type {boolean}
  24980. * @readonly
  24981. * @default true
  24982. */
  24983. this.isBitcastNode = true;
  24984. }
  24985. generateNodeType( builder ) {
  24986. // GLSL aliasing
  24987. if ( this.inputType !== null ) {
  24988. const valueType = this.valueNode.getNodeType( builder );
  24989. const valueLength = builder.getTypeLength( valueType );
  24990. return builder.getTypeFromLength( valueLength, this.conversionType );
  24991. }
  24992. return this.conversionType;
  24993. }
  24994. generate( builder ) {
  24995. const type = this.getNodeType( builder );
  24996. let inputType = '';
  24997. if ( this.inputType !== null ) {
  24998. const valueType = this.valueNode.getNodeType( builder );
  24999. const valueTypeLength = builder.getTypeLength( valueType );
  25000. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  25001. } else {
  25002. inputType = this.valueNode.getNodeType( builder );
  25003. }
  25004. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  25005. }
  25006. }
  25007. /**
  25008. * Reinterpret the bit representation of a value in one type as a value in another type.
  25009. *
  25010. * @tsl
  25011. * @function
  25012. * @param {Node | number} x - The parameter.
  25013. * @param {string} y - The new type.
  25014. * @returns {Node}
  25015. */
  25016. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  25017. /**
  25018. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  25019. *
  25020. * @tsl
  25021. * @function
  25022. * @param {Node<float>} value - The float or vector of floats to bitcast.
  25023. * @returns {BitcastNode}
  25024. */
  25025. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  25026. /**
  25027. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  25028. *
  25029. * @tsl
  25030. * @function
  25031. * @param {Node<float>} value - The float or vector of floats to bitcast.
  25032. * @returns {BitcastNode}
  25033. */
  25034. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  25035. /**
  25036. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  25037. *
  25038. * @tsl
  25039. * @function
  25040. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  25041. * @returns {BitcastNode}
  25042. */
  25043. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  25044. /**
  25045. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  25046. *
  25047. * @tsl
  25048. * @function
  25049. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  25050. * @returns {BitcastNode}
  25051. */
  25052. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  25053. const registeredBitcountFunctions = {};
  25054. /**
  25055. * This node represents an operation that counts the bits of a piece of shader data.
  25056. *
  25057. * @augments MathNode
  25058. */
  25059. class BitcountNode extends MathNode {
  25060. static get type() {
  25061. return 'BitcountNode';
  25062. }
  25063. /**
  25064. * Constructs a new math node.
  25065. *
  25066. * @param {'countTrailingZeros'|'countLeadingZeros'|'countOneBits'} method - The method name.
  25067. * @param {Node} aNode - The first input.
  25068. */
  25069. constructor( method, aNode ) {
  25070. super( method, aNode );
  25071. /**
  25072. * This flag can be used for type testing.
  25073. *
  25074. * @type {boolean}
  25075. * @readonly
  25076. * @default true
  25077. */
  25078. this.isBitcountNode = true;
  25079. }
  25080. /**
  25081. * Casts the input value of the function to an integer if necessary.
  25082. *
  25083. * @private
  25084. * @param {Node<uint>|Node<int>} inputNode - The input value.
  25085. * @param {Node<uint>} outputNode - The output value.
  25086. * @param {string} elementType - The type of the input value.
  25087. */
  25088. _resolveElementType( inputNode, outputNode, elementType ) {
  25089. if ( elementType === 'int' ) {
  25090. outputNode.assign( bitcast( inputNode, 'uint' ) );
  25091. } else {
  25092. outputNode.assign( inputNode );
  25093. }
  25094. }
  25095. _returnDataNode( inputType ) {
  25096. switch ( inputType ) {
  25097. case 'uint': {
  25098. return uint;
  25099. }
  25100. case 'int': {
  25101. return int;
  25102. }
  25103. case 'uvec2': {
  25104. return uvec2;
  25105. }
  25106. case 'uvec3': {
  25107. return uvec3;
  25108. }
  25109. case 'uvec4': {
  25110. return uvec4;
  25111. }
  25112. case 'ivec2': {
  25113. return ivec2;
  25114. }
  25115. case 'ivec3': {
  25116. return ivec3;
  25117. }
  25118. case 'ivec4': {
  25119. return ivec4;
  25120. }
  25121. }
  25122. }
  25123. /**
  25124. * Creates and registers a reusable GLSL function that emulates the behavior of countTrailingZeros.
  25125. *
  25126. * @private
  25127. * @param {string} method - The name of the function to create.
  25128. * @param {string} elementType - The type of the input value.
  25129. * @returns {Function} - The generated function
  25130. */
  25131. _createTrailingZerosBaseLayout( method, elementType ) {
  25132. const outputConvertNode = this._returnDataNode( elementType );
  25133. const fnDef = Fn( ( [ value ] ) => {
  25134. const v = uint( 0.0 );
  25135. this._resolveElementType( value, v, elementType );
  25136. const f = float( v.bitAnd( negate( v ) ) );
  25137. const uintBits = floatBitsToUint( f );
  25138. const numTrailingZeros = ( uintBits.shiftRight( 23 ) ).sub( 127 );
  25139. return outputConvertNode( numTrailingZeros );
  25140. } ).setLayout( {
  25141. name: method,
  25142. type: elementType,
  25143. inputs: [
  25144. { name: 'value', type: elementType }
  25145. ]
  25146. } );
  25147. return fnDef;
  25148. }
  25149. /**
  25150. * Creates and registers a reusable GLSL function that emulates the behavior of countLeadingZeros.
  25151. *
  25152. * @private
  25153. * @param {string} method - The name of the function to create.
  25154. * @param {string} elementType - The type of the input value.
  25155. * @returns {Function} - The generated function
  25156. */
  25157. _createLeadingZerosBaseLayout( method, elementType ) {
  25158. const outputConvertNode = this._returnDataNode( elementType );
  25159. const fnDef = Fn( ( [ value ] ) => {
  25160. If( value.equal( uint( 0 ) ), () => {
  25161. return uint( 32 );
  25162. } );
  25163. const v = uint( 0 );
  25164. const n = uint( 0 );
  25165. this._resolveElementType( value, v, elementType );
  25166. If( v.shiftRight( 16 ).equal( 0 ), () => {
  25167. n.addAssign( 16 );
  25168. v.shiftLeftAssign( 16 );
  25169. } );
  25170. If( v.shiftRight( 24 ).equal( 0 ), () => {
  25171. n.addAssign( 8 );
  25172. v.shiftLeftAssign( 8 );
  25173. } );
  25174. If( v.shiftRight( 28 ).equal( 0 ), () => {
  25175. n.addAssign( 4 );
  25176. v.shiftLeftAssign( 4 );
  25177. } );
  25178. If( v.shiftRight( 30 ).equal( 0 ), () => {
  25179. n.addAssign( 2 );
  25180. v.shiftLeftAssign( 2 );
  25181. } );
  25182. If( v.shiftRight( 31 ).equal( 0 ), () => {
  25183. n.addAssign( 1 );
  25184. } );
  25185. return outputConvertNode( n );
  25186. } ).setLayout( {
  25187. name: method,
  25188. type: elementType,
  25189. inputs: [
  25190. { name: 'value', type: elementType }
  25191. ]
  25192. } );
  25193. return fnDef;
  25194. }
  25195. /**
  25196. * Creates and registers a reusable GLSL function that emulates the behavior of countOneBits.
  25197. *
  25198. * @private
  25199. * @param {string} method - The name of the function to create.
  25200. * @param {string} elementType - The type of the input value.
  25201. * @returns {Function} - The generated function
  25202. */
  25203. _createOneBitsBaseLayout( method, elementType ) {
  25204. const outputConvertNode = this._returnDataNode( elementType );
  25205. const fnDef = Fn( ( [ value ] ) => {
  25206. const v = uint( 0.0 );
  25207. this._resolveElementType( value, v, elementType );
  25208. v.assign( v.sub( v.shiftRight( uint( 1 ) ).bitAnd( uint( 0x55555555 ) ) ) );
  25209. v.assign( v.bitAnd( uint( 0x33333333 ) ).add( v.shiftRight( uint( 2 ) ).bitAnd( uint( 0x33333333 ) ) ) );
  25210. const numBits = v.add( v.shiftRight( uint( 4 ) ) ).bitAnd( uint( 0xF0F0F0F ) ).mul( uint( 0x1010101 ) ).shiftRight( uint( 24 ) );
  25211. return outputConvertNode( numBits );
  25212. } ).setLayout( {
  25213. name: method,
  25214. type: elementType,
  25215. inputs: [
  25216. { name: 'value', type: elementType }
  25217. ]
  25218. } );
  25219. return fnDef;
  25220. }
  25221. /**
  25222. * Creates and registers a reusable GLSL function that emulates the behavior of the specified bitcount function.
  25223. * including considerations for component-wise bitcounts on vector type inputs.
  25224. *
  25225. * @private
  25226. * @param {string} method - The name of the function to create.
  25227. * @param {string} inputType - The type of the input value.
  25228. * @param {number} typeLength - The vec length of the input value.
  25229. * @param {Function} baseFn - The base function that operates on an individual component of the vector.
  25230. * @returns {Function} - The alias function for the specified bitcount method.
  25231. */
  25232. _createMainLayout( method, inputType, typeLength, baseFn ) {
  25233. const outputConvertNode = this._returnDataNode( inputType );
  25234. const fnDef = Fn( ( [ value ] ) => {
  25235. if ( typeLength === 1 ) {
  25236. return outputConvertNode( baseFn( value ) );
  25237. } else {
  25238. const vec = outputConvertNode( 0 );
  25239. const components = [ 'x', 'y', 'z', 'w' ];
  25240. for ( let i = 0; i < typeLength; i ++ ) {
  25241. const component = components[ i ];
  25242. vec[ component ].assign( baseFn( value[ component ] ) );
  25243. }
  25244. return vec;
  25245. }
  25246. } ).setLayout( {
  25247. name: method,
  25248. type: inputType,
  25249. inputs: [
  25250. { name: 'value', type: inputType }
  25251. ]
  25252. } );
  25253. return fnDef;
  25254. }
  25255. setup( builder ) {
  25256. const { method, aNode } = this;
  25257. const { renderer } = builder;
  25258. if ( renderer.backend.isWebGPUBackend ) {
  25259. // use built-in WGSL functions for WebGPU
  25260. return super.setup( builder );
  25261. }
  25262. const inputType = this.getInputType( builder );
  25263. const elementType = builder.getElementType( inputType );
  25264. const typeLength = builder.getTypeLength( inputType );
  25265. const baseMethod = `${method}_base_${elementType}`;
  25266. const newMethod = `${method}_${inputType}`;
  25267. let baseFn = registeredBitcountFunctions[ baseMethod ];
  25268. if ( baseFn === undefined ) {
  25269. switch ( method ) {
  25270. case BitcountNode.COUNT_LEADING_ZEROS: {
  25271. baseFn = this._createLeadingZerosBaseLayout( baseMethod, elementType );
  25272. break;
  25273. }
  25274. case BitcountNode.COUNT_TRAILING_ZEROS: {
  25275. baseFn = this._createTrailingZerosBaseLayout( baseMethod, elementType );
  25276. break;
  25277. }
  25278. case BitcountNode.COUNT_ONE_BITS: {
  25279. baseFn = this._createOneBitsBaseLayout( baseMethod, elementType );
  25280. break;
  25281. }
  25282. }
  25283. registeredBitcountFunctions[ baseMethod ] = baseFn;
  25284. }
  25285. let fn = registeredBitcountFunctions[ newMethod ];
  25286. if ( fn === undefined ) {
  25287. fn = this._createMainLayout( newMethod, inputType, typeLength, baseFn );
  25288. registeredBitcountFunctions[ newMethod ] = fn;
  25289. }
  25290. const output = Fn( () => {
  25291. return fn(
  25292. aNode,
  25293. );
  25294. } );
  25295. return output();
  25296. }
  25297. }
  25298. BitcountNode.COUNT_TRAILING_ZEROS = 'countTrailingZeros';
  25299. BitcountNode.COUNT_LEADING_ZEROS = 'countLeadingZeros';
  25300. BitcountNode.COUNT_ONE_BITS = 'countOneBits';
  25301. /**
  25302. * Finds the number of consecutive 0 bits from the least significant bit of the input value,
  25303. * which is also the index of the least significant bit of the input value.
  25304. *
  25305. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  25306. *
  25307. * @tsl
  25308. * @function
  25309. * @param {Node | number} x - The input value.
  25310. * @returns {Node}
  25311. */
  25312. const countTrailingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_TRAILING_ZEROS ).setParameterLength( 1 );
  25313. /**
  25314. * Finds the number of consecutive 0 bits starting from the most significant bit of the input value.
  25315. *
  25316. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  25317. *
  25318. * @tsl
  25319. * @function
  25320. * @param {Node | number} x - The input value.
  25321. * @returns {Node}
  25322. */
  25323. const countLeadingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_LEADING_ZEROS ).setParameterLength( 1 );
  25324. /**
  25325. * Finds the number of '1' bits set in the input value
  25326. *
  25327. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  25328. *
  25329. * @tsl
  25330. * @function
  25331. * @returns {Node}
  25332. */
  25333. const countOneBits = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_ONE_BITS ).setParameterLength( 1 );
  25334. /**
  25335. * Generates a hash value in the range `[0, 1]` from the given seed.
  25336. *
  25337. * @tsl
  25338. * @function
  25339. * @param {Node<float>} seed - The seed.
  25340. * @return {Node<float>} The hash value.
  25341. */
  25342. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  25343. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  25344. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  25345. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  25346. const result = word.shiftRight( 22 ).bitXor( word );
  25347. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  25348. } );
  25349. /**
  25350. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  25351. * The corners are mapped to `0` and the center to `1`.
  25352. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25353. *
  25354. * @tsl
  25355. * @function
  25356. * @param {Node<float>} x - The value to remap.
  25357. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  25358. * @return {Node<float>} The remapped value.
  25359. */
  25360. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  25361. /**
  25362. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  25363. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  25364. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25365. *
  25366. * @tsl
  25367. * @function
  25368. * @param {Node<float>} x - The value to remap.
  25369. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  25370. * @return {Node<float>} The remapped value.
  25371. */
  25372. 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 ) );
  25373. /**
  25374. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  25375. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  25376. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25377. *
  25378. * @tsl
  25379. * @function
  25380. * @param {Node<float>} x - The value to remap.
  25381. * @param {Node<float>} a - First control parameter.
  25382. * @param {Node<float>} b - Second control parameter.
  25383. * @return {Node<float>} The remapped value.
  25384. */
  25385. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  25386. /**
  25387. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  25388. * Reference: {@link https://iquilezles.org/articles/functions/}.
  25389. *
  25390. * @tsl
  25391. * @function
  25392. * @param {Node<float>} x - The value to compute the sin for.
  25393. * @param {Node<float>} k - Controls the amount of bounces.
  25394. * @return {Node<float>} The result value.
  25395. */
  25396. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  25397. /**
  25398. * This node represents an operation that packs floating-point values of a vector into an unsigned 32-bit integer
  25399. *
  25400. * @augments TempNode
  25401. */
  25402. class PackFloatNode extends TempNode {
  25403. static get type() {
  25404. return 'PackFloatNode';
  25405. }
  25406. /**
  25407. *
  25408. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  25409. * @param {Node} vectorNode - The vector node to be packed
  25410. */
  25411. constructor( encoding, vectorNode ) {
  25412. super();
  25413. /**
  25414. * The vector to be packed.
  25415. *
  25416. * @type {Node}
  25417. */
  25418. this.vectorNode = vectorNode;
  25419. /**
  25420. * The numeric encoding.
  25421. *
  25422. * @type {string}
  25423. */
  25424. this.encoding = encoding;
  25425. /**
  25426. * This flag can be used for type testing.
  25427. *
  25428. * @type {boolean}
  25429. * @readonly
  25430. * @default true
  25431. */
  25432. this.isPackFloatNode = true;
  25433. }
  25434. generateNodeType() {
  25435. return 'uint';
  25436. }
  25437. generate( builder ) {
  25438. const inputType = this.vectorNode.getNodeType( builder );
  25439. return `${ builder.getFloatPackingMethod( this.encoding ) }(${ this.vectorNode.build( builder, inputType )})`;
  25440. }
  25441. }
  25442. /**
  25443. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  25444. * round(clamp(c, -1, +1) * 32767.0)
  25445. *
  25446. * @tsl
  25447. * @function
  25448. * @param {Node<vec2>} value - The 2-component vector to be packed
  25449. * @returns {Node}
  25450. */
  25451. const packSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'snorm' ).setParameterLength( 1 );
  25452. /**
  25453. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  25454. * round(clamp(c, 0, +1) * 65535.0)
  25455. *
  25456. * @tsl
  25457. * @function
  25458. * @param {Node<vec2>} value - The 2-component vector to be packed
  25459. * @returns {Node}
  25460. */
  25461. const packUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'unorm' ).setParameterLength( 1 );
  25462. /**
  25463. * Converts each component of the vec2 to 16-bit floating-point values. The results are packed into a single unsigned integer.
  25464. *
  25465. * @tsl
  25466. * @function
  25467. * @param {Node<vec2>} value - The 2-component vector to be packed
  25468. * @returns {Node}
  25469. */
  25470. const packHalf2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'float16' ).setParameterLength( 1 );
  25471. /**
  25472. * This node represents an operation that unpacks values from a 32-bit unsigned integer, reinterpreting the results as a floating-point vector
  25473. *
  25474. * @augments TempNode
  25475. */
  25476. class UnpackFloatNode extends TempNode {
  25477. static get type() {
  25478. return 'UnpackFloatNode';
  25479. }
  25480. /**
  25481. *
  25482. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the integer values are mapped to the float range
  25483. * @param {Node} uintNode - The uint node to be unpacked
  25484. */
  25485. constructor( encoding, uintNode ) {
  25486. super();
  25487. /**
  25488. * The unsigned integer to be unpacked.
  25489. *
  25490. * @type {Node}
  25491. */
  25492. this.uintNode = uintNode;
  25493. /**
  25494. * The numeric encoding.
  25495. *
  25496. * @type {string}
  25497. */
  25498. this.encoding = encoding;
  25499. /**
  25500. * This flag can be used for type testing.
  25501. *
  25502. * @type {boolean}
  25503. * @readonly
  25504. * @default true
  25505. */
  25506. this.isUnpackFloatNode = true;
  25507. }
  25508. generateNodeType() {
  25509. return 'vec2';
  25510. }
  25511. generate( builder ) {
  25512. const inputType = this.uintNode.getNodeType( builder );
  25513. return `${ builder.getFloatUnpackingMethod( this.encoding ) }(${ this.uintNode.build( builder, inputType )})`;
  25514. }
  25515. }
  25516. /**
  25517. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized signed integers. Returns a vec2 with both values.
  25518. *
  25519. * @tsl
  25520. * @function
  25521. * @param {Node<uint>} value - The unsigned integer to be unpacked
  25522. * @returns {Node}
  25523. */
  25524. const unpackSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'snorm' ).setParameterLength( 1 );
  25525. /**
  25526. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized unsigned integers. Returns a vec2 with both values.
  25527. *
  25528. * @tsl
  25529. * @function
  25530. * @param {Node<uint>} value - The unsigned integer to be unpacked
  25531. * @returns {Node}
  25532. */
  25533. const unpackUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'unorm' ).setParameterLength( 1 );
  25534. /**
  25535. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as 16-bit floating-point numbers. Returns a vec2 with both values.
  25536. *
  25537. * @tsl
  25538. * @function
  25539. * @param {Node<uint>} value - The unsigned integer to be unpacked
  25540. * @returns {Node}
  25541. */
  25542. const unpackHalf2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'float16' ).setParameterLength( 1 );
  25543. // https://github.com/cabbibo/glsl-tri-noise-3d
  25544. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  25545. return x.fract().sub( .5 ).abs();
  25546. } ).setLayout( {
  25547. name: 'tri',
  25548. type: 'float',
  25549. inputs: [
  25550. { name: 'x', type: 'float' }
  25551. ]
  25552. } );
  25553. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  25554. 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. ) ) ) ) );
  25555. } ).setLayout( {
  25556. name: 'tri3',
  25557. type: 'vec3',
  25558. inputs: [
  25559. { name: 'p', type: 'vec3' }
  25560. ]
  25561. } );
  25562. /**
  25563. * Generates a noise value from the given position, speed and time parameters.
  25564. *
  25565. * @tsl
  25566. * @function
  25567. * @param {Node<vec3>} position - The position.
  25568. * @param {Node<float>} speed - The speed.
  25569. * @param {Node<float>} time - The time.
  25570. * @return {Node<float>} The generated noise.
  25571. */
  25572. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  25573. const p = vec3( position ).toVar();
  25574. const z = float( 1.4 ).toVar();
  25575. const rz = float( 0.0 ).toVar();
  25576. const bp = vec3( p ).toVar();
  25577. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  25578. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  25579. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  25580. bp.mulAssign( 1.8 );
  25581. z.mulAssign( 1.5 );
  25582. p.mulAssign( 1.2 );
  25583. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  25584. rz.addAssign( t.div( z ) );
  25585. bp.addAssign( 0.14 );
  25586. } );
  25587. return rz;
  25588. } ).setLayout( {
  25589. name: 'triNoise3D',
  25590. type: 'float',
  25591. inputs: [
  25592. { name: 'position', type: 'vec3' },
  25593. { name: 'speed', type: 'float' },
  25594. { name: 'time', type: 'float' }
  25595. ]
  25596. } );
  25597. /**
  25598. * This class allows to define multiple overloaded versions
  25599. * of the same function. Depending on the parameters of the function
  25600. * call, the node picks the best-fit overloaded version.
  25601. *
  25602. * @augments Node
  25603. */
  25604. class FunctionOverloadingNode extends Node {
  25605. static get type() {
  25606. return 'FunctionOverloadingNode';
  25607. }
  25608. /**
  25609. * Constructs a new function overloading node.
  25610. *
  25611. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  25612. * @param {...Node} parametersNodes - A list of parameter nodes.
  25613. */
  25614. constructor( functionNodes = [], ...parametersNodes ) {
  25615. super();
  25616. /**
  25617. * Array of `Fn` function definitions.
  25618. *
  25619. * @type {Array<Function>}
  25620. */
  25621. this.functionNodes = functionNodes;
  25622. /**
  25623. * A list of parameter nodes.
  25624. *
  25625. * @type {Array<Node>}
  25626. */
  25627. this.parametersNodes = parametersNodes;
  25628. /**
  25629. * The selected overloaded function call.
  25630. *
  25631. * @private
  25632. * @type {ShaderCallNodeInternal}
  25633. */
  25634. this._candidateFn = null;
  25635. /**
  25636. * This node is marked as global.
  25637. *
  25638. * @type {boolean}
  25639. * @default true
  25640. */
  25641. this.global = true;
  25642. }
  25643. /**
  25644. * This method is overwritten since the node type is inferred from
  25645. * the function's return type.
  25646. *
  25647. * @param {NodeBuilder} builder - The current node builder.
  25648. * @return {string} The node type.
  25649. */
  25650. generateNodeType( builder ) {
  25651. const candidateFn = this.getCandidateFn( builder );
  25652. return candidateFn.shaderNode.layout.type;
  25653. }
  25654. /**
  25655. * Returns the candidate function for the current parameters.
  25656. *
  25657. * @param {NodeBuilder} builder - The current node builder.
  25658. * @return {FunctionNode} The candidate function.
  25659. */
  25660. getCandidateFn( builder ) {
  25661. const params = this.parametersNodes;
  25662. let candidateFn = this._candidateFn;
  25663. if ( candidateFn === null ) {
  25664. let bestCandidateFn = null;
  25665. let bestScore = -1;
  25666. for ( const functionNode of this.functionNodes ) {
  25667. const shaderNode = functionNode.shaderNode;
  25668. const layout = shaderNode.layout;
  25669. if ( layout === null ) {
  25670. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  25671. }
  25672. const inputs = layout.inputs;
  25673. if ( params.length === inputs.length ) {
  25674. let currentScore = 0;
  25675. for ( let i = 0; i < params.length; i ++ ) {
  25676. const param = params[ i ];
  25677. const input = inputs[ i ];
  25678. if ( param.getNodeType( builder ) === input.type ) {
  25679. currentScore ++;
  25680. }
  25681. }
  25682. if ( currentScore > bestScore ) {
  25683. bestCandidateFn = functionNode;
  25684. bestScore = currentScore;
  25685. }
  25686. }
  25687. }
  25688. this._candidateFn = candidateFn = bestCandidateFn;
  25689. }
  25690. return candidateFn;
  25691. }
  25692. /**
  25693. * Sets up the node for the current parameters.
  25694. *
  25695. * @param {NodeBuilder} builder - The current node builder.
  25696. * @return {Node} The setup node.
  25697. */
  25698. setup( builder ) {
  25699. const candidateFn = this.getCandidateFn( builder );
  25700. return candidateFn( ...this.parametersNodes );
  25701. }
  25702. }
  25703. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  25704. /**
  25705. * TSL function for creating a function overloading node.
  25706. *
  25707. * @tsl
  25708. * @function
  25709. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  25710. * @returns {FunctionOverloadingNode}
  25711. */
  25712. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  25713. /**
  25714. * Represents the elapsed time in seconds.
  25715. *
  25716. * @tsl
  25717. * @type {UniformNode<float>}
  25718. */
  25719. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  25720. /**
  25721. * Represents the delta time in seconds.
  25722. *
  25723. * @tsl
  25724. * @type {UniformNode<float>}
  25725. */
  25726. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  25727. /**
  25728. * Represents the current frame ID.
  25729. *
  25730. * @tsl
  25731. * @type {UniformNode<uint>}
  25732. */
  25733. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  25734. /**
  25735. * Generates a sine wave oscillation based on a timer.
  25736. *
  25737. * @tsl
  25738. * @function
  25739. * @param {Node<float>} t - The timer to generate the oscillation with.
  25740. * @return {Node<float>} The oscillation node.
  25741. */
  25742. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  25743. /**
  25744. * Generates a square wave oscillation based on a timer.
  25745. *
  25746. * @tsl
  25747. * @function
  25748. * @param {Node<float>} t - The timer to generate the oscillation with.
  25749. * @return {Node<float>} The oscillation node.
  25750. */
  25751. const oscSquare = ( t = time ) => t.fract().round();
  25752. /**
  25753. * Generates a triangle wave oscillation based on a timer.
  25754. *
  25755. * @tsl
  25756. * @function
  25757. * @param {Node<float>} t - The timer to generate the oscillation with.
  25758. * @return {Node<float>} The oscillation node.
  25759. */
  25760. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  25761. /**
  25762. * Generates a sawtooth wave oscillation based on a timer.
  25763. *
  25764. * @tsl
  25765. * @function
  25766. * @param {Node<float>} t - The timer to generate the oscillation with.
  25767. * @return {Node<float>} The oscillation node.
  25768. */
  25769. const oscSawtooth = ( t = time ) => t.fract();
  25770. /**
  25771. * Replaces the default UV coordinates used in texture lookups.
  25772. *
  25773. * ```js
  25774. *material.contextNode = replaceDefaultUV( ( textureNode ) => {
  25775. *
  25776. * // ...
  25777. * return customUVCoordinates;
  25778. *
  25779. *} );
  25780. *```
  25781. *
  25782. * @tsl
  25783. * @function
  25784. * @param {function(Node):Node<vec2>|Node<vec2>} callback - A callback that receives the texture node
  25785. * and must return the new uv coordinates.
  25786. * @param {Node} [node=null] - An optional node to which the context will be applied.
  25787. * @return {ContextNode} A context node that replaces the default UV coordinates.
  25788. */
  25789. function replaceDefaultUV( callback, node = null ) {
  25790. const getUV = typeof callback === 'function' ? callback : () => callback;
  25791. return context( node, { getUV } );
  25792. }
  25793. /**
  25794. * Rotates the given uv coordinates around a center point
  25795. *
  25796. * @tsl
  25797. * @function
  25798. * @param {Node<vec2>} uv - The uv coordinates.
  25799. * @param {Node<float>} rotation - The rotation defined in radians.
  25800. * @param {Node<vec2>} center - The center of rotation
  25801. * @return {Node<vec2>} The rotated uv coordinates.
  25802. */
  25803. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  25804. return rotate( uv.sub( center ), rotation ).add( center );
  25805. } );
  25806. /**
  25807. * Applies a spherical warping effect to the given uv coordinates.
  25808. *
  25809. * @tsl
  25810. * @function
  25811. * @param {Node<vec2>} uv - The uv coordinates.
  25812. * @param {Node<float>} strength - The strength of the effect.
  25813. * @param {Node<vec2>} center - The center point
  25814. * @return {Node<vec2>} The updated uv coordinates.
  25815. */
  25816. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  25817. const delta = uv.sub( center );
  25818. const delta2 = delta.dot( delta );
  25819. const delta4 = delta2.mul( delta2 );
  25820. const deltaOffset = delta4.mul( strength );
  25821. return uv.add( delta.mul( deltaOffset ) );
  25822. } );
  25823. /**
  25824. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  25825. * oriented always towards the camera.
  25826. *
  25827. * ```js
  25828. * material.vertexNode = billboarding();
  25829. * ```
  25830. *
  25831. * @tsl
  25832. * @function
  25833. * @param {Object} config - The configuration object.
  25834. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  25835. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  25836. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  25837. * @return {Node<vec3>} The updated vertex position in clip space.
  25838. */
  25839. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  25840. let worldMatrix;
  25841. if ( position !== null ) {
  25842. worldMatrix = modelWorldMatrix.toVar();
  25843. worldMatrix[ 3 ][ 0 ] = position.x;
  25844. worldMatrix[ 3 ][ 1 ] = position.y;
  25845. worldMatrix[ 3 ][ 2 ] = position.z;
  25846. } else {
  25847. worldMatrix = modelWorldMatrix;
  25848. }
  25849. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  25850. if ( defined( horizontal ) ) {
  25851. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  25852. modelViewMatrix[ 0 ][ 1 ] = 0;
  25853. modelViewMatrix[ 0 ][ 2 ] = 0;
  25854. }
  25855. if ( defined( vertical ) ) {
  25856. modelViewMatrix[ 1 ][ 0 ] = 0;
  25857. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  25858. modelViewMatrix[ 1 ][ 2 ] = 0;
  25859. }
  25860. modelViewMatrix[ 2 ][ 0 ] = 0;
  25861. modelViewMatrix[ 2 ][ 1 ] = 0;
  25862. modelViewMatrix[ 2 ][ 2 ] = 1;
  25863. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  25864. } );
  25865. /**
  25866. * A special version of a screen uv function that involves a depth comparison
  25867. * when computing the final uvs. The function mitigates visual errors when
  25868. * using viewport texture nodes for refraction purposes. Without this function
  25869. * objects in front of a refractive surface might appear on the refractive surface
  25870. * which is incorrect.
  25871. *
  25872. * @tsl
  25873. * @function
  25874. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  25875. * @return {Node<vec2>} The update uv coordinates.
  25876. */
  25877. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  25878. const depth = linearDepth();
  25879. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  25880. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  25881. return finalUV;
  25882. } );
  25883. /**
  25884. * TSL function for computing texture coordinates for animated sprite sheets.
  25885. *
  25886. * ```js
  25887. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  25888. *
  25889. * material.colorNode = texture( spriteSheet, uvNode );
  25890. * ```
  25891. *
  25892. * @tsl
  25893. * @function
  25894. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  25895. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  25896. * @param {?Node<float>} [frameNode=float(0)] - The node that defines the current frame/sprite.
  25897. * @returns {Node<vec2>}
  25898. */
  25899. const spritesheetUV = /*@__PURE__*/ Fn( ( [ countNode, uvNode = uv$1(), frameNode = float( 0 ) ] ) => {
  25900. const width = countNode.x;
  25901. const height = countNode.y;
  25902. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  25903. const column = frameNum.mod( width );
  25904. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  25905. const scale = countNode.reciprocal();
  25906. const uvFrameOffset = vec2( column, row );
  25907. return uvNode.add( uvFrameOffset ).mul( scale );
  25908. } );
  25909. /**
  25910. * TSL function for creating a triplanar textures node.
  25911. *
  25912. * Can be used for triplanar texture mapping.
  25913. *
  25914. * ```js
  25915. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  25916. * ```
  25917. *
  25918. * @tsl
  25919. * @function
  25920. * @param {Node} textureXNode - First texture node.
  25921. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  25922. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  25923. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  25924. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  25925. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  25926. * @returns {Node<vec4>}
  25927. */
  25928. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  25929. // Reference: https://github.com/keijiro/StandardTriplanar
  25930. // Blending factor of triplanar mapping
  25931. let bf = normalNode.abs().normalize();
  25932. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  25933. // Triplanar mapping
  25934. const tx = positionNode.yz.mul( scaleNode );
  25935. const ty = positionNode.zx.mul( scaleNode );
  25936. const tz = positionNode.xy.mul( scaleNode );
  25937. // Base color
  25938. const textureX = textureXNode.value;
  25939. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  25940. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  25941. const cx = texture( textureX, tx ).mul( bf.x );
  25942. const cy = texture( textureY, ty ).mul( bf.y );
  25943. const cz = texture( textureZ, tz ).mul( bf.z );
  25944. return add( cx, cy, cz );
  25945. } );
  25946. /**
  25947. * TSL function for creating a triplanar textures node.
  25948. *
  25949. * @tsl
  25950. * @function
  25951. * @param {Node} textureXNode - First texture node.
  25952. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  25953. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  25954. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  25955. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  25956. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  25957. * @returns {Node<vec4>}
  25958. */
  25959. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  25960. const _reflectorPlane = new Plane();
  25961. const _normal = new Vector3();
  25962. const _reflectorWorldPosition = new Vector3();
  25963. const _cameraWorldPosition = new Vector3();
  25964. const _rotationMatrix = new Matrix4();
  25965. const _lookAtPosition = new Vector3( 0, 0, -1 );
  25966. const clipPlane = new Vector4();
  25967. const _view = new Vector3();
  25968. const _target = new Vector3();
  25969. const _q = new Vector4();
  25970. const _size$2 = new Vector2();
  25971. const _defaultRT = new RenderTarget();
  25972. const _defaultUV = screenUV.flipX();
  25973. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  25974. let _inReflector = false;
  25975. /**
  25976. * This node can be used to implement mirror-like flat reflective surfaces.
  25977. *
  25978. * ```js
  25979. * const groundReflector = reflector();
  25980. * material.colorNode = groundReflector;
  25981. *
  25982. * const plane = new Mesh( geometry, material );
  25983. * plane.add( groundReflector.target );
  25984. * ```
  25985. *
  25986. * @augments TextureNode
  25987. */
  25988. class ReflectorNode extends TextureNode {
  25989. static get type() {
  25990. return 'ReflectorNode';
  25991. }
  25992. /**
  25993. * Constructs a new reflector node.
  25994. *
  25995. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25996. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25997. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  25998. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25999. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  26000. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  26001. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  26002. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  26003. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  26004. */
  26005. constructor( parameters = {} ) {
  26006. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  26007. /**
  26008. * A reference to the internal reflector base node which holds the actual implementation.
  26009. *
  26010. * @private
  26011. * @type {ReflectorBaseNode}
  26012. * @default ReflectorBaseNode
  26013. */
  26014. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  26015. /**
  26016. * A reference to the internal depth node.
  26017. *
  26018. * @private
  26019. * @type {?Node}
  26020. * @default null
  26021. */
  26022. this._depthNode = null;
  26023. this.setUpdateMatrix( false );
  26024. }
  26025. /**
  26026. * A reference to the internal reflector node.
  26027. *
  26028. * @type {ReflectorBaseNode}
  26029. */
  26030. get reflector() {
  26031. return this._reflectorBaseNode;
  26032. }
  26033. /**
  26034. * A reference to 3D object the reflector is linked to.
  26035. *
  26036. * @type {Object3D}
  26037. */
  26038. get target() {
  26039. return this._reflectorBaseNode.target;
  26040. }
  26041. /**
  26042. * Returns a node representing the mirror's depth. That can be used
  26043. * to implement more advanced reflection effects like distance attenuation.
  26044. *
  26045. * @return {Node} The depth node.
  26046. */
  26047. getDepthNode() {
  26048. if ( this._depthNode === null ) {
  26049. if ( this._reflectorBaseNode.depth !== true ) {
  26050. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  26051. }
  26052. this._depthNode = new ReflectorNode( {
  26053. defaultTexture: _defaultRT.depthTexture,
  26054. reflector: this._reflectorBaseNode
  26055. } );
  26056. }
  26057. return this._depthNode;
  26058. }
  26059. setup( builder ) {
  26060. // ignore if used in post-processing
  26061. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  26062. return super.setup( builder );
  26063. }
  26064. clone() {
  26065. const newNode = new this.constructor( this.reflectorNode );
  26066. newNode.uvNode = this.uvNode;
  26067. newNode.levelNode = this.levelNode;
  26068. newNode.biasNode = this.biasNode;
  26069. newNode.sampler = this.sampler;
  26070. newNode.depthNode = this.depthNode;
  26071. newNode.compareNode = this.compareNode;
  26072. newNode.gradNode = this.gradNode;
  26073. newNode.offsetNode = this.offsetNode;
  26074. newNode._reflectorBaseNode = this._reflectorBaseNode;
  26075. return newNode;
  26076. }
  26077. /**
  26078. * Frees internal resources. Should be called when the node is no longer in use.
  26079. */
  26080. dispose() {
  26081. super.dispose();
  26082. this._reflectorBaseNode.dispose();
  26083. }
  26084. }
  26085. /**
  26086. * Holds the actual implementation of the reflector.
  26087. *
  26088. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  26089. * in `ReflectorNode`, see #29619.
  26090. *
  26091. * @private
  26092. * @augments Node
  26093. */
  26094. class ReflectorBaseNode extends Node {
  26095. static get type() {
  26096. return 'ReflectorBaseNode';
  26097. }
  26098. /**
  26099. * Constructs a new reflector base node.
  26100. *
  26101. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  26102. * @param {Object} [parameters={}] - An object holding configuration parameters.
  26103. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  26104. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  26105. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  26106. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  26107. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  26108. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  26109. */
  26110. constructor( textureNode, parameters = {} ) {
  26111. super();
  26112. const {
  26113. target = new Object3D(),
  26114. resolutionScale = 1,
  26115. generateMipmaps = false,
  26116. bounces = true,
  26117. depth = false,
  26118. samples = 0
  26119. } = parameters;
  26120. /**
  26121. * Represents the rendered reflections as a texture node.
  26122. *
  26123. * @type {TextureNode}
  26124. */
  26125. this.textureNode = textureNode;
  26126. /**
  26127. * The 3D object the reflector is linked to.
  26128. *
  26129. * @type {Object3D}
  26130. * @default {new Object3D()}
  26131. */
  26132. this.target = target;
  26133. /**
  26134. * The resolution scale.
  26135. *
  26136. * @type {number}
  26137. * @default {1}
  26138. */
  26139. this.resolutionScale = resolutionScale;
  26140. if ( parameters.resolution !== undefined ) {
  26141. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  26142. this.resolutionScale = parameters.resolution;
  26143. }
  26144. /**
  26145. * Whether mipmaps should be generated or not.
  26146. *
  26147. * @type {boolean}
  26148. * @default {false}
  26149. */
  26150. this.generateMipmaps = generateMipmaps;
  26151. /**
  26152. * Whether reflectors can render other reflector nodes or not.
  26153. *
  26154. * @type {boolean}
  26155. * @default {true}
  26156. */
  26157. this.bounces = bounces;
  26158. /**
  26159. * Whether depth data should be generated or not.
  26160. *
  26161. * @type {boolean}
  26162. * @default {false}
  26163. */
  26164. this.depth = depth;
  26165. /**
  26166. * The number of anti-aliasing samples for the render-target
  26167. *
  26168. * @type {number}
  26169. * @default {0}
  26170. */
  26171. this.samples = samples;
  26172. /**
  26173. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  26174. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  26175. *
  26176. * @type {string}
  26177. * @default 'render'
  26178. */
  26179. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  26180. /**
  26181. * Weak map for managing virtual cameras.
  26182. *
  26183. * @type {WeakMap<Camera, Camera>}
  26184. */
  26185. this.virtualCameras = new WeakMap();
  26186. /**
  26187. * Weak map for managing render targets.
  26188. *
  26189. * @type {Map<Camera, RenderTarget>}
  26190. */
  26191. this.renderTargets = new Map();
  26192. /**
  26193. * Force render even if reflector is facing away from camera.
  26194. *
  26195. * @type {boolean}
  26196. * @default {false}
  26197. */
  26198. this.forceUpdate = false;
  26199. /**
  26200. * Whether the reflector has been rendered or not.
  26201. *
  26202. * When the reflector is facing away from the camera,
  26203. * this flag is set to `false` and the texture will be empty(black).
  26204. *
  26205. * @type {boolean}
  26206. * @default {false}
  26207. */
  26208. this.hasOutput = false;
  26209. }
  26210. /**
  26211. * Updates the resolution of the internal render target.
  26212. *
  26213. * @private
  26214. * @param {RenderTarget} renderTarget - The render target to resize.
  26215. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  26216. */
  26217. _updateResolution( renderTarget, renderer ) {
  26218. const resolution = this.resolutionScale;
  26219. renderer.getDrawingBufferSize( _size$2 );
  26220. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  26221. }
  26222. setup( builder ) {
  26223. this._updateResolution( _defaultRT, builder.renderer );
  26224. return super.setup( builder );
  26225. }
  26226. /**
  26227. * Frees internal resources. Should be called when the node is no longer in use.
  26228. */
  26229. dispose() {
  26230. super.dispose();
  26231. for ( const renderTarget of this.renderTargets.values() ) {
  26232. renderTarget.dispose();
  26233. }
  26234. }
  26235. /**
  26236. * Returns a virtual camera for the given camera. The virtual camera is used to
  26237. * render the scene from the reflector's view so correct reflections can be produced.
  26238. *
  26239. * @param {Camera} camera - The scene's camera.
  26240. * @return {Camera} The corresponding virtual camera.
  26241. */
  26242. getVirtualCamera( camera ) {
  26243. let virtualCamera = this.virtualCameras.get( camera );
  26244. if ( virtualCamera === undefined ) {
  26245. virtualCamera = camera.clone();
  26246. this.virtualCameras.set( camera, virtualCamera );
  26247. }
  26248. return virtualCamera;
  26249. }
  26250. /**
  26251. * Returns a render target for the given camera. The reflections are rendered
  26252. * into this render target.
  26253. *
  26254. * @param {Camera} camera - The scene's camera.
  26255. * @return {RenderTarget} The render target.
  26256. */
  26257. getRenderTarget( camera ) {
  26258. let renderTarget = this.renderTargets.get( camera );
  26259. if ( renderTarget === undefined ) {
  26260. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  26261. if ( this.generateMipmaps === true ) {
  26262. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  26263. renderTarget.texture.generateMipmaps = true;
  26264. }
  26265. if ( this.depth === true ) {
  26266. renderTarget.depthTexture = new DepthTexture();
  26267. }
  26268. this.renderTargets.set( camera, renderTarget );
  26269. }
  26270. return renderTarget;
  26271. }
  26272. updateBefore( frame ) {
  26273. if ( this.bounces === false && _inReflector ) return false;
  26274. _inReflector = true;
  26275. const { scene, camera, renderer, material } = frame;
  26276. const { target } = this;
  26277. const virtualCamera = this.getVirtualCamera( camera );
  26278. const renderTarget = this.getRenderTarget( virtualCamera );
  26279. renderer.getDrawingBufferSize( _size$2 );
  26280. this._updateResolution( renderTarget, renderer );
  26281. //
  26282. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  26283. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  26284. _rotationMatrix.extractRotation( target.matrixWorld );
  26285. _normal.set( 0, 0, 1 );
  26286. _normal.applyMatrix4( _rotationMatrix );
  26287. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  26288. // Avoid rendering when reflector is facing away unless forcing an update
  26289. const isFacingAway = _view.dot( _normal ) > 0;
  26290. let needsClear = false;
  26291. if ( isFacingAway === true && this.forceUpdate === false ) {
  26292. if ( this.hasOutput === false ) {
  26293. _inReflector = false;
  26294. return;
  26295. }
  26296. needsClear = true;
  26297. }
  26298. _view.reflect( _normal ).negate();
  26299. _view.add( _reflectorWorldPosition );
  26300. _rotationMatrix.extractRotation( camera.matrixWorld );
  26301. _lookAtPosition.set( 0, 0, -1 );
  26302. _lookAtPosition.applyMatrix4( _rotationMatrix );
  26303. _lookAtPosition.add( _cameraWorldPosition );
  26304. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  26305. _target.reflect( _normal ).negate();
  26306. _target.add( _reflectorWorldPosition );
  26307. //
  26308. virtualCamera.coordinateSystem = camera.coordinateSystem;
  26309. virtualCamera.position.copy( _view );
  26310. virtualCamera.up.set( 0, 1, 0 );
  26311. virtualCamera.up.applyMatrix4( _rotationMatrix );
  26312. virtualCamera.up.reflect( _normal );
  26313. virtualCamera.lookAt( _target );
  26314. virtualCamera.near = camera.near;
  26315. virtualCamera.far = camera.far;
  26316. virtualCamera.updateMatrixWorld();
  26317. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  26318. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  26319. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  26320. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  26321. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  26322. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  26323. const projectionMatrix = virtualCamera.projectionMatrix;
  26324. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  26325. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  26326. _q.z = -1;
  26327. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  26328. // Calculate the scaled plane vector
  26329. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  26330. const clipBias = 0;
  26331. // Replacing the third row of the projection matrix
  26332. projectionMatrix.elements[ 2 ] = clipPlane.x;
  26333. projectionMatrix.elements[ 6 ] = clipPlane.y;
  26334. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  26335. projectionMatrix.elements[ 14 ] = clipPlane.w;
  26336. //
  26337. this.textureNode.value = renderTarget.texture;
  26338. if ( this.depth === true ) {
  26339. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  26340. }
  26341. material.visible = false;
  26342. const currentRenderTarget = renderer.getRenderTarget();
  26343. const currentMRT = renderer.getMRT();
  26344. const currentAutoClear = renderer.autoClear;
  26345. renderer.setMRT( null );
  26346. renderer.setRenderTarget( renderTarget );
  26347. renderer.autoClear = true;
  26348. const previousName = scene.name;
  26349. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  26350. if ( needsClear ) {
  26351. renderer.clear();
  26352. this.hasOutput = false;
  26353. } else {
  26354. renderer.render( scene, virtualCamera );
  26355. this.hasOutput = true;
  26356. }
  26357. scene.name = previousName;
  26358. renderer.setMRT( currentMRT );
  26359. renderer.setRenderTarget( currentRenderTarget );
  26360. renderer.autoClear = currentAutoClear;
  26361. material.visible = true;
  26362. _inReflector = false;
  26363. this.forceUpdate = false;
  26364. }
  26365. /**
  26366. * The resolution scale.
  26367. *
  26368. * @deprecated
  26369. * @type {number}
  26370. * @default {1}
  26371. */
  26372. get resolution() {
  26373. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  26374. return this.resolutionScale;
  26375. }
  26376. set resolution( value ) {
  26377. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  26378. this.resolutionScale = value;
  26379. }
  26380. }
  26381. /**
  26382. * TSL function for creating a reflector node.
  26383. *
  26384. * @tsl
  26385. * @function
  26386. * @param {Object} [parameters={}] - An object holding configuration parameters.
  26387. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  26388. * @param {number} [parameters.resolution=1] - The resolution scale.
  26389. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  26390. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  26391. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  26392. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  26393. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  26394. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  26395. * @returns {ReflectorNode}
  26396. */
  26397. const reflector = ( parameters ) => new ReflectorNode( parameters );
  26398. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  26399. /**
  26400. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  26401. *
  26402. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  26403. *
  26404. * @private
  26405. * @augments BufferGeometry
  26406. */
  26407. class QuadGeometry extends BufferGeometry {
  26408. /**
  26409. * Constructs a new quad geometry.
  26410. *
  26411. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  26412. */
  26413. constructor( flipY = false ) {
  26414. super();
  26415. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  26416. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  26417. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  26418. }
  26419. }
  26420. const _geometry = /*@__PURE__*/ new QuadGeometry();
  26421. /**
  26422. * This module is a helper for passes which need to render a full
  26423. * screen effect which is quite common in context of post processing.
  26424. *
  26425. * The intended usage is to reuse a single quad mesh for rendering
  26426. * subsequent passes by just reassigning the `material` reference.
  26427. *
  26428. * Note: This module can only be used with `WebGPURenderer`.
  26429. *
  26430. * @augments Mesh
  26431. */
  26432. class QuadMesh extends Mesh {
  26433. /**
  26434. * Constructs a new quad mesh.
  26435. *
  26436. * @param {?Material} [material=null] - The material to render the quad mesh with.
  26437. */
  26438. constructor( material = null ) {
  26439. super( _geometry, material );
  26440. /**
  26441. * The camera to render the quad mesh with.
  26442. *
  26443. * @type {OrthographicCamera}
  26444. * @readonly
  26445. */
  26446. this.camera = _camera;
  26447. /**
  26448. * This flag can be used for type testing.
  26449. *
  26450. * @type {boolean}
  26451. * @readonly
  26452. * @default true
  26453. */
  26454. this.isQuadMesh = true;
  26455. }
  26456. /**
  26457. * Async version of `render()`.
  26458. *
  26459. * @async
  26460. * @deprecated
  26461. * @param {Renderer} renderer - The renderer.
  26462. * @return {Promise} A Promise that resolves when the render has been finished.
  26463. */
  26464. async renderAsync( renderer ) {
  26465. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  26466. await renderer.init();
  26467. renderer.render( this, _camera );
  26468. }
  26469. /**
  26470. * Renders the quad mesh
  26471. *
  26472. * @param {Renderer} renderer - The renderer.
  26473. */
  26474. render( renderer ) {
  26475. renderer.render( this, _camera );
  26476. }
  26477. }
  26478. const _size$1 = /*@__PURE__*/ new Vector2();
  26479. /**
  26480. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  26481. * This module is especially relevant in context of post processing where certain nodes require
  26482. * texture input for their effects. With the helper function `convertToTexture()` which is based
  26483. * on this module, the node system can automatically ensure texture input if required.
  26484. *
  26485. * @augments TextureNode
  26486. */
  26487. class RTTNode extends TextureNode {
  26488. static get type() {
  26489. return 'RTTNode';
  26490. }
  26491. /**
  26492. * Constructs a new RTT node.
  26493. *
  26494. * @param {Node} node - The node to render a texture with.
  26495. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  26496. * @param {?number} [height=null] - The height of the internal render target.
  26497. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  26498. */
  26499. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  26500. const renderTarget = new RenderTarget( width, height, options );
  26501. super( renderTarget.texture, uv$1() );
  26502. /**
  26503. * This flag can be used for type testing.
  26504. *
  26505. * @type {boolean}
  26506. * @readonly
  26507. * @default true
  26508. */
  26509. this.isRTTNode = true;
  26510. /**
  26511. * The node to render a texture with.
  26512. *
  26513. * @type {Node}
  26514. */
  26515. this.node = node;
  26516. /**
  26517. * The width of the internal render target.
  26518. * If not width is applied, the render target is automatically resized.
  26519. *
  26520. * @type {?number}
  26521. * @default null
  26522. */
  26523. this.width = width;
  26524. /**
  26525. * The height of the internal render target.
  26526. *
  26527. * @type {?number}
  26528. * @default null
  26529. */
  26530. this.height = height;
  26531. /**
  26532. * The pixel ratio
  26533. *
  26534. * @type {number}
  26535. * @default 1
  26536. */
  26537. this.pixelRatio = 1;
  26538. /**
  26539. * The render target
  26540. *
  26541. * @type {RenderTarget}
  26542. */
  26543. this.renderTarget = renderTarget;
  26544. /**
  26545. * Whether the texture requires an update or not.
  26546. *
  26547. * @type {boolean}
  26548. * @default true
  26549. */
  26550. this.textureNeedsUpdate = true;
  26551. /**
  26552. * Whether the texture should automatically be updated or not.
  26553. *
  26554. * @type {boolean}
  26555. * @default true
  26556. */
  26557. this.autoUpdate = true;
  26558. /**
  26559. * The node which is used with the quad mesh for RTT.
  26560. *
  26561. * @private
  26562. * @type {Node}
  26563. * @default null
  26564. */
  26565. this._rttNode = null;
  26566. /**
  26567. * The internal quad mesh for RTT.
  26568. *
  26569. * @private
  26570. * @type {QuadMesh}
  26571. */
  26572. this._quadMesh = new QuadMesh( new NodeMaterial() );
  26573. /**
  26574. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  26575. * the texture once per render in its {@link RTTNode#updateBefore} method.
  26576. *
  26577. * @type {string}
  26578. * @default 'render'
  26579. */
  26580. this.updateBeforeType = NodeUpdateType.RENDER;
  26581. }
  26582. /**
  26583. * Whether the internal render target should automatically be resized or not.
  26584. *
  26585. * @type {boolean}
  26586. * @readonly
  26587. * @default true
  26588. */
  26589. get autoResize() {
  26590. return this.width === null;
  26591. }
  26592. setup( builder ) {
  26593. this._rttNode = this.node.context( builder.getSharedContext() );
  26594. this._quadMesh.material.name = 'RTT';
  26595. this._quadMesh.material.needsUpdate = true;
  26596. return super.setup( builder );
  26597. }
  26598. /**
  26599. * Sets the size of the internal render target
  26600. *
  26601. * @param {number} width - The width to set.
  26602. * @param {number} height - The width to set.
  26603. */
  26604. setSize( width, height ) {
  26605. this.width = width;
  26606. this.height = height;
  26607. const effectiveWidth = width * this.pixelRatio;
  26608. const effectiveHeight = height * this.pixelRatio;
  26609. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  26610. this.textureNeedsUpdate = true;
  26611. }
  26612. /**
  26613. * Sets the pixel ratio. This will also resize the render target.
  26614. *
  26615. * @param {number} pixelRatio - The pixel ratio to set.
  26616. */
  26617. setPixelRatio( pixelRatio ) {
  26618. this.pixelRatio = pixelRatio;
  26619. this.setSize( this.width, this.height );
  26620. }
  26621. updateBefore( { renderer } ) {
  26622. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  26623. this.textureNeedsUpdate = false;
  26624. //
  26625. if ( this.autoResize === true ) {
  26626. const pixelRatio = renderer.getPixelRatio();
  26627. const size = renderer.getSize( _size$1 );
  26628. const effectiveWidth = Math.floor( size.width * pixelRatio );
  26629. const effectiveHeight = Math.floor( size.height * pixelRatio );
  26630. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  26631. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  26632. this.textureNeedsUpdate = true;
  26633. }
  26634. }
  26635. //
  26636. let name = 'RTT';
  26637. if ( this.node.name ) {
  26638. name = this.node.name + ' [ ' + name + ' ]';
  26639. }
  26640. this._quadMesh.material.fragmentNode = this._rttNode;
  26641. this._quadMesh.name = name;
  26642. //
  26643. const currentRenderTarget = renderer.getRenderTarget();
  26644. renderer.setRenderTarget( this.renderTarget );
  26645. this._quadMesh.render( renderer );
  26646. renderer.setRenderTarget( currentRenderTarget );
  26647. }
  26648. clone() {
  26649. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  26650. newNode.sampler = this.sampler;
  26651. newNode.referenceNode = this;
  26652. return newNode;
  26653. }
  26654. }
  26655. /**
  26656. * TSL function for creating a RTT node.
  26657. *
  26658. * @tsl
  26659. * @function
  26660. * @param {Node} node - The node to render a texture with.
  26661. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  26662. * @param {?number} [height=null] - The height of the internal render target.
  26663. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  26664. * @returns {RTTNode}
  26665. */
  26666. const rtt = ( node, ...params ) => new RTTNode( nodeObject( node ), ...params );
  26667. /**
  26668. * TSL function for converting nodes to textures nodes.
  26669. *
  26670. * @tsl
  26671. * @function
  26672. * @param {Node} node - The node to render a texture with.
  26673. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  26674. * @param {?number} [height=null] - The height of the internal render target.
  26675. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  26676. * @returns {RTTNode}
  26677. */
  26678. const convertToTexture = ( node, ...params ) => {
  26679. if ( node.isSampleNode || node.isTextureNode ) return node;
  26680. if ( node.isPassNode ) return node.getTextureNode();
  26681. return rtt( node, ...params );
  26682. };
  26683. /**
  26684. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  26685. * depth value and the camera's inverse projection matrix.
  26686. *
  26687. * @tsl
  26688. * @function
  26689. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  26690. * @param {Node<float>} depth - The fragment's depth value.
  26691. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  26692. * @return {Node<vec3>} The fragments position in view space.
  26693. */
  26694. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  26695. let clipSpacePosition;
  26696. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  26697. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  26698. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  26699. } else {
  26700. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  26701. }
  26702. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  26703. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  26704. } );
  26705. /**
  26706. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  26707. * and the camera's projection matrix
  26708. *
  26709. * @tsl
  26710. * @function
  26711. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  26712. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  26713. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  26714. */
  26715. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  26716. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  26717. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  26718. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  26719. } );
  26720. /**
  26721. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  26722. * target is available or if flat surface normals are required.
  26723. *
  26724. * @tsl
  26725. * @function
  26726. * @param {Node<vec2>} uv - The texture coordinate.
  26727. * @param {DepthTexture} depthTexture - The depth texture.
  26728. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  26729. * @return {Node<vec3>} The computed normal vector.
  26730. */
  26731. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  26732. const size = textureSize( textureLoad( depthTexture ) );
  26733. const p = ivec2( uv.mul( size ) ).toVar();
  26734. const c0 = textureLoad( depthTexture, p ).toVar();
  26735. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  26736. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  26737. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  26738. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  26739. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  26740. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  26741. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  26742. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  26743. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  26744. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  26745. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  26746. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  26747. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  26748. 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 ) ) );
  26749. 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 ) ) );
  26750. return normalize( cross( dpdx, dpdy ) );
  26751. } );
  26752. /**
  26753. * Interleaved Gradient Noise (IGN) from Jimenez 2014.
  26754. *
  26755. * IGN has "low discrepancy" resulting in evenly distributed samples. It's superior compared to
  26756. * default white noise, blue noise or Bayer.
  26757. *
  26758. * References:
  26759. * - {@link https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/}
  26760. * - {@link https://blog.demofox.org/2022/01/01/interleaved-gradient-noise-a-different-kind-of-low-discrepancy-sequence/}
  26761. *
  26762. * @tsl
  26763. * @function
  26764. * @param {Node<vec2>} position - The input position, usually screen coordinates.
  26765. * @return {Node<float>} The noise value.
  26766. */
  26767. const interleavedGradientNoise = Fn( ( [ position ] ) => {
  26768. return fract( float( 52.9829189 ).mul( fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ) );
  26769. } ).setLayout( {
  26770. name: 'interleavedGradientNoise',
  26771. type: 'float',
  26772. inputs: [
  26773. { name: 'position', type: 'vec2' }
  26774. ]
  26775. } );
  26776. /**
  26777. * Vogel disk sampling for uniform circular distribution.
  26778. *
  26779. * This function generates sample points distributed uniformly on a disk using the golden angle,
  26780. * resulting in an efficient low-discrepancy sequence for sampling. The rotation parameter (phi)
  26781. * allows randomizing the pattern per-pixel when combined with IGN.
  26782. *
  26783. * @tsl
  26784. * @function
  26785. * @param {Node<int>} sampleIndex - The index of the current sample (0-based).
  26786. * @param {Node<int>} samplesCount - The total number of samples.
  26787. * @param {Node<float>} phi - Rotation angle in radians (typically from IGN * 2π).
  26788. * @return {Node<vec2>} A 2D point on the unit disk.
  26789. */
  26790. const vogelDiskSample = Fn( ( [ sampleIndex, samplesCount, phi ] ) => {
  26791. const goldenAngle = float( 2.399963229728653 ); // 2π * (2 - φ) where φ is golden ratio
  26792. const r = sqrt( float( sampleIndex ).add( 0.5 ).div( float( samplesCount ) ) );
  26793. const theta = float( sampleIndex ).mul( goldenAngle ).add( phi );
  26794. return vec2( cos( theta ), sin( theta ) ).mul( r );
  26795. } ).setLayout( {
  26796. name: 'vogelDiskSample',
  26797. type: 'vec2',
  26798. inputs: [
  26799. { name: 'sampleIndex', type: 'int' },
  26800. { name: 'samplesCount', type: 'int' },
  26801. { name: 'phi', type: 'float' }
  26802. ]
  26803. } );
  26804. /**
  26805. * Class representing a node that samples a value using a provided callback function.
  26806. *
  26807. * @extends Node
  26808. */
  26809. class SampleNode extends Node {
  26810. /**
  26811. * Returns the type of the node.
  26812. *
  26813. * @type {string}
  26814. * @readonly
  26815. * @static
  26816. */
  26817. static get type() {
  26818. return 'SampleNode';
  26819. }
  26820. /**
  26821. * Creates an instance of SampleNode.
  26822. *
  26823. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  26824. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  26825. */
  26826. constructor( callback, uvNode = null ) {
  26827. super();
  26828. this.callback = callback;
  26829. /**
  26830. * Represents the texture coordinates.
  26831. *
  26832. * @type {?Node<vec2|vec3>}
  26833. * @default null
  26834. */
  26835. this.uvNode = uvNode;
  26836. /**
  26837. * This flag can be used for type testing.
  26838. *
  26839. * @type {boolean}
  26840. * @readonly
  26841. * @default true
  26842. */
  26843. this.isSampleNode = true;
  26844. }
  26845. /**
  26846. * Sets up the node by sampling with the default UV accessor.
  26847. *
  26848. * @returns {Node} The result of the callback function when called with the UV node.
  26849. */
  26850. setup() {
  26851. return this.sample( uv$1() );
  26852. }
  26853. /**
  26854. * Calls the callback function with the provided UV node.
  26855. *
  26856. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  26857. * @returns {Node} The result of the callback function.
  26858. */
  26859. sample( uv ) {
  26860. return this.callback( uv );
  26861. }
  26862. }
  26863. /**
  26864. * Helper function to create a SampleNode wrapped as a node object.
  26865. *
  26866. * @function
  26867. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  26868. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  26869. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  26870. */
  26871. const sample = ( callback, uv = null ) => new SampleNode( callback, nodeObject( uv ) );
  26872. /**
  26873. * EventNode is a node that executes a callback during specific update phases.
  26874. *
  26875. * @augments Node
  26876. */
  26877. class EventNode extends Node {
  26878. static get type() {
  26879. return 'EventNode';
  26880. }
  26881. /**
  26882. * Creates an EventNode.
  26883. *
  26884. * @param {string} eventType - The type of event
  26885. * @param {Function} callback - The callback to execute on update.
  26886. */
  26887. constructor( eventType, callback ) {
  26888. super( 'void' );
  26889. this.eventType = eventType;
  26890. this.callback = callback;
  26891. if ( eventType === EventNode.OBJECT ) {
  26892. this.updateType = NodeUpdateType.OBJECT;
  26893. } else if ( eventType === EventNode.MATERIAL ) {
  26894. this.updateType = NodeUpdateType.RENDER;
  26895. } else if ( eventType === EventNode.BEFORE_OBJECT ) {
  26896. this.updateBeforeType = NodeUpdateType.OBJECT;
  26897. } else if ( eventType === EventNode.BEFORE_MATERIAL ) {
  26898. this.updateBeforeType = NodeUpdateType.RENDER;
  26899. }
  26900. }
  26901. update( frame ) {
  26902. this.callback( frame );
  26903. }
  26904. updateBefore( frame ) {
  26905. this.callback( frame );
  26906. }
  26907. }
  26908. EventNode.OBJECT = 'object';
  26909. EventNode.MATERIAL = 'material';
  26910. EventNode.BEFORE_OBJECT = 'beforeObject';
  26911. EventNode.BEFORE_MATERIAL = 'beforeMaterial';
  26912. /**
  26913. * Helper to create an EventNode and add it to the stack.
  26914. *
  26915. * @param {string} type - The event type.
  26916. * @param {Function} callback - The callback function.
  26917. * @returns {EventNode}
  26918. */
  26919. const createEvent = ( type, callback ) => new EventNode( type, callback ).toStack();
  26920. /**
  26921. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  26922. *
  26923. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  26924. *
  26925. * @param {Function} callback - The callback function.
  26926. * @returns {EventNode}
  26927. */
  26928. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  26929. /**
  26930. * Creates an event that triggers a function when the first object that uses the material is rendered.
  26931. *
  26932. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  26933. *
  26934. * @param {Function} callback - The callback function.
  26935. * @returns {EventNode}
  26936. */
  26937. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  26938. /**
  26939. * Creates an event that triggers a function before an object (Mesh|Sprite) is updated.
  26940. *
  26941. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  26942. *
  26943. * @param {Function} callback - The callback function.
  26944. * @returns {EventNode}
  26945. */
  26946. const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJECT, callback );
  26947. /**
  26948. * Creates an event that triggers a function before the material is updated.
  26949. *
  26950. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  26951. *
  26952. * @param {Function} callback - The callback function.
  26953. * @returns {EventNode}
  26954. */
  26955. const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback );
  26956. /**
  26957. * This special type of instanced buffer attribute is intended for compute shaders.
  26958. * In earlier three.js versions it was only possible to update attribute data
  26959. * on the CPU via JavaScript and then upload the data to the GPU. With the
  26960. * new material system and renderer it is now possible to use compute shaders
  26961. * to compute the data for an attribute more efficiently on the GPU.
  26962. *
  26963. * The idea is to create an instance of this class and provide it as an input
  26964. * to {@link StorageBufferNode}.
  26965. *
  26966. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  26967. *
  26968. * @augments InstancedBufferAttribute
  26969. */
  26970. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  26971. /**
  26972. * Constructs a new storage instanced buffer attribute.
  26973. *
  26974. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  26975. * The subsequent parameters are then obsolete.
  26976. * @param {number} itemSize - The item size.
  26977. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  26978. */
  26979. constructor( count, itemSize, typeClass = Float32Array ) {
  26980. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  26981. super( array, itemSize );
  26982. /**
  26983. * This flag can be used for type testing.
  26984. *
  26985. * @type {boolean}
  26986. * @readonly
  26987. * @default true
  26988. */
  26989. this.isStorageInstancedBufferAttribute = true;
  26990. }
  26991. }
  26992. /**
  26993. * This special type of buffer attribute is intended for compute shaders.
  26994. * In earlier three.js versions it was only possible to update attribute data
  26995. * on the CPU via JavaScript and then upload the data to the GPU. With the
  26996. * new material system and renderer it is now possible to use compute shaders
  26997. * to compute the data for an attribute more efficiently on the GPU.
  26998. *
  26999. * The idea is to create an instance of this class and provide it as an input
  27000. * to {@link StorageBufferNode}.
  27001. *
  27002. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  27003. *
  27004. * @augments BufferAttribute
  27005. */
  27006. class StorageBufferAttribute extends BufferAttribute {
  27007. /**
  27008. * Constructs a new storage buffer attribute.
  27009. *
  27010. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  27011. * The subsequent parameters are then obsolete.
  27012. * @param {number} itemSize - The item size.
  27013. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  27014. */
  27015. constructor( count, itemSize, typeClass = Float32Array ) {
  27016. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  27017. super( array, itemSize );
  27018. /**
  27019. * This flag can be used for type testing.
  27020. *
  27021. * @type {boolean}
  27022. * @readonly
  27023. * @default true
  27024. */
  27025. this.isStorageBufferAttribute = true;
  27026. }
  27027. }
  27028. /**
  27029. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  27030. *
  27031. * @tsl
  27032. * @function
  27033. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  27034. * @param {string|Struct} [type='float'] - The data type.
  27035. * @returns {StorageBufferNode}
  27036. */
  27037. const attributeArray = ( count, type = 'float' ) => {
  27038. let itemSize, typedArray;
  27039. if ( type.isStruct === true ) {
  27040. itemSize = type.layout.getLength();
  27041. typedArray = getTypedArrayFromType( 'float' );
  27042. } else {
  27043. itemSize = getLengthFromType( type );
  27044. typedArray = getTypedArrayFromType( type );
  27045. }
  27046. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  27047. const node = storage( buffer, type, count );
  27048. return node;
  27049. };
  27050. /**
  27051. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  27052. *
  27053. * @tsl
  27054. * @function
  27055. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  27056. * @param {string|Struct} [type='float'] - The data type.
  27057. * @returns {StorageBufferNode}
  27058. */
  27059. const instancedArray = ( count, type = 'float' ) => {
  27060. let itemSize, typedArray;
  27061. if ( type.isStruct === true ) {
  27062. itemSize = type.layout.getLength();
  27063. typedArray = getTypedArrayFromType( 'float' );
  27064. } else {
  27065. itemSize = getLengthFromType( type );
  27066. typedArray = getTypedArrayFromType( type );
  27067. }
  27068. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  27069. const node = storage( buffer, type, buffer.count );
  27070. return node;
  27071. };
  27072. /**
  27073. * A node for representing the uv coordinates of points.
  27074. *
  27075. * Can only be used with a WebGL backend. In WebGPU, point
  27076. * primitives always have the size of one pixel and can thus
  27077. * can't be used as sprite-like objects that display textures.
  27078. *
  27079. * @augments Node
  27080. */
  27081. class PointUVNode extends Node {
  27082. static get type() {
  27083. return 'PointUVNode';
  27084. }
  27085. /**
  27086. * Constructs a new point uv node.
  27087. */
  27088. constructor() {
  27089. super( 'vec2' );
  27090. /**
  27091. * This flag can be used for type testing.
  27092. *
  27093. * @type {boolean}
  27094. * @readonly
  27095. * @default true
  27096. */
  27097. this.isPointUVNode = true;
  27098. }
  27099. generate( /*builder*/ ) {
  27100. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  27101. }
  27102. }
  27103. /**
  27104. * TSL object that represents the uv coordinates of points.
  27105. *
  27106. * @tsl
  27107. * @type {PointUVNode}
  27108. */
  27109. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  27110. const _m1 = /*@__PURE__*/ new Matrix4();
  27111. /**
  27112. * TSL object that represents the scene's background blurriness.
  27113. *
  27114. * @tsl
  27115. * @type {Node<float>}
  27116. */
  27117. const backgroundBlurriness = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => scene.backgroundBlurriness );
  27118. /**
  27119. * TSL object that represents the scene's background intensity.
  27120. *
  27121. * @tsl
  27122. * @type {Node<float>}
  27123. */
  27124. const backgroundIntensity = /*@__PURE__*/ uniform( 1 ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => scene.backgroundIntensity );
  27125. /**
  27126. * TSL object that represents the scene's background rotation.
  27127. *
  27128. * @tsl
  27129. * @type {Node<mat4>}
  27130. */
  27131. const backgroundRotation = /*@__PURE__*/ uniform( new Matrix4() ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => {
  27132. const background = scene.background;
  27133. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  27134. // note: since the matrix is orthonormal, we can use the more-efficient transpose() in lieu of invert()
  27135. _m1.makeRotationFromEuler( scene.backgroundRotation ).transpose();
  27136. } else {
  27137. _m1.identity();
  27138. }
  27139. return _m1;
  27140. } );
  27141. /**
  27142. * This special version of a texture node can be used to
  27143. * write data into a storage texture with a compute shader.
  27144. *
  27145. * ```js
  27146. * const storageTexture = new THREE.StorageTexture( width, height );
  27147. *
  27148. * const computeTexture = Fn( ( { storageTexture } ) => {
  27149. *
  27150. * const posX = instanceIndex.mod( width );
  27151. * const posY = instanceIndex.div( width );
  27152. * const indexUV = uvec2( posX, posY );
  27153. *
  27154. * // generate RGB values
  27155. *
  27156. * const r = 1;
  27157. * const g = 1;
  27158. * const b = 1;
  27159. *
  27160. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  27161. *
  27162. * } );
  27163. *
  27164. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  27165. * renderer.computeAsync( computeNode );
  27166. * ```
  27167. *
  27168. * This node can only be used with a WebGPU backend.
  27169. *
  27170. * @augments TextureNode
  27171. */
  27172. class StorageTextureNode extends TextureNode {
  27173. static get type() {
  27174. return 'StorageTextureNode';
  27175. }
  27176. /**
  27177. * Constructs a new storage texture node.
  27178. *
  27179. * @param {StorageTexture} value - The storage texture.
  27180. * @param {Node<vec2|vec3>} uvNode - The uv node.
  27181. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27182. */
  27183. constructor( value, uvNode, storeNode = null ) {
  27184. super( value, uvNode );
  27185. /**
  27186. * The value node that should be stored in the texture.
  27187. *
  27188. * @type {?Node}
  27189. * @default null
  27190. */
  27191. this.storeNode = storeNode;
  27192. /**
  27193. * The mip level to write to for storage textures.
  27194. *
  27195. * @type {number}
  27196. * @default 0
  27197. */
  27198. this.mipLevel = 0;
  27199. /**
  27200. * This flag can be used for type testing.
  27201. *
  27202. * @type {boolean}
  27203. * @readonly
  27204. * @default true
  27205. */
  27206. this.isStorageTextureNode = true;
  27207. /**
  27208. * The access type of the texture node.
  27209. *
  27210. * @type {string}
  27211. * @default 'writeOnly'
  27212. */
  27213. this.access = NodeAccess.WRITE_ONLY;
  27214. }
  27215. /**
  27216. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  27217. *
  27218. * @param {NodeBuilder} builder - The current node builder.
  27219. * @return {string} The input type.
  27220. */
  27221. getInputType( /*builder*/ ) {
  27222. return 'storageTexture';
  27223. }
  27224. setup( builder ) {
  27225. super.setup( builder );
  27226. const properties = builder.getNodeProperties( this );
  27227. properties.storeNode = this.storeNode;
  27228. return properties;
  27229. }
  27230. /**
  27231. * Defines the node access.
  27232. *
  27233. * @param {string} value - The node access.
  27234. * @return {StorageTextureNode} A reference to this node.
  27235. */
  27236. setAccess( value ) {
  27237. this.access = value;
  27238. return this;
  27239. }
  27240. /**
  27241. * Sets the mip level to write to.
  27242. *
  27243. * @param {number} level - The mip level.
  27244. * @return {StorageTextureNode} A reference to this node.
  27245. */
  27246. setMipLevel( level ) {
  27247. this.mipLevel = level;
  27248. return this;
  27249. }
  27250. /**
  27251. * Generates the code snippet of the storage node. If no `storeNode`
  27252. * is defined, the texture node is generated as normal texture.
  27253. *
  27254. * @param {NodeBuilder} builder - The current node builder.
  27255. * @param {string} output - The current output.
  27256. * @return {string} The generated code snippet.
  27257. */
  27258. generate( builder, output ) {
  27259. if ( this.storeNode !== null ) {
  27260. this.generateStore( builder );
  27261. return '';
  27262. }
  27263. return super.generate( builder, output );
  27264. }
  27265. /**
  27266. * Generates the snippet for the storage texture.
  27267. *
  27268. * @param {NodeBuilder} builder - The current node builder.
  27269. * @param {string} textureProperty - The texture property.
  27270. * @param {string} uvSnippet - The uv snippet.
  27271. * @param {?string} levelSnippet - The level snippet.
  27272. * @param {?string} biasSnippet - The bias snippet.
  27273. * @param {?string} depthSnippet - The depth snippet.
  27274. * @param {?string} compareSnippet - The compare snippet.
  27275. * @param {?Array<string>} gradSnippet - The grad snippet.
  27276. * @param {?string} offsetSnippet - The offset snippet.
  27277. * @return {string} The generated code snippet.
  27278. */
  27279. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  27280. const texture = this.value;
  27281. return builder.generateStorageTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  27282. }
  27283. /**
  27284. * Convenience method for configuring a read/write node access.
  27285. *
  27286. * @return {StorageTextureNode} A reference to this node.
  27287. */
  27288. toReadWrite() {
  27289. return this.setAccess( NodeAccess.READ_WRITE );
  27290. }
  27291. /**
  27292. * Convenience method for configuring a read-only node access.
  27293. *
  27294. * @return {StorageTextureNode} A reference to this node.
  27295. */
  27296. toReadOnly() {
  27297. return this.setAccess( NodeAccess.READ_ONLY );
  27298. }
  27299. /**
  27300. * Convenience method for configuring a write-only node access.
  27301. *
  27302. * @return {StorageTextureNode} A reference to this node.
  27303. */
  27304. toWriteOnly() {
  27305. return this.setAccess( NodeAccess.WRITE_ONLY );
  27306. }
  27307. /**
  27308. * Generates the code snippet of the storage texture node.
  27309. *
  27310. * @param {NodeBuilder} builder - The current node builder.
  27311. */
  27312. generateStore( builder ) {
  27313. const properties = builder.getNodeProperties( this );
  27314. const { uvNode, storeNode, depthNode } = properties;
  27315. const textureProperty = super.generate( builder, 'property' );
  27316. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  27317. const storeSnippet = storeNode.build( builder, 'vec4' );
  27318. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  27319. const snippet = builder.generateTextureStore( this.value, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  27320. builder.addLineFlowCode( snippet, this );
  27321. }
  27322. clone() {
  27323. const newNode = super.clone();
  27324. newNode.storeNode = this.storeNode;
  27325. newNode.mipLevel = this.mipLevel;
  27326. newNode.access = this.access;
  27327. return newNode;
  27328. }
  27329. }
  27330. /**
  27331. * TSL function for creating a storage texture node.
  27332. *
  27333. * @tsl
  27334. * @function
  27335. * @param {StorageTexture} value - The storage texture.
  27336. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  27337. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27338. * @returns {StorageTextureNode}
  27339. */
  27340. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  27341. /**
  27342. * TODO: Explain difference to `storageTexture()`.
  27343. *
  27344. * @tsl
  27345. * @function
  27346. * @param {StorageTexture} value - The storage texture.
  27347. * @param {Node<vec2|vec3>} uvNode - The uv node.
  27348. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  27349. * @returns {StorageTextureNode}
  27350. */
  27351. const textureStore = ( value, uvNode, storeNode ) => {
  27352. let node;
  27353. if ( value.isStorageTextureNode === true ) {
  27354. // Derive new storage texture node from existing one
  27355. node = value.clone();
  27356. node.uvNode = uvNode;
  27357. node.storeNode = storeNode;
  27358. } else {
  27359. node = storageTexture( value, uvNode, storeNode );
  27360. }
  27361. if ( storeNode !== null ) node.toStack();
  27362. return node;
  27363. };
  27364. const normal = Fn( ( { texture, uv } ) => {
  27365. const epsilon = 0.0001;
  27366. const ret = vec3().toVar();
  27367. If( uv.x.lessThan( epsilon ), () => {
  27368. ret.assign( vec3( 1, 0, 0 ) );
  27369. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  27370. ret.assign( vec3( 0, 1, 0 ) );
  27371. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  27372. ret.assign( vec3( 0, 0, 1 ) );
  27373. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  27374. ret.assign( vec3( -1, 0, 0 ) );
  27375. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  27376. ret.assign( vec3( 0, -1, 0 ) );
  27377. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  27378. ret.assign( vec3( 0, 0, -1 ) );
  27379. } ).Else( () => {
  27380. const step = 0.01;
  27381. const x = texture.sample( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  27382. const y = texture.sample( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  27383. const z = texture.sample( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  27384. ret.assign( vec3( x, y, z ) );
  27385. } );
  27386. return ret.normalize();
  27387. } );
  27388. /**
  27389. * This type of uniform node represents a 3D texture.
  27390. *
  27391. * @augments TextureNode
  27392. */
  27393. class Texture3DNode extends TextureNode {
  27394. static get type() {
  27395. return 'Texture3DNode';
  27396. }
  27397. /**
  27398. * Constructs a new 3D texture node.
  27399. *
  27400. * @param {Data3DTexture} value - The 3D texture.
  27401. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  27402. * @param {?Node<int>} [levelNode=null] - The level node.
  27403. */
  27404. constructor( value, uvNode = null, levelNode = null ) {
  27405. super( value, uvNode, levelNode );
  27406. /**
  27407. * This flag can be used for type testing.
  27408. *
  27409. * @type {boolean}
  27410. * @readonly
  27411. * @default true
  27412. */
  27413. this.isTexture3DNode = true;
  27414. }
  27415. /**
  27416. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  27417. *
  27418. * @param {NodeBuilder} builder - The current node builder.
  27419. * @return {string} The input type.
  27420. */
  27421. getInputType( /*builder*/ ) {
  27422. return 'texture3D';
  27423. }
  27424. /**
  27425. * Returns a default uv node which is in context of 3D textures a three-dimensional
  27426. * uv node.
  27427. *
  27428. * @return {Node<vec3>} The default uv node.
  27429. */
  27430. getDefaultUV() {
  27431. return vec3( 0.5, 0.5, 0.5 );
  27432. }
  27433. /**
  27434. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  27435. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  27436. *
  27437. * @param {boolean} value - The update toggle.
  27438. */
  27439. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  27440. /**
  27441. * Generates the uv code snippet.
  27442. *
  27443. * @param {NodeBuilder} builder - The current node builder.
  27444. * @param {Node} uvNode - The uv node to generate code for.
  27445. * @return {string} The generated code snippet.
  27446. */
  27447. generateUV( builder, uvNode ) {
  27448. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  27449. }
  27450. /**
  27451. * Generates the offset code snippet.
  27452. *
  27453. * @param {NodeBuilder} builder - The current node builder.
  27454. * @param {Node} offsetNode - The offset node to generate code for.
  27455. * @return {string} The generated code snippet.
  27456. */
  27457. generateOffset( builder, offsetNode ) {
  27458. return offsetNode.build( builder, 'ivec3' );
  27459. }
  27460. /**
  27461. * Computes the normal for the given uv. These texture coordiantes represent a
  27462. * position inside the 3D texture. Unlike geometric normals, this normal
  27463. * represents a slope or gradient of scalar data inside the 3D texture.
  27464. *
  27465. * @param {Node<vec3>} uvNode - The uv node that defines a position in the 3D texture.
  27466. * @return {Node<vec3>} The normal representing the slope/gradient in the data.
  27467. */
  27468. normal( uvNode ) {
  27469. return normal( { texture: this, uv: uvNode } );
  27470. }
  27471. }
  27472. /**
  27473. * TSL function for creating a 3D texture node.
  27474. *
  27475. * @tsl
  27476. * @function
  27477. * @param {Data3DTexture} value - The 3D texture.
  27478. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  27479. * @param {?Node<int>} [levelNode=null] - The level node.
  27480. * @returns {Texture3DNode}
  27481. */
  27482. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  27483. /**
  27484. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  27485. *
  27486. * @tsl
  27487. * @function
  27488. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  27489. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  27490. * @param {?Node<int>} [levelNode=null] - The level node.
  27491. * @param {?Node<float>} [biasNode=null] - The bias node.
  27492. * @returns {TextureNode}
  27493. */
  27494. const texture3DLoad = ( ...params ) => texture3D( ...params ).setSampler( false );
  27495. /**
  27496. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  27497. *
  27498. * @tsl
  27499. * @function
  27500. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  27501. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  27502. * @param {?Node<int>} [levelNode=null] - The level node.
  27503. * @returns {TextureNode}
  27504. */
  27505. const texture3DLevel = ( value, uvNode, levelNode ) => texture3D( value, uvNode ).level( levelNode );
  27506. /**
  27507. * A special type of reference node that allows to link values in
  27508. * `userData` fields to node objects.
  27509. * ```js
  27510. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  27511. *
  27512. * const material = new THREE.SpriteNodeMaterial();
  27513. * material.rotationNode = userData( 'rotation', 'float' );
  27514. * ```
  27515. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  27516. * will automatically be updated when the `rotation` user data field changes.
  27517. *
  27518. * @augments ReferenceNode
  27519. */
  27520. class UserDataNode extends ReferenceNode {
  27521. static get type() {
  27522. return 'UserDataNode';
  27523. }
  27524. /**
  27525. * Constructs a new user data node.
  27526. *
  27527. * @param {string} property - The property name that should be referenced by the node.
  27528. * @param {string} inputType - The node data type of the reference.
  27529. * @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.
  27530. */
  27531. constructor( property, inputType, userData = null ) {
  27532. super( property, inputType, userData );
  27533. /**
  27534. * A reference to the `userData` object. If not provided, the `userData`
  27535. * property of the 3D object that uses the node material is evaluated.
  27536. *
  27537. * @type {?Object}
  27538. * @default null
  27539. */
  27540. this.userData = userData;
  27541. }
  27542. /**
  27543. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  27544. * `userData` field.
  27545. *
  27546. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  27547. * @return {Object} A reference to the `userData` field.
  27548. */
  27549. updateReference( state ) {
  27550. this.reference = this.userData !== null ? this.userData : state.object.userData;
  27551. return this.reference;
  27552. }
  27553. }
  27554. /**
  27555. * TSL function for creating a user data node.
  27556. *
  27557. * @tsl
  27558. * @function
  27559. * @param {string} name - The property name that should be referenced by the node.
  27560. * @param {string} inputType - The node data type of the reference.
  27561. * @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.
  27562. * @returns {UserDataNode}
  27563. */
  27564. const userData = ( name, inputType, userData ) => new UserDataNode( name, inputType, userData );
  27565. const _objectData = new WeakMap();
  27566. /**
  27567. * A node for representing motion or velocity vectors. Foundation
  27568. * for advanced post processing effects like motion blur or TRAA.
  27569. *
  27570. * The node keeps track of the model, view and projection matrices
  27571. * of the previous frame and uses them to compute offsets in NDC space.
  27572. * These offsets represent the final velocity.
  27573. *
  27574. * @augments TempNode
  27575. */
  27576. class VelocityNode extends TempNode {
  27577. static get type() {
  27578. return 'VelocityNode';
  27579. }
  27580. /**
  27581. * Constructs a new vertex color node.
  27582. */
  27583. constructor() {
  27584. super( 'vec2' );
  27585. /**
  27586. * The current projection matrix.
  27587. *
  27588. * @type {?Matrix4}
  27589. * @default null
  27590. */
  27591. this.projectionMatrix = null;
  27592. /**
  27593. * Overwritten since velocity nodes are updated per object.
  27594. *
  27595. * @type {string}
  27596. * @default 'object'
  27597. */
  27598. this.updateType = NodeUpdateType.OBJECT;
  27599. /**
  27600. * Overwritten since velocity nodes save data after the update.
  27601. *
  27602. * @type {string}
  27603. * @default 'object'
  27604. */
  27605. this.updateAfterType = NodeUpdateType.OBJECT;
  27606. /**
  27607. * Uniform node representing the previous model matrix in world space.
  27608. *
  27609. * @type {UniformNode<mat4>}
  27610. * @default null
  27611. */
  27612. this.previousModelWorldMatrix = uniform( new Matrix4() );
  27613. /**
  27614. * Uniform node representing the previous projection matrix.
  27615. *
  27616. * @type {UniformNode<mat4>}
  27617. * @default null
  27618. */
  27619. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  27620. /**
  27621. * Uniform node representing the previous view matrix.
  27622. *
  27623. * @type {UniformNode<mat4>}
  27624. * @default null
  27625. */
  27626. this.previousCameraViewMatrix = uniform( new Matrix4() );
  27627. }
  27628. /**
  27629. * Sets the given projection matrix.
  27630. *
  27631. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  27632. */
  27633. setProjectionMatrix( projectionMatrix ) {
  27634. this.projectionMatrix = projectionMatrix;
  27635. }
  27636. /**
  27637. * Updates velocity specific uniforms.
  27638. *
  27639. * @param {NodeFrame} frame - A reference to the current node frame.
  27640. */
  27641. update( { frameId, camera, object } ) {
  27642. const previousModelMatrix = getPreviousMatrix( object );
  27643. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  27644. //
  27645. const cameraData = getData( camera );
  27646. if ( cameraData.frameId !== frameId ) {
  27647. cameraData.frameId = frameId;
  27648. if ( cameraData.previousProjectionMatrix === undefined ) {
  27649. cameraData.previousProjectionMatrix = new Matrix4();
  27650. cameraData.previousCameraViewMatrix = new Matrix4();
  27651. cameraData.currentProjectionMatrix = new Matrix4();
  27652. cameraData.currentCameraViewMatrix = new Matrix4();
  27653. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  27654. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  27655. } else {
  27656. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  27657. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  27658. }
  27659. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  27660. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  27661. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  27662. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  27663. }
  27664. }
  27665. /**
  27666. * Overwritten to updated velocity specific uniforms.
  27667. *
  27668. * @param {NodeFrame} frame - A reference to the current node frame.
  27669. */
  27670. updateAfter( { object } ) {
  27671. getPreviousMatrix( object ).copy( object.matrixWorld );
  27672. }
  27673. /**
  27674. * Implements the velocity computation based on the previous and current vertex data.
  27675. *
  27676. * @param {NodeBuilder} builder - A reference to the current node builder.
  27677. * @return {Node<vec2>} The motion vector.
  27678. */
  27679. setup( /*builder*/ ) {
  27680. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  27681. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  27682. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  27683. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  27684. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  27685. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  27686. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  27687. return velocity;
  27688. }
  27689. }
  27690. function getData( object ) {
  27691. let objectData = _objectData.get( object );
  27692. if ( objectData === undefined ) {
  27693. objectData = {};
  27694. _objectData.set( object, objectData );
  27695. }
  27696. return objectData;
  27697. }
  27698. function getPreviousMatrix( object, index = 0 ) {
  27699. const objectData = getData( object );
  27700. let matrix = objectData[ index ];
  27701. if ( matrix === undefined ) {
  27702. objectData[ index ] = matrix = new Matrix4();
  27703. objectData[ index ].copy( object.matrixWorld );
  27704. }
  27705. return matrix;
  27706. }
  27707. /**
  27708. * TSL object that represents the velocity of a render pass.
  27709. *
  27710. * @tsl
  27711. * @type {VelocityNode}
  27712. */
  27713. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  27714. /**
  27715. * Computes a grayscale value for the given RGB color value.
  27716. *
  27717. * @tsl
  27718. * @function
  27719. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  27720. * @return {Node<vec3>} The grayscale color.
  27721. */
  27722. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  27723. return luminance( color.rgb );
  27724. } );
  27725. /**
  27726. * Super-saturates or desaturates the given RGB color.
  27727. *
  27728. * @tsl
  27729. * @function
  27730. * @param {Node<vec3>} color - The input color.
  27731. * @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.
  27732. * @return {Node<vec3>} The saturated color.
  27733. */
  27734. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  27735. return adjustment.mix( luminance( color.rgb ), color.rgb );
  27736. } );
  27737. /**
  27738. * Selectively enhance the intensity of less saturated RGB colors. Can result
  27739. * in a more natural and visually appealing image with enhanced color depth
  27740. * compared to {@link ColorAdjustment#saturation}.
  27741. *
  27742. * @tsl
  27743. * @function
  27744. * @param {Node<vec3>} color - The input color.
  27745. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  27746. * @return {Node<vec3>} The updated color.
  27747. */
  27748. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  27749. const average = add( color.r, color.g, color.b ).div( 3.0 );
  27750. const mx = color.r.max( color.g.max( color.b ) );
  27751. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  27752. return mix( color.rgb, mx, amt );
  27753. } );
  27754. /**
  27755. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  27756. *
  27757. * @tsl
  27758. * @function
  27759. * @param {Node<vec3>} color - The input color.
  27760. * @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.
  27761. * @return {Node<vec3>} The updated color.
  27762. */
  27763. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  27764. const k = vec3( 0.57735, 0.57735, 0.57735 );
  27765. const cosAngle = adjustment.cos();
  27766. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  27767. } );
  27768. /**
  27769. * Computes the luminance for the given RGB color value.
  27770. *
  27771. * @tsl
  27772. * @function
  27773. * @param {Node<vec3>} color - The color value to compute the luminance for.
  27774. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  27775. * @return {Node<float>} The luminance.
  27776. */
  27777. const luminance = (
  27778. color,
  27779. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  27780. ) => dot( color, luminanceCoefficients );
  27781. /**
  27782. * Color Decision List (CDL) v1.2
  27783. *
  27784. * Compact representation of color grading information, defined by slope, offset, power, and
  27785. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  27786. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  27787. *
  27788. * @tsl
  27789. * @function
  27790. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  27791. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  27792. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  27793. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  27794. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  27795. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  27796. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  27797. *
  27798. * References:
  27799. * - ASC CDL v1.2
  27800. * - {@link https://blender.stackexchange.com/a/55239/43930}
  27801. * - {@link https://docs.acescentral.com/specifications/acescc/}
  27802. */
  27803. const cdl = /*@__PURE__*/ Fn( ( [
  27804. color,
  27805. slope = vec3( 1 ),
  27806. offset = vec3( 0 ),
  27807. power = vec3( 1 ),
  27808. saturation = float( 1 ),
  27809. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  27810. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  27811. ] ) => {
  27812. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  27813. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  27814. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  27815. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  27816. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  27817. const pv = v.pow( power ).toVar();
  27818. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  27819. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  27820. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  27821. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  27822. return vec4( v.rgb, color.a );
  27823. } );
  27824. /**
  27825. * TSL function for creating a posterize effect which reduces the number of colors
  27826. * in an image, resulting in a more blocky and stylized appearance.
  27827. *
  27828. * @tsl
  27829. * @function
  27830. * @param {Node} sourceNode - The input color.
  27831. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  27832. * @returns {Node} The posterized color.
  27833. */
  27834. const posterize = Fn( ( [ source, steps ] ) => {
  27835. return source.mul( steps ).floor().div( steps );
  27836. } );
  27837. let _sharedFramebuffer = null;
  27838. /**
  27839. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  27840. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  27841. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  27842. *
  27843. * @augments ViewportTextureNode
  27844. */
  27845. class ViewportSharedTextureNode extends ViewportTextureNode {
  27846. static get type() {
  27847. return 'ViewportSharedTextureNode';
  27848. }
  27849. /**
  27850. * Constructs a new viewport shared texture node.
  27851. *
  27852. * @param {Node} [uvNode=screenUV] - The uv node.
  27853. * @param {?Node} [levelNode=null] - The level node.
  27854. */
  27855. constructor( uvNode = screenUV, levelNode = null ) {
  27856. if ( _sharedFramebuffer === null ) {
  27857. _sharedFramebuffer = new FramebufferTexture();
  27858. }
  27859. super( uvNode, levelNode, _sharedFramebuffer );
  27860. }
  27861. /**
  27862. * Overwritten so the method always returns the unique shared
  27863. * framebuffer texture.
  27864. *
  27865. * @return {FramebufferTexture} The shared framebuffer texture.
  27866. */
  27867. getTextureForReference() {
  27868. return _sharedFramebuffer;
  27869. }
  27870. updateReference() {
  27871. return this;
  27872. }
  27873. }
  27874. /**
  27875. * TSL function for creating a shared viewport texture node.
  27876. *
  27877. * @tsl
  27878. * @function
  27879. * @param {?Node} [uvNode=screenUV] - The uv node.
  27880. * @param {?Node} [levelNode=null] - The level node.
  27881. * @returns {ViewportSharedTextureNode}
  27882. */
  27883. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  27884. const _size = /*@__PURE__*/ new Vector2();
  27885. /**
  27886. * Represents the texture of a pass node.
  27887. *
  27888. * @augments TextureNode
  27889. */
  27890. class PassTextureNode extends TextureNode {
  27891. static get type() {
  27892. return 'PassTextureNode';
  27893. }
  27894. /**
  27895. * Constructs a new pass texture node.
  27896. *
  27897. * @param {PassNode} passNode - The pass node.
  27898. * @param {Texture} texture - The output texture.
  27899. */
  27900. constructor( passNode, texture ) {
  27901. super( texture );
  27902. /**
  27903. * A reference to the pass node.
  27904. *
  27905. * @type {PassNode}
  27906. */
  27907. this.passNode = passNode;
  27908. /**
  27909. * This flag can be used for type testing.
  27910. *
  27911. * @type {boolean}
  27912. * @default true
  27913. * @readonly
  27914. */
  27915. this.isPassTextureNode = true;
  27916. this.setUpdateMatrix( false );
  27917. }
  27918. setup( builder ) {
  27919. const properties = builder.getNodeProperties( this );
  27920. properties.passNode = this.passNode;
  27921. return super.setup( builder );
  27922. }
  27923. clone() {
  27924. return new this.constructor( this.passNode, this.value );
  27925. }
  27926. }
  27927. /**
  27928. * An extension of `PassTextureNode` which allows to manage more than one
  27929. * internal texture. Relevant for the `getPreviousTexture()` related API.
  27930. *
  27931. * @augments PassTextureNode
  27932. */
  27933. class PassMultipleTextureNode extends PassTextureNode {
  27934. static get type() {
  27935. return 'PassMultipleTextureNode';
  27936. }
  27937. /**
  27938. * Constructs a new pass texture node.
  27939. *
  27940. * @param {PassNode} passNode - The pass node.
  27941. * @param {string} textureName - The output texture name.
  27942. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  27943. */
  27944. constructor( passNode, textureName, previousTexture = false ) {
  27945. // null is passed to the super call since this class does not
  27946. // use an external texture for rendering pass data into. Instead
  27947. // the texture is managed by the pass node itself
  27948. super( passNode, null );
  27949. /**
  27950. * The output texture name.
  27951. *
  27952. * @type {string}
  27953. */
  27954. this.textureName = textureName;
  27955. /**
  27956. * Whether previous frame data should be used or not.
  27957. *
  27958. * @type {boolean}
  27959. */
  27960. this.previousTexture = previousTexture;
  27961. /**
  27962. * This flag can be used for type testing.
  27963. *
  27964. * @type {boolean}
  27965. * @default true
  27966. * @readonly
  27967. */
  27968. this.isPassMultipleTextureNode = true;
  27969. }
  27970. /**
  27971. * Updates the texture reference of this node.
  27972. */
  27973. updateTexture() {
  27974. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  27975. }
  27976. setup( builder ) {
  27977. this.updateTexture();
  27978. return super.setup( builder );
  27979. }
  27980. clone() {
  27981. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  27982. newNode.uvNode = this.uvNode;
  27983. newNode.levelNode = this.levelNode;
  27984. newNode.biasNode = this.biasNode;
  27985. newNode.sampler = this.sampler;
  27986. newNode.depthNode = this.depthNode;
  27987. newNode.compareNode = this.compareNode;
  27988. newNode.gradNode = this.gradNode;
  27989. newNode.offsetNode = this.offsetNode;
  27990. return newNode;
  27991. }
  27992. }
  27993. /**
  27994. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  27995. * This pass produces a render for the given scene and camera and can provide multiple outputs
  27996. * via MRT for further processing.
  27997. *
  27998. * ```js
  27999. * const postProcessing = new RenderPipeline( renderer );
  28000. *
  28001. * const scenePass = pass( scene, camera );
  28002. *
  28003. * postProcessing.outputNode = scenePass;
  28004. * ```
  28005. *
  28006. * @augments TempNode
  28007. */
  28008. class PassNode extends TempNode {
  28009. static get type() {
  28010. return 'PassNode';
  28011. }
  28012. /**
  28013. * Constructs a new pass node.
  28014. *
  28015. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  28016. * @param {Scene} scene - A reference to the scene.
  28017. * @param {Camera} camera - A reference to the camera.
  28018. * @param {Object} options - Options for the internal render target.
  28019. */
  28020. constructor( scope, scene, camera, options = {} ) {
  28021. super( 'vec4' );
  28022. /**
  28023. * The scope of the pass. The scope determines whether the node outputs color or depth.
  28024. *
  28025. * @type {('color'|'depth')}
  28026. */
  28027. this.scope = scope;
  28028. /**
  28029. * A reference to the scene.
  28030. *
  28031. * @type {Scene}
  28032. */
  28033. this.scene = scene;
  28034. /**
  28035. * A reference to the camera.
  28036. *
  28037. * @type {Camera}
  28038. */
  28039. this.camera = camera;
  28040. /**
  28041. * Options for the internal render target.
  28042. *
  28043. * @type {Object}
  28044. */
  28045. this.options = options;
  28046. /**
  28047. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  28048. *
  28049. * @private
  28050. * @type {number}
  28051. * @default 1
  28052. */
  28053. this._pixelRatio = 1;
  28054. /**
  28055. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  28056. * @private
  28057. * @type {number}
  28058. * @default 1
  28059. */
  28060. this._width = 1;
  28061. /**
  28062. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  28063. * @private
  28064. * @type {number}
  28065. * @default 1
  28066. */
  28067. this._height = 1;
  28068. const depthTexture = new DepthTexture();
  28069. depthTexture.isRenderTargetTexture = true;
  28070. //depthTexture.type = FloatType;
  28071. depthTexture.name = 'depth';
  28072. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  28073. renderTarget.texture.name = 'output';
  28074. renderTarget.depthTexture = depthTexture;
  28075. /**
  28076. * The pass's render target.
  28077. *
  28078. * @type {RenderTarget}
  28079. */
  28080. this.renderTarget = renderTarget;
  28081. /**
  28082. * An optional override material for the pass.
  28083. *
  28084. * @type {Material|null}
  28085. */
  28086. this.overrideMaterial = null;
  28087. /**
  28088. * Whether the pass is transparent.
  28089. *
  28090. * @type {boolean}
  28091. * @default false
  28092. */
  28093. this.transparent = true;
  28094. /**
  28095. * Whether the pass is opaque.
  28096. *
  28097. * @type {boolean}
  28098. * @default true
  28099. */
  28100. this.opaque = true;
  28101. /**
  28102. * An optional global context for the pass.
  28103. *
  28104. * @type {ContextNode|null}
  28105. */
  28106. this.contextNode = null;
  28107. /**
  28108. * A cache for the context node.
  28109. *
  28110. * @private
  28111. * @type {?Object}
  28112. * @default null
  28113. */
  28114. this._contextNodeCache = null;
  28115. /**
  28116. * A dictionary holding the internal result textures.
  28117. *
  28118. * @private
  28119. * @type {Object<string, Texture>}
  28120. */
  28121. this._textures = {
  28122. output: renderTarget.texture,
  28123. depth: depthTexture
  28124. };
  28125. /**
  28126. * A dictionary holding the internal texture nodes.
  28127. *
  28128. * @private
  28129. * @type {Object<string, TextureNode>}
  28130. */
  28131. this._textureNodes = {};
  28132. /**
  28133. * A dictionary holding the internal depth nodes.
  28134. *
  28135. * @private
  28136. * @type {Object}
  28137. */
  28138. this._linearDepthNodes = {};
  28139. /**
  28140. * A dictionary holding the internal viewZ nodes.
  28141. *
  28142. * @private
  28143. * @type {Object}
  28144. */
  28145. this._viewZNodes = {};
  28146. /**
  28147. * A dictionary holding the texture data of the previous frame.
  28148. * Used for computing velocity/motion vectors.
  28149. *
  28150. * @private
  28151. * @type {Object<string, Texture>}
  28152. */
  28153. this._previousTextures = {};
  28154. /**
  28155. * A dictionary holding the texture nodes of the previous frame.
  28156. * Used for computing velocity/motion vectors.
  28157. *
  28158. * @private
  28159. * @type {Object<string, TextureNode>}
  28160. */
  28161. this._previousTextureNodes = {};
  28162. /**
  28163. * The `near` property of the camera as a uniform.
  28164. *
  28165. * @private
  28166. * @type {UniformNode}
  28167. */
  28168. this._cameraNear = uniform( 0 );
  28169. /**
  28170. * The `far` property of the camera as a uniform.
  28171. *
  28172. * @private
  28173. * @type {UniformNode}
  28174. */
  28175. this._cameraFar = uniform( 0 );
  28176. /**
  28177. * A MRT node configuring the MRT settings.
  28178. *
  28179. * @private
  28180. * @type {?MRTNode}
  28181. * @default null
  28182. */
  28183. this._mrt = null;
  28184. /**
  28185. * Layer object for configuring the camera that is used
  28186. * to produce the pass.
  28187. *
  28188. * @private
  28189. * @type {?Layers}
  28190. * @default null
  28191. */
  28192. this._layers = null;
  28193. /**
  28194. * Scales the resolution of the internal render target.
  28195. *
  28196. * @private
  28197. * @type {number}
  28198. * @default 1
  28199. */
  28200. this._resolutionScale = 1;
  28201. /**
  28202. * Custom viewport definition.
  28203. *
  28204. * @private
  28205. * @type {?Vector4}
  28206. * @default null
  28207. */
  28208. this._viewport = null;
  28209. /**
  28210. * Custom scissor definition.
  28211. *
  28212. * @private
  28213. * @type {?Vector4}
  28214. * @default null
  28215. */
  28216. this._scissor = null;
  28217. /**
  28218. * This flag can be used for type testing.
  28219. *
  28220. * @type {boolean}
  28221. * @readonly
  28222. * @default true
  28223. */
  28224. this.isPassNode = true;
  28225. /**
  28226. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  28227. * scene once per frame in its {@link PassNode#updateBefore} method.
  28228. *
  28229. * @type {string}
  28230. * @default 'frame'
  28231. */
  28232. this.updateBeforeType = NodeUpdateType.FRAME;
  28233. /**
  28234. * This flag is used for global cache.
  28235. *
  28236. * @type {boolean}
  28237. * @default true
  28238. */
  28239. this.global = true;
  28240. }
  28241. /**
  28242. * Sets the resolution scale for the pass.
  28243. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  28244. *
  28245. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  28246. * @return {PassNode} A reference to this pass.
  28247. */
  28248. setResolutionScale( resolutionScale ) {
  28249. this._resolutionScale = resolutionScale;
  28250. return this;
  28251. }
  28252. /**
  28253. * Gets the current resolution scale of the pass.
  28254. *
  28255. * @return {number} The current resolution scale. A value of `1` means full resolution.
  28256. */
  28257. getResolutionScale() {
  28258. return this._resolutionScale;
  28259. }
  28260. /**
  28261. * Sets the resolution for the pass.
  28262. * The resolution is a factor that is multiplied with the renderer's width and height.
  28263. *
  28264. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  28265. * @return {PassNode} A reference to this pass.
  28266. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  28267. */
  28268. setResolution( resolution ) { // @deprecated, r181
  28269. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  28270. return this.setResolutionScale( resolution );
  28271. }
  28272. /**
  28273. * Gets the current resolution of the pass.
  28274. *
  28275. * @return {number} The current resolution. A value of `1` means full resolution.
  28276. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  28277. */
  28278. getResolution() { // @deprecated, r181
  28279. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  28280. return this.getResolutionScale();
  28281. }
  28282. /**
  28283. * Sets the layer configuration that should be used when rendering the pass.
  28284. *
  28285. * @param {Layers} layers - The layers object to set.
  28286. * @return {PassNode} A reference to this pass.
  28287. */
  28288. setLayers( layers ) {
  28289. this._layers = layers;
  28290. return this;
  28291. }
  28292. /**
  28293. * Gets the current layer configuration of the pass.
  28294. *
  28295. * @return {?Layers} .
  28296. */
  28297. getLayers() {
  28298. return this._layers;
  28299. }
  28300. /**
  28301. * Sets the given MRT node to setup MRT for this pass.
  28302. *
  28303. * @param {MRTNode} mrt - The MRT object.
  28304. * @return {PassNode} A reference to this pass.
  28305. */
  28306. setMRT( mrt ) {
  28307. this._mrt = mrt;
  28308. return this;
  28309. }
  28310. /**
  28311. * Returns the current MRT node.
  28312. *
  28313. * @return {MRTNode} The current MRT node.
  28314. */
  28315. getMRT() {
  28316. return this._mrt;
  28317. }
  28318. /**
  28319. * Returns the texture for the given output name.
  28320. *
  28321. * @param {string} name - The output name to get the texture for.
  28322. * @return {Texture} The texture.
  28323. */
  28324. getTexture( name ) {
  28325. let texture = this._textures[ name ];
  28326. if ( texture === undefined ) {
  28327. const refTexture = this.renderTarget.texture;
  28328. texture = refTexture.clone();
  28329. texture.name = name;
  28330. this._textures[ name ] = texture;
  28331. this.renderTarget.textures.push( texture );
  28332. }
  28333. return texture;
  28334. }
  28335. /**
  28336. * Returns the texture holding the data of the previous frame for the given output name.
  28337. *
  28338. * @param {string} name - The output name to get the texture for.
  28339. * @return {Texture} The texture holding the data of the previous frame.
  28340. */
  28341. getPreviousTexture( name ) {
  28342. let texture = this._previousTextures[ name ];
  28343. if ( texture === undefined ) {
  28344. texture = this.getTexture( name ).clone();
  28345. this._previousTextures[ name ] = texture;
  28346. }
  28347. return texture;
  28348. }
  28349. /**
  28350. * Switches current and previous textures for the given output name.
  28351. *
  28352. * @param {string} name - The output name.
  28353. */
  28354. toggleTexture( name ) {
  28355. const prevTexture = this._previousTextures[ name ];
  28356. if ( prevTexture !== undefined ) {
  28357. const texture = this._textures[ name ];
  28358. const index = this.renderTarget.textures.indexOf( texture );
  28359. this.renderTarget.textures[ index ] = prevTexture;
  28360. this._textures[ name ] = prevTexture;
  28361. this._previousTextures[ name ] = texture;
  28362. this._textureNodes[ name ].updateTexture();
  28363. this._previousTextureNodes[ name ].updateTexture();
  28364. }
  28365. }
  28366. /**
  28367. * Returns the texture node for the given output name.
  28368. *
  28369. * @param {string} [name='output'] - The output name to get the texture node for.
  28370. * @return {TextureNode} The texture node.
  28371. */
  28372. getTextureNode( name = 'output' ) {
  28373. let textureNode = this._textureNodes[ name ];
  28374. if ( textureNode === undefined ) {
  28375. textureNode = new PassMultipleTextureNode( this, name );
  28376. textureNode.updateTexture();
  28377. this._textureNodes[ name ] = textureNode;
  28378. }
  28379. return textureNode;
  28380. }
  28381. /**
  28382. * Returns the previous texture node for the given output name.
  28383. *
  28384. * @param {string} [name='output'] - The output name to get the previous texture node for.
  28385. * @return {TextureNode} The previous texture node.
  28386. */
  28387. getPreviousTextureNode( name = 'output' ) {
  28388. let textureNode = this._previousTextureNodes[ name ];
  28389. if ( textureNode === undefined ) {
  28390. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  28391. textureNode = new PassMultipleTextureNode( this, name, true );
  28392. textureNode.updateTexture();
  28393. this._previousTextureNodes[ name ] = textureNode;
  28394. }
  28395. return textureNode;
  28396. }
  28397. /**
  28398. * Returns a viewZ node of this pass.
  28399. *
  28400. * @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.
  28401. * @return {Node} The viewZ node.
  28402. */
  28403. getViewZNode( name = 'depth' ) {
  28404. let viewZNode = this._viewZNodes[ name ];
  28405. if ( viewZNode === undefined ) {
  28406. const cameraNear = this._cameraNear;
  28407. const cameraFar = this._cameraFar;
  28408. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  28409. }
  28410. return viewZNode;
  28411. }
  28412. /**
  28413. * Returns a linear depth node of this pass.
  28414. *
  28415. * @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.
  28416. * @return {Node} The linear depth node.
  28417. */
  28418. getLinearDepthNode( name = 'depth' ) {
  28419. let linearDepthNode = this._linearDepthNodes[ name ];
  28420. if ( linearDepthNode === undefined ) {
  28421. const cameraNear = this._cameraNear;
  28422. const cameraFar = this._cameraFar;
  28423. const viewZNode = this.getViewZNode( name );
  28424. // TODO: just if ( builder.camera.isPerspectiveCamera )
  28425. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  28426. }
  28427. return linearDepthNode;
  28428. }
  28429. /**
  28430. * Precompiles the pass.
  28431. *
  28432. * Note that this method must be called after the pass configuration is complete.
  28433. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  28434. *
  28435. * @async
  28436. * @param {Renderer} renderer - The renderer.
  28437. * @return {Promise} A Promise that resolves when the compile has been finished.
  28438. * @see {@link Renderer#compileAsync}
  28439. */
  28440. async compileAsync( renderer ) {
  28441. const currentRenderTarget = renderer.getRenderTarget();
  28442. const currentMRT = renderer.getMRT();
  28443. renderer.setRenderTarget( this.renderTarget );
  28444. renderer.setMRT( this._mrt );
  28445. await renderer.compileAsync( this.scene, this.camera );
  28446. renderer.setRenderTarget( currentRenderTarget );
  28447. renderer.setMRT( currentMRT );
  28448. }
  28449. setup( { renderer } ) {
  28450. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  28451. this.renderTarget.texture.type = renderer.getOutputBufferType();
  28452. if ( renderer.reversedDepthBuffer === true ) {
  28453. this.renderTarget.depthTexture.type = FloatType;
  28454. }
  28455. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  28456. }
  28457. updateBefore( frame ) {
  28458. const { renderer } = frame;
  28459. const { scene } = this;
  28460. let camera;
  28461. let pixelRatio;
  28462. const outputRenderTarget = renderer.getOutputRenderTarget();
  28463. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  28464. pixelRatio = 1;
  28465. camera = renderer.xr.getCamera();
  28466. renderer.xr.updateCamera( camera );
  28467. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  28468. } else {
  28469. camera = this.camera;
  28470. pixelRatio = renderer.getPixelRatio();
  28471. renderer.getSize( _size );
  28472. }
  28473. this._pixelRatio = pixelRatio;
  28474. this.setSize( _size.width, _size.height );
  28475. const currentRenderTarget = renderer.getRenderTarget();
  28476. const currentMRT = renderer.getMRT();
  28477. const currentAutoClear = renderer.autoClear;
  28478. const currentTransparent = renderer.transparent;
  28479. const currentOpaque = renderer.opaque;
  28480. const currentMask = camera.layers.mask;
  28481. const currentContextNode = renderer.contextNode;
  28482. const currentOverrideMaterial = scene.overrideMaterial;
  28483. this._cameraNear.value = camera.near;
  28484. this._cameraFar.value = camera.far;
  28485. if ( this._layers !== null ) {
  28486. camera.layers.mask = this._layers.mask;
  28487. }
  28488. for ( const name in this._previousTextures ) {
  28489. this.toggleTexture( name );
  28490. }
  28491. if ( this.overrideMaterial !== null ) {
  28492. scene.overrideMaterial = this.overrideMaterial;
  28493. }
  28494. renderer.setRenderTarget( this.renderTarget );
  28495. renderer.setMRT( this._mrt );
  28496. renderer.autoClear = true;
  28497. renderer.transparent = this.transparent;
  28498. renderer.opaque = this.opaque;
  28499. if ( this.contextNode !== null ) {
  28500. if ( this._contextNodeCache === null || this._contextNodeCache.version !== this.version ) {
  28501. this._contextNodeCache = {
  28502. version: this.version,
  28503. context: context( { ...renderer.contextNode.getFlowContextData(), ...this.contextNode.getFlowContextData() } )
  28504. };
  28505. }
  28506. renderer.contextNode = this._contextNodeCache.context;
  28507. }
  28508. const currentSceneName = scene.name;
  28509. scene.name = this.name ? this.name : scene.name;
  28510. renderer.render( scene, camera );
  28511. scene.name = currentSceneName;
  28512. scene.overrideMaterial = currentOverrideMaterial;
  28513. renderer.setRenderTarget( currentRenderTarget );
  28514. renderer.setMRT( currentMRT );
  28515. renderer.autoClear = currentAutoClear;
  28516. renderer.transparent = currentTransparent;
  28517. renderer.opaque = currentOpaque;
  28518. renderer.contextNode = currentContextNode;
  28519. camera.layers.mask = currentMask;
  28520. }
  28521. /**
  28522. * Sets the size of the pass's render target. Honors the pixel ratio.
  28523. *
  28524. * @param {number} width - The width to set.
  28525. * @param {number} height - The height to set.
  28526. */
  28527. setSize( width, height ) {
  28528. this._width = width;
  28529. this._height = height;
  28530. const effectiveWidth = Math.floor( this._width * this._pixelRatio * this._resolutionScale );
  28531. const effectiveHeight = Math.floor( this._height * this._pixelRatio * this._resolutionScale );
  28532. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  28533. // scissor
  28534. if ( this._scissor !== null ) {
  28535. this.renderTarget.scissor.copy( this._scissor ).multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  28536. this.renderTarget.scissorTest = true;
  28537. } else {
  28538. this.renderTarget.scissorTest = false;
  28539. }
  28540. // viewport
  28541. if ( this._viewport !== null ) {
  28542. this.renderTarget.viewport.copy( this._viewport ).multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  28543. }
  28544. }
  28545. /**
  28546. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  28547. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  28548. * with `null` as the single argument.
  28549. *
  28550. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  28551. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  28552. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  28553. * @param {number} width - The width of the scissor box in logical pixel unit.
  28554. * @param {number} height - The height of the scissor box in logical pixel unit.
  28555. */
  28556. setScissor( x, y, width, height ) {
  28557. if ( x === null ) {
  28558. this._scissor = null;
  28559. } else {
  28560. if ( this._scissor === null ) this._scissor = new Vector4();
  28561. if ( x.isVector4 ) {
  28562. this._scissor.copy( x );
  28563. } else {
  28564. this._scissor.set( x, y, width, height );
  28565. }
  28566. }
  28567. }
  28568. /**
  28569. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  28570. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  28571. * with `null` as the single argument.
  28572. *
  28573. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  28574. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  28575. * @param {number} width - The width of the viewport in logical pixel unit.
  28576. * @param {number} height - The height of the viewport in logical pixel unit.
  28577. */
  28578. setViewport( x, y, width, height ) {
  28579. if ( x === null ) {
  28580. this._viewport = null;
  28581. } else {
  28582. if ( this._viewport === null ) this._viewport = new Vector4();
  28583. if ( x.isVector4 ) {
  28584. this._viewport.copy( x );
  28585. } else {
  28586. this._viewport.set( x, y, width, height );
  28587. }
  28588. }
  28589. }
  28590. /**
  28591. * Sets the pixel ratio the pass's render target and updates the size.
  28592. *
  28593. * @param {number} pixelRatio - The pixel ratio to set.
  28594. */
  28595. setPixelRatio( pixelRatio ) {
  28596. this._pixelRatio = pixelRatio;
  28597. this.setSize( this._width, this._height );
  28598. }
  28599. /**
  28600. * Frees internal resources. Should be called when the node is no longer in use.
  28601. */
  28602. dispose() {
  28603. this.renderTarget.dispose();
  28604. }
  28605. }
  28606. /**
  28607. * @static
  28608. * @type {'color'}
  28609. * @default 'color'
  28610. */
  28611. PassNode.COLOR = 'color';
  28612. /**
  28613. * @static
  28614. * @type {'depth'}
  28615. * @default 'depth'
  28616. */
  28617. PassNode.DEPTH = 'depth';
  28618. /**
  28619. * TSL function for creating a pass node.
  28620. *
  28621. * @tsl
  28622. * @function
  28623. * @param {Scene} scene - A reference to the scene.
  28624. * @param {Camera} camera - A reference to the camera.
  28625. * @param {Object} options - Options for the internal render target.
  28626. * @returns {PassNode}
  28627. */
  28628. const pass = ( scene, camera, options ) => new PassNode( PassNode.COLOR, scene, camera, options );
  28629. /**
  28630. * TSL function for creating a pass texture node.
  28631. *
  28632. * @tsl
  28633. * @function
  28634. * @param {PassNode} pass - The pass node.
  28635. * @param {Texture} texture - The output texture.
  28636. * @returns {PassTextureNode}
  28637. */
  28638. const passTexture = ( pass, texture ) => new PassTextureNode( pass, texture );
  28639. /**
  28640. * TSL function for creating a depth pass node.
  28641. *
  28642. * @tsl
  28643. * @function
  28644. * @param {Scene} scene - A reference to the scene.
  28645. * @param {Camera} camera - A reference to the camera.
  28646. * @param {Object} options - Options for the internal render target.
  28647. * @returns {PassNode}
  28648. */
  28649. const depthPass = ( scene, camera, options ) => new PassNode( PassNode.DEPTH, scene, camera, options );
  28650. /**
  28651. * Represents a render pass for producing a toon outline effect on compatible objects.
  28652. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  28653. * will receive the outline.
  28654. *
  28655. * ```js
  28656. * const postProcessing = new RenderPipeline( renderer );
  28657. *
  28658. * const scenePass = toonOutlinePass( scene, camera );
  28659. *
  28660. * postProcessing.outputNode = scenePass;
  28661. * ```
  28662. * @augments PassNode
  28663. */
  28664. class ToonOutlinePassNode extends PassNode {
  28665. static get type() {
  28666. return 'ToonOutlinePassNode';
  28667. }
  28668. /**
  28669. * Constructs a new outline pass node.
  28670. *
  28671. * @param {Scene} scene - A reference to the scene.
  28672. * @param {Camera} camera - A reference to the camera.
  28673. * @param {Node} colorNode - Defines the outline's color.
  28674. * @param {Node} thicknessNode - Defines the outline's thickness.
  28675. * @param {Node} alphaNode - Defines the outline's alpha.
  28676. */
  28677. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  28678. super( PassNode.COLOR, scene, camera );
  28679. /**
  28680. * Defines the outline's color.
  28681. *
  28682. * @type {Node}
  28683. */
  28684. this.colorNode = colorNode;
  28685. /**
  28686. * Defines the outline's thickness.
  28687. *
  28688. * @type {Node}
  28689. */
  28690. this.thicknessNode = thicknessNode;
  28691. /**
  28692. * Defines the outline's alpha.
  28693. *
  28694. * @type {Node}
  28695. */
  28696. this.alphaNode = alphaNode;
  28697. /**
  28698. * An internal material cache.
  28699. *
  28700. * @private
  28701. * @type {WeakMap<Material, NodeMaterial>}
  28702. */
  28703. this._materialCache = new WeakMap();
  28704. /**
  28705. * The name of this pass.
  28706. *
  28707. * @type {string}
  28708. * @default 'Outline Pass'
  28709. */
  28710. this.name = 'Outline Pass';
  28711. }
  28712. updateBefore( frame ) {
  28713. const { renderer } = frame;
  28714. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  28715. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  28716. // only render outline for supported materials
  28717. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  28718. if ( material.wireframe === false ) {
  28719. const outlineMaterial = this._getOutlineMaterial( material );
  28720. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  28721. }
  28722. }
  28723. // default
  28724. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  28725. } );
  28726. super.updateBefore( frame );
  28727. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  28728. }
  28729. /**
  28730. * Creates the material used for outline rendering.
  28731. *
  28732. * @private
  28733. * @return {NodeMaterial} The outline material.
  28734. */
  28735. _createMaterial() {
  28736. const material = new NodeMaterial();
  28737. material.isMeshToonOutlineMaterial = true;
  28738. material.name = 'Toon_Outline';
  28739. material.side = BackSide;
  28740. // vertex node
  28741. const outlineNormal = normalLocal.negate();
  28742. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  28743. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  28744. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  28745. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  28746. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  28747. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  28748. // color node
  28749. material.colorNode = vec4( this.colorNode, this.alphaNode );
  28750. return material;
  28751. }
  28752. /**
  28753. * For the given toon material, this method returns a corresponding
  28754. * outline material.
  28755. *
  28756. * @private
  28757. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  28758. * @return {NodeMaterial} The outline material.
  28759. */
  28760. _getOutlineMaterial( originalMaterial ) {
  28761. let outlineMaterial = this._materialCache.get( originalMaterial );
  28762. if ( outlineMaterial === undefined ) {
  28763. outlineMaterial = this._createMaterial();
  28764. this._materialCache.set( originalMaterial, outlineMaterial );
  28765. }
  28766. return outlineMaterial;
  28767. }
  28768. }
  28769. /**
  28770. * TSL function for creating a toon outline pass node.
  28771. *
  28772. * @tsl
  28773. * @function
  28774. * @param {Scene} scene - A reference to the scene.
  28775. * @param {Camera} camera - A reference to the camera.
  28776. * @param {Color} color - Defines the outline's color.
  28777. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  28778. * @param {number} [alpha=1] - Defines the outline's alpha.
  28779. * @returns {ToonOutlinePassNode}
  28780. */
  28781. const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) );
  28782. /**
  28783. * Linear tone mapping, exposure only.
  28784. *
  28785. * @tsl
  28786. * @function
  28787. * @param {Node<vec3>} color - The color that should be tone mapped.
  28788. * @param {Node<float>} exposure - The exposure.
  28789. * @return {Node<vec3>} The tone mapped color.
  28790. */
  28791. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28792. return color.mul( exposure ).clamp();
  28793. } ).setLayout( {
  28794. name: 'linearToneMapping',
  28795. type: 'vec3',
  28796. inputs: [
  28797. { name: 'color', type: 'vec3' },
  28798. { name: 'exposure', type: 'float' }
  28799. ]
  28800. } );
  28801. /**
  28802. * Reinhard tone mapping.
  28803. *
  28804. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  28805. *
  28806. * @tsl
  28807. * @function
  28808. * @param {Node<vec3>} color - The color that should be tone mapped.
  28809. * @param {Node<float>} exposure - The exposure.
  28810. * @return {Node<vec3>} The tone mapped color.
  28811. */
  28812. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28813. color = color.mul( exposure );
  28814. return color.div( color.add( 1.0 ) ).clamp();
  28815. } ).setLayout( {
  28816. name: 'reinhardToneMapping',
  28817. type: 'vec3',
  28818. inputs: [
  28819. { name: 'color', type: 'vec3' },
  28820. { name: 'exposure', type: 'float' }
  28821. ]
  28822. } );
  28823. /**
  28824. * Cineon tone mapping.
  28825. *
  28826. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  28827. *
  28828. * @tsl
  28829. * @function
  28830. * @param {Node<vec3>} color - The color that should be tone mapped.
  28831. * @param {Node<float>} exposure - The exposure.
  28832. * @return {Node<vec3>} The tone mapped color.
  28833. */
  28834. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28835. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  28836. color = color.mul( exposure );
  28837. color = color.sub( 0.004 ).max( 0.0 );
  28838. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  28839. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  28840. return a.div( b ).pow( 2.2 );
  28841. } ).setLayout( {
  28842. name: 'cineonToneMapping',
  28843. type: 'vec3',
  28844. inputs: [
  28845. { name: 'color', type: 'vec3' },
  28846. { name: 'exposure', type: 'float' }
  28847. ]
  28848. } );
  28849. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  28850. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  28851. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  28852. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  28853. return a.div( b );
  28854. } );
  28855. /**
  28856. * ACESFilmic tone mapping.
  28857. *
  28858. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  28859. *
  28860. * @tsl
  28861. * @function
  28862. * @param {Node<vec3>} color - The color that should be tone mapped.
  28863. * @param {Node<float>} exposure - The exposure.
  28864. * @return {Node<vec3>} The tone mapped color.
  28865. */
  28866. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28867. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  28868. const ACESInputMat = mat3(
  28869. 0.59719, 0.35458, 0.04823,
  28870. 0.07600, 0.90834, 0.01566,
  28871. 0.02840, 0.13383, 0.83777
  28872. );
  28873. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  28874. const ACESOutputMat = mat3(
  28875. 1.60475, -0.53108, -0.07367,
  28876. -0.10208, 1.10813, -605e-5,
  28877. -327e-5, -0.07276, 1.07602
  28878. );
  28879. color = color.mul( exposure ).div( 0.6 );
  28880. color = ACESInputMat.mul( color );
  28881. // Apply RRT and ODT
  28882. color = RRTAndODTFit( color );
  28883. color = ACESOutputMat.mul( color );
  28884. // Clamp to [0, 1]
  28885. return color.clamp();
  28886. } ).setLayout( {
  28887. name: 'acesFilmicToneMapping',
  28888. type: 'vec3',
  28889. inputs: [
  28890. { name: 'color', type: 'vec3' },
  28891. { name: 'exposure', type: 'float' }
  28892. ]
  28893. } );
  28894. 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 ) );
  28895. 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 ) );
  28896. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28897. const x = vec3( x_immutable ).toVar();
  28898. const x2 = vec3( x.mul( x ) ).toVar();
  28899. const x4 = vec3( x2.mul( x2 ) ).toVar();
  28900. 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 ) ) ) );
  28901. } );
  28902. /**
  28903. * AgX tone mapping.
  28904. *
  28905. * @tsl
  28906. * @function
  28907. * @param {Node<vec3>} color - The color that should be tone mapped.
  28908. * @param {Node<float>} exposure - The exposure.
  28909. * @return {Node<vec3>} The tone mapped color.
  28910. */
  28911. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28912. const colortone = vec3( color ).toVar();
  28913. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  28914. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  28915. const AgxMinEv = float( -12.47393 );
  28916. const AgxMaxEv = float( 4.026069 );
  28917. colortone.mulAssign( exposure );
  28918. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  28919. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  28920. colortone.assign( max$1( colortone, 1e-10 ) );
  28921. colortone.assign( log2( colortone ) );
  28922. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  28923. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  28924. colortone.assign( agxDefaultContrastApprox( colortone ) );
  28925. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  28926. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  28927. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  28928. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  28929. return colortone;
  28930. } ).setLayout( {
  28931. name: 'agxToneMapping',
  28932. type: 'vec3',
  28933. inputs: [
  28934. { name: 'color', type: 'vec3' },
  28935. { name: 'exposure', type: 'float' }
  28936. ]
  28937. } );
  28938. /**
  28939. * Neutral tone mapping.
  28940. *
  28941. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  28942. *
  28943. * @tsl
  28944. * @function
  28945. * @param {Node<vec3>} color - The color that should be tone mapped.
  28946. * @param {Node<float>} exposure - The exposure.
  28947. * @return {Node<vec3>} The tone mapped color.
  28948. */
  28949. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28950. const StartCompression = float( 0.8 - 0.04 );
  28951. const Desaturation = float( 0.15 );
  28952. color = color.mul( exposure );
  28953. const x = min$1( color.r, min$1( color.g, color.b ) );
  28954. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  28955. color.subAssign( offset );
  28956. const peak = max$1( color.r, max$1( color.g, color.b ) );
  28957. If( peak.lessThan( StartCompression ), () => {
  28958. return color;
  28959. } );
  28960. const d = sub( 1, StartCompression );
  28961. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  28962. color.mulAssign( newPeak.div( peak ) );
  28963. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  28964. return mix( color, vec3( newPeak ), g );
  28965. } ).setLayout( {
  28966. name: 'neutralToneMapping',
  28967. type: 'vec3',
  28968. inputs: [
  28969. { name: 'color', type: 'vec3' },
  28970. { name: 'exposure', type: 'float' }
  28971. ]
  28972. } );
  28973. /**
  28974. * This class represents native code sections. It is the base
  28975. * class for modules like {@link FunctionNode} which allows to implement
  28976. * functions with native shader languages.
  28977. *
  28978. * @augments Node
  28979. */
  28980. class CodeNode extends Node {
  28981. static get type() {
  28982. return 'CodeNode';
  28983. }
  28984. /**
  28985. * Constructs a new code node.
  28986. *
  28987. * @param {string} [code=''] - The native code.
  28988. * @param {Array<Node>} [includes=[]] - An array of includes.
  28989. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28990. */
  28991. constructor( code = '', includes = [], language = '' ) {
  28992. super( 'code' );
  28993. /**
  28994. * This flag can be used for type testing.
  28995. *
  28996. * @type {boolean}
  28997. * @readonly
  28998. * @default true
  28999. */
  29000. this.isCodeNode = true;
  29001. /**
  29002. * This flag is used for global cache.
  29003. *
  29004. * @type {boolean}
  29005. * @default true
  29006. */
  29007. this.global = true;
  29008. /**
  29009. * The native code.
  29010. *
  29011. * @type {string}
  29012. * @default ''
  29013. */
  29014. this.code = code;
  29015. /**
  29016. * An array of includes
  29017. *
  29018. * @type {Array<Node>}
  29019. * @default []
  29020. */
  29021. this.includes = includes;
  29022. /**
  29023. * The used language.
  29024. *
  29025. * @type {('js'|'wgsl'|'glsl')}
  29026. * @default ''
  29027. */
  29028. this.language = language;
  29029. }
  29030. /**
  29031. * Sets the includes of this code node.
  29032. *
  29033. * @param {Array<Node>} includes - The includes to set.
  29034. * @return {CodeNode} A reference to this node.
  29035. */
  29036. setIncludes( includes ) {
  29037. this.includes = includes;
  29038. return this;
  29039. }
  29040. /**
  29041. * Returns the includes of this code node.
  29042. *
  29043. * @param {NodeBuilder} builder - The current node builder.
  29044. * @return {Array<Node>} The includes.
  29045. */
  29046. getIncludes( /*builder*/ ) {
  29047. return this.includes;
  29048. }
  29049. generate( builder ) {
  29050. const includes = this.getIncludes( builder );
  29051. for ( const include of includes ) {
  29052. include.build( builder );
  29053. }
  29054. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  29055. nodeCode.code = this.code;
  29056. return nodeCode.code;
  29057. }
  29058. serialize( data ) {
  29059. super.serialize( data );
  29060. data.code = this.code;
  29061. data.language = this.language;
  29062. }
  29063. deserialize( data ) {
  29064. super.deserialize( data );
  29065. this.code = data.code;
  29066. this.language = data.language;
  29067. }
  29068. }
  29069. /**
  29070. * TSL function for creating a code node.
  29071. *
  29072. * @tsl
  29073. * @function
  29074. * @param {string} [code] - The native code.
  29075. * @param {?Array<Node>} [includes=[]] - An array of includes.
  29076. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  29077. * @returns {CodeNode}
  29078. */
  29079. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  29080. /**
  29081. * TSL function for creating a JS code node.
  29082. *
  29083. * @tsl
  29084. * @function
  29085. * @param {string} src - The native code.
  29086. * @param {Array<Node>} includes - An array of includes.
  29087. * @returns {CodeNode}
  29088. */
  29089. const js = ( src, includes ) => code( src, includes, 'js' );
  29090. /**
  29091. * TSL function for creating a WGSL code node.
  29092. *
  29093. * @tsl
  29094. * @function
  29095. * @param {string} src - The native code.
  29096. * @param {Array<Node>} includes - An array of includes.
  29097. * @returns {CodeNode}
  29098. */
  29099. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  29100. /**
  29101. * TSL function for creating a GLSL code node.
  29102. *
  29103. * @tsl
  29104. * @function
  29105. * @param {string} src - The native code.
  29106. * @param {Array<Node>} includes - An array of includes.
  29107. * @returns {CodeNode}
  29108. */
  29109. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  29110. /**
  29111. * This class represents a native shader function. It can be used to implement
  29112. * certain aspects of a node material with native shader code. There are two predefined
  29113. * TSL functions for easier usage.
  29114. *
  29115. * - `wgslFn`: Creates a WGSL function node.
  29116. * - `glslFn`: Creates a GLSL function node.
  29117. *
  29118. * A basic example with one include looks like so:
  29119. *
  29120. * ```js
  29121. * const desaturateWGSLFn = wgslFn( `
  29122. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  29123. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  29124. * return vec3<f32>( dot( lum, color ) );
  29125. * }`
  29126. *);
  29127. * const someWGSLFn = wgslFn( `
  29128. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  29129. * return desaturate( color );
  29130. * }
  29131. * `, [ desaturateWGSLFn ] );
  29132. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  29133. *```
  29134. * @augments CodeNode
  29135. */
  29136. class FunctionNode extends CodeNode {
  29137. static get type() {
  29138. return 'FunctionNode';
  29139. }
  29140. /**
  29141. * Constructs a new function node.
  29142. *
  29143. * @param {string} [code=''] - The native code.
  29144. * @param {Array<Node>} [includes=[]] - An array of includes.
  29145. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  29146. */
  29147. constructor( code = '', includes = [], language = '' ) {
  29148. super( code, includes, language );
  29149. }
  29150. /**
  29151. * Returns the type of this function node.
  29152. *
  29153. * @param {NodeBuilder} builder - The current node builder.
  29154. * @return {string} The type.
  29155. */
  29156. generateNodeType( builder ) {
  29157. return this.getNodeFunction( builder ).type;
  29158. }
  29159. /**
  29160. * Returns the type of a member of this function node.
  29161. *
  29162. * @param {NodeBuilder} builder - The current node builder.
  29163. * @param {string} name - The name of the member.
  29164. * @return {string} The type of the member.
  29165. */
  29166. getMemberType( builder, name ) {
  29167. const type = this.getNodeType( builder );
  29168. const structType = builder.getStructTypeNode( type );
  29169. return structType.getMemberType( builder, name );
  29170. }
  29171. /**
  29172. * Returns the inputs of this function node.
  29173. *
  29174. * @param {NodeBuilder} builder - The current node builder.
  29175. * @return {Array<NodeFunctionInput>} The inputs.
  29176. */
  29177. getInputs( builder ) {
  29178. return this.getNodeFunction( builder ).inputs;
  29179. }
  29180. /**
  29181. * Returns the node function for this function node.
  29182. *
  29183. * @param {NodeBuilder} builder - The current node builder.
  29184. * @return {NodeFunction} The node function.
  29185. */
  29186. getNodeFunction( builder ) {
  29187. const nodeData = builder.getDataFromNode( this );
  29188. let nodeFunction = nodeData.nodeFunction;
  29189. if ( nodeFunction === undefined ) {
  29190. nodeFunction = builder.parser.parseFunction( this.code );
  29191. nodeData.nodeFunction = nodeFunction;
  29192. }
  29193. return nodeFunction;
  29194. }
  29195. generate( builder, output ) {
  29196. super.generate( builder );
  29197. const nodeFunction = this.getNodeFunction( builder );
  29198. const name = nodeFunction.name;
  29199. const type = nodeFunction.type;
  29200. const nodeCode = builder.getCodeFromNode( this, type );
  29201. if ( name !== '' ) {
  29202. // use a custom property name
  29203. nodeCode.name = name;
  29204. }
  29205. const propertyName = builder.getPropertyName( nodeCode );
  29206. const code = this.getNodeFunction( builder ).getCode( propertyName );
  29207. nodeCode.code = code + '\n';
  29208. if ( output === 'property' ) {
  29209. return propertyName;
  29210. } else {
  29211. return builder.format( `${ propertyName }()`, type, output );
  29212. }
  29213. }
  29214. }
  29215. const nativeFn = ( code, includes = [], language = '' ) => {
  29216. for ( let i = 0; i < includes.length; i ++ ) {
  29217. const include = includes[ i ];
  29218. // TSL Function: glslFn, wgslFn
  29219. if ( typeof include === 'function' ) {
  29220. includes[ i ] = include.functionNode;
  29221. }
  29222. }
  29223. const functionNode = new FunctionNode( code, includes, language );
  29224. const fn = ( ...params ) => functionNode.call( ...params );
  29225. fn.functionNode = functionNode;
  29226. return fn;
  29227. };
  29228. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  29229. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  29230. /**
  29231. * Returns a node that represents the `z` coordinate in view space
  29232. * for the current fragment. It's a different representation of the
  29233. * default depth value.
  29234. *
  29235. * This value can be part of a computation that defines how the fog
  29236. * density increases when moving away from the camera.
  29237. *
  29238. * @param {NodeBuilder} builder - The current node builder.
  29239. * @return {Node} The viewZ node.
  29240. */
  29241. function getViewZNode( builder ) {
  29242. let viewZ;
  29243. const getViewZ = builder.context.getViewZ;
  29244. if ( getViewZ !== undefined ) {
  29245. viewZ = getViewZ( this );
  29246. }
  29247. return ( viewZ || positionView.z ).negate();
  29248. }
  29249. /**
  29250. * Constructs a new range factor node.
  29251. *
  29252. * @tsl
  29253. * @function
  29254. * @param {Node} near - Defines the near value.
  29255. * @param {Node} far - Defines the far value.
  29256. */
  29257. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  29258. const viewZ = getViewZNode( builder );
  29259. return smoothstep( near, far, viewZ );
  29260. } );
  29261. /**
  29262. * Represents an exponential squared fog. This type of fog gives
  29263. * a clear view near the camera and a faster than exponentially
  29264. * densening fog farther from the camera.
  29265. *
  29266. * @tsl
  29267. * @function
  29268. * @param {Node} density - Defines the fog density.
  29269. */
  29270. const densityFogFactor = Fn( ( [ density ], builder ) => {
  29271. const viewZ = getViewZNode( builder );
  29272. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  29273. } );
  29274. /**
  29275. * Constructs a new height fog factor node. This fog factor requires a Y-up coordinate system.
  29276. *
  29277. * @tsl
  29278. * @function
  29279. * @param {Node} density - Defines the fog density.
  29280. * @param {Node} height - The height threshold in world space. Everything below this y-coordinate is affected by fog.
  29281. */
  29282. const exponentialHeightFogFactor = Fn( ( [ density, height ], builder ) => {
  29283. const viewZ = getViewZNode( builder );
  29284. const distance = height.sub( positionWorld.y ).max( 0 ).toConst();
  29285. const m = distance.mul( viewZ ).toConst();
  29286. return density.mul( density, m, m ).negate().exp().oneMinus();
  29287. } );
  29288. /**
  29289. * This class can be used to configure a fog for the scene.
  29290. * Nodes of this type are assigned to `Scene.fogNode`.
  29291. *
  29292. * @tsl
  29293. * @function
  29294. * @param {Node} color - Defines the color of the fog.
  29295. * @param {Node} factor - Defines how the fog is factored in the scene.
  29296. */
  29297. const fog = Fn( ( [ color, factor ] ) => {
  29298. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  29299. } );
  29300. let min = null;
  29301. let max = null;
  29302. /**
  29303. * `RangeNode` generates random instanced attribute data in a defined range.
  29304. * An exemplary use case for this utility node is to generate random per-instance
  29305. * colors:
  29306. * ```js
  29307. * const material = new MeshBasicNodeMaterial();
  29308. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  29309. * const mesh = new InstancedMesh( geometry, material, count );
  29310. * ```
  29311. * @augments Node
  29312. */
  29313. class RangeNode extends Node {
  29314. static get type() {
  29315. return 'RangeNode';
  29316. }
  29317. /**
  29318. * Constructs a new range node.
  29319. *
  29320. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29321. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29322. */
  29323. constructor( minNode = float(), maxNode = float() ) {
  29324. super();
  29325. /**
  29326. * A node defining the lower bound of the range.
  29327. *
  29328. * @type {Node<any>}
  29329. * @default float()
  29330. */
  29331. this.minNode = minNode;
  29332. /**
  29333. * A node defining the upper bound of the range.
  29334. *
  29335. * @type {Node<any>}
  29336. * @default float()
  29337. */
  29338. this.maxNode = maxNode;
  29339. }
  29340. /**
  29341. * Returns the vector length which is computed based on the range definition.
  29342. *
  29343. * @param {NodeBuilder} builder - The current node builder.
  29344. * @return {number} The vector length.
  29345. */
  29346. getVectorLength( builder ) {
  29347. const minNode = this.getConstNode( this.minNode );
  29348. const maxNode = this.getConstNode( this.maxNode );
  29349. const minLength = builder.getTypeLength( getValueType( minNode.value ) );
  29350. const maxLength = builder.getTypeLength( getValueType( maxNode.value ) );
  29351. return minLength > maxLength ? minLength : maxLength;
  29352. }
  29353. /**
  29354. * This method is overwritten since the node type is inferred from range definition.
  29355. *
  29356. * @param {NodeBuilder} builder - The current node builder.
  29357. * @return {string} The node type.
  29358. */
  29359. generateNodeType( builder ) {
  29360. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  29361. }
  29362. /**
  29363. * Returns a constant node from the given node by traversing it.
  29364. *
  29365. * @param {Node} node - The node to traverse.
  29366. * @returns {Node} The constant node, if found.
  29367. */
  29368. getConstNode( node ) {
  29369. let output = null;
  29370. node.traverse( n => {
  29371. if ( n.isConstNode === true ) {
  29372. output = n;
  29373. }
  29374. } );
  29375. if ( output === null ) {
  29376. throw new NodeError( 'THREE.TSL: No "ConstNode" found in node graph.', this.stackTrace );
  29377. }
  29378. return output;
  29379. }
  29380. setup( builder ) {
  29381. const object = builder.object;
  29382. let output = null;
  29383. if ( object.count > 1 ) {
  29384. const minNode = this.getConstNode( this.minNode );
  29385. const maxNode = this.getConstNode( this.maxNode );
  29386. const minValue = minNode.value;
  29387. const maxValue = maxNode.value;
  29388. const minLength = builder.getTypeLength( getValueType( minValue ) );
  29389. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  29390. min = min || new Vector4();
  29391. max = max || new Vector4();
  29392. min.setScalar( 0 );
  29393. max.setScalar( 0 );
  29394. if ( minLength === 1 ) min.setScalar( minValue );
  29395. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  29396. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  29397. if ( maxLength === 1 ) max.setScalar( maxValue );
  29398. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  29399. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  29400. const stride = 4;
  29401. const length = stride * object.count;
  29402. const array = new Float32Array( length );
  29403. for ( let i = 0; i < length; i ++ ) {
  29404. const index = i % stride;
  29405. const minElementValue = min.getComponent( index );
  29406. const maxElementValue = max.getComponent( index );
  29407. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  29408. }
  29409. const nodeType = this.getNodeType( builder );
  29410. const uniformBufferSize = object.count * 4 * 4; // count * 4 components * 4 bytes (float)
  29411. if ( uniformBufferSize <= builder.getUniformBufferLimit() ) {
  29412. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  29413. } else {
  29414. // TODO: Improve anonymous buffer attribute creation removing this part
  29415. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  29416. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  29417. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  29418. }
  29419. } else {
  29420. output = float( 0 );
  29421. }
  29422. return output;
  29423. }
  29424. }
  29425. /**
  29426. * TSL function for creating a range node.
  29427. *
  29428. * @tsl
  29429. * @function
  29430. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29431. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29432. * @returns {RangeNode}
  29433. */
  29434. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  29435. /**
  29436. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  29437. * about the currently running dispatch and/or the device it is running on.
  29438. *
  29439. * This node can only be used with a WebGPU backend.
  29440. *
  29441. * @augments Node
  29442. */
  29443. class ComputeBuiltinNode extends Node {
  29444. static get type() {
  29445. return 'ComputeBuiltinNode';
  29446. }
  29447. /**
  29448. * Constructs a new compute builtin node.
  29449. *
  29450. * @param {string} builtinName - The built-in name.
  29451. * @param {string} nodeType - The node type.
  29452. */
  29453. constructor( builtinName, nodeType ) {
  29454. super( nodeType );
  29455. /**
  29456. * The built-in name.
  29457. *
  29458. * @private
  29459. * @type {string}
  29460. */
  29461. this._builtinName = builtinName;
  29462. }
  29463. /**
  29464. * This method is overwritten since hash is derived from the built-in name.
  29465. *
  29466. * @param {NodeBuilder} builder - The current node builder.
  29467. * @return {string} The hash.
  29468. */
  29469. getHash( builder ) {
  29470. return this.getBuiltinName( builder );
  29471. }
  29472. /**
  29473. * This method is overwritten since the node type is simply derived from `nodeType`..
  29474. *
  29475. * @param {NodeBuilder} builder - The current node builder.
  29476. * @return {string} The node type.
  29477. */
  29478. generateNodeType( /*builder*/ ) {
  29479. return this.nodeType;
  29480. }
  29481. /**
  29482. * Sets the builtin name.
  29483. *
  29484. * @param {string} builtinName - The built-in name.
  29485. * @return {ComputeBuiltinNode} A reference to this node.
  29486. */
  29487. setBuiltinName( builtinName ) {
  29488. this._builtinName = builtinName;
  29489. return this;
  29490. }
  29491. /**
  29492. * Returns the builtin name.
  29493. *
  29494. * @param {NodeBuilder} builder - The current node builder.
  29495. * @return {string} The builtin name.
  29496. */
  29497. getBuiltinName( /*builder*/ ) {
  29498. return this._builtinName;
  29499. }
  29500. /**
  29501. * Whether the current node builder has the builtin or not.
  29502. *
  29503. * @param {NodeBuilder} builder - The current node builder.
  29504. * @return {boolean} Whether the builder has the builtin or not.
  29505. */
  29506. hasBuiltin( builder ) {
  29507. return builder.hasBuiltin( this._builtinName );
  29508. }
  29509. generate( builder, output ) {
  29510. const builtinName = this.getBuiltinName( builder );
  29511. const nodeType = this.getNodeType( builder );
  29512. if ( builder.shaderStage === 'compute' ) {
  29513. return builder.format( builtinName, nodeType, output );
  29514. } else {
  29515. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  29516. return builder.generateConst( nodeType );
  29517. }
  29518. }
  29519. serialize( data ) {
  29520. super.serialize( data );
  29521. data.global = this.global;
  29522. data._builtinName = this._builtinName;
  29523. }
  29524. deserialize( data ) {
  29525. super.deserialize( data );
  29526. this.global = data.global;
  29527. this._builtinName = data._builtinName;
  29528. }
  29529. }
  29530. /**
  29531. * TSL function for creating a compute builtin node.
  29532. *
  29533. * @tsl
  29534. * @function
  29535. * @param {string} name - The built-in name.
  29536. * @param {string} nodeType - The node type.
  29537. * @returns {ComputeBuiltinNode}
  29538. */
  29539. const computeBuiltin = ( name, nodeType ) => new ComputeBuiltinNode( name, nodeType );
  29540. /**
  29541. * Represents the number of workgroups dispatched by the compute shader.
  29542. * ```js
  29543. * // Run 512 invocations/threads with a workgroup size of 128.
  29544. * const computeFn = Fn(() => {
  29545. *
  29546. * // numWorkgroups.x = 4
  29547. * storageBuffer.element(0).assign(numWorkgroups.x)
  29548. *
  29549. * })().compute(512, [128]);
  29550. *
  29551. * // Run 512 invocations/threads with the default workgroup size of 64.
  29552. * const computeFn = Fn(() => {
  29553. *
  29554. * // numWorkgroups.x = 8
  29555. * storageBuffer.element(0).assign(numWorkgroups.x)
  29556. *
  29557. * })().compute(512);
  29558. * ```
  29559. *
  29560. * @tsl
  29561. * @type {ComputeBuiltinNode<uvec3>}
  29562. */
  29563. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  29564. /**
  29565. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  29566. * ```js
  29567. * // Execute 12 compute threads with a workgroup size of 3.
  29568. * const computeFn = Fn( () => {
  29569. *
  29570. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  29571. *
  29572. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  29573. *
  29574. * } ).Else( () => {
  29575. *
  29576. * storageBuffer.element( instanceIndex ).assign( 0 );
  29577. *
  29578. * } );
  29579. *
  29580. * } )().compute( 12, [ 3 ] );
  29581. *
  29582. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  29583. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  29584. * ```
  29585. *
  29586. * @tsl
  29587. * @type {ComputeBuiltinNode<uvec3>}
  29588. */
  29589. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  29590. /**
  29591. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  29592. *
  29593. * @tsl
  29594. * @type {ComputeBuiltinNode<uvec3>}
  29595. */
  29596. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  29597. /**
  29598. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  29599. *
  29600. * @tsl
  29601. * @type {ComputeBuiltinNode<uvec3>}
  29602. */
  29603. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  29604. /**
  29605. * A device dependent variable that exposes the size of the current invocation's subgroup.
  29606. *
  29607. * @tsl
  29608. * @type {ComputeBuiltinNode<uint>}
  29609. */
  29610. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  29611. /**
  29612. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  29613. *
  29614. * This node can only be used with a WebGPU backend.
  29615. *
  29616. * @augments Node
  29617. */
  29618. class BarrierNode extends Node {
  29619. /**
  29620. * Constructs a new barrier node.
  29621. *
  29622. * @param {string} scope - The scope defines the behavior of the node.
  29623. */
  29624. constructor( scope ) {
  29625. super();
  29626. this.scope = scope;
  29627. this.isBarrierNode = true;
  29628. }
  29629. generate( builder ) {
  29630. const { scope } = this;
  29631. const { renderer } = builder;
  29632. builder.allowEarlyReturns = false;
  29633. if ( renderer.backend.isWebGLBackend === true ) {
  29634. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  29635. } else {
  29636. builder.addLineFlowCode( `${scope}Barrier()`, this );
  29637. }
  29638. }
  29639. }
  29640. /**
  29641. * TSL function for creating a barrier node.
  29642. *
  29643. * @tsl
  29644. * @function
  29645. * @param {string} scope - The scope defines the behavior of the node..
  29646. * @returns {BarrierNode}
  29647. */
  29648. const barrier = nodeProxy( BarrierNode );
  29649. /**
  29650. * TSL function for creating a workgroup barrier. All compute shader
  29651. * invocations must wait for each invocation within a workgroup to
  29652. * complete before the barrier can be surpassed.
  29653. *
  29654. * @tsl
  29655. * @function
  29656. * @returns {BarrierNode}
  29657. */
  29658. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  29659. /**
  29660. * TSL function for creating a storage barrier. All invocations must
  29661. * wait for each access to variables within the 'storage' address space
  29662. * to complete before the barrier can be passed.
  29663. *
  29664. * @tsl
  29665. * @function
  29666. * @returns {BarrierNode}
  29667. */
  29668. const storageBarrier = () => barrier( 'storage' ).toStack();
  29669. /**
  29670. * TSL function for creating a texture barrier. All invocations must
  29671. * wait for each access to variables within the 'texture' address space
  29672. * to complete before the barrier can be passed.
  29673. *
  29674. * @tsl
  29675. * @function
  29676. * @returns {BarrierNode}
  29677. */
  29678. const textureBarrier = () => barrier( 'texture' ).toStack();
  29679. /**
  29680. * Represents an element of a 'workgroup' scoped buffer.
  29681. *
  29682. * @augments ArrayElementNode
  29683. */
  29684. class WorkgroupInfoElementNode extends ArrayElementNode {
  29685. /**
  29686. * Constructs a new workgroup info element node.
  29687. *
  29688. * @param {Node} workgroupInfoNode - The workgroup info node.
  29689. * @param {Node} indexNode - The index node that defines the element access.
  29690. */
  29691. constructor( workgroupInfoNode, indexNode ) {
  29692. super( workgroupInfoNode, indexNode );
  29693. /**
  29694. * This flag can be used for type testing.
  29695. *
  29696. * @type {boolean}
  29697. * @readonly
  29698. * @default true
  29699. */
  29700. this.isWorkgroupInfoElementNode = true;
  29701. }
  29702. generate( builder, output ) {
  29703. let snippet;
  29704. const isAssignContext = builder.context.assign;
  29705. snippet = super.generate( builder );
  29706. if ( isAssignContext !== true ) {
  29707. const type = this.getNodeType( builder );
  29708. snippet = builder.format( snippet, type, output );
  29709. }
  29710. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  29711. return snippet;
  29712. }
  29713. }
  29714. /**
  29715. * A node allowing the user to create a 'workgroup' scoped buffer within the
  29716. * context of a compute shader. Typically, workgroup scoped buffers are
  29717. * created to hold data that is transferred from a global storage scope into
  29718. * a local workgroup scope. For invocations within a workgroup, data
  29719. * access speeds on 'workgroup' scoped buffers can be significantly faster
  29720. * than similar access operations on globally accessible storage buffers.
  29721. *
  29722. * This node can only be used with a WebGPU backend.
  29723. *
  29724. * @augments Node
  29725. */
  29726. class WorkgroupInfoNode extends Node {
  29727. /**
  29728. * Constructs a new buffer scoped to type scope.
  29729. *
  29730. * @param {string} scope - TODO.
  29731. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  29732. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  29733. */
  29734. constructor( scope, bufferType, bufferCount = 0 ) {
  29735. super( bufferType );
  29736. /**
  29737. * The buffer type.
  29738. *
  29739. * @type {string}
  29740. */
  29741. this.bufferType = bufferType;
  29742. /**
  29743. * The buffer count.
  29744. *
  29745. * @type {number}
  29746. * @default 0
  29747. */
  29748. this.bufferCount = bufferCount;
  29749. /**
  29750. * This flag can be used for type testing.
  29751. *
  29752. * @type {boolean}
  29753. * @readonly
  29754. * @default true
  29755. */
  29756. this.isWorkgroupInfoNode = true;
  29757. /**
  29758. * The data type of the array buffer.
  29759. *
  29760. * @type {string}
  29761. */
  29762. this.elementType = bufferType;
  29763. /**
  29764. * TODO.
  29765. *
  29766. * @type {string}
  29767. */
  29768. this.scope = scope;
  29769. /**
  29770. * The name of the workgroup scoped buffer.
  29771. *
  29772. * @type {string}
  29773. * @default ''
  29774. */
  29775. this.name = '';
  29776. }
  29777. /**
  29778. * Sets the name of this node.
  29779. *
  29780. * @param {string} name - The name to set.
  29781. * @return {WorkgroupInfoNode} A reference to this node.
  29782. */
  29783. setName( name ) {
  29784. this.name = name;
  29785. return this;
  29786. }
  29787. /**
  29788. * Sets the name/label of this node.
  29789. *
  29790. * @deprecated
  29791. * @param {string} name - The name to set.
  29792. * @return {WorkgroupInfoNode} A reference to this node.
  29793. */
  29794. label( name ) {
  29795. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  29796. return this.setName( name );
  29797. }
  29798. /**
  29799. * Sets the scope of this node.
  29800. *
  29801. * @param {string} scope - The scope to set.
  29802. * @return {WorkgroupInfoNode} A reference to this node.
  29803. */
  29804. setScope( scope ) {
  29805. this.scope = scope;
  29806. return this;
  29807. }
  29808. /**
  29809. * The data type of the array buffer.
  29810. *
  29811. * @return {string} The element type.
  29812. */
  29813. getElementType() {
  29814. return this.elementType;
  29815. }
  29816. /**
  29817. * Overwrites the default implementation since the input type
  29818. * is inferred from the scope.
  29819. *
  29820. * @param {NodeBuilder} builder - The current node builder.
  29821. * @return {string} The input type.
  29822. */
  29823. getInputType( /*builder*/ ) {
  29824. return `${this.scope}Array`;
  29825. }
  29826. /**
  29827. * This method can be used to access elements via an index node.
  29828. *
  29829. * @param {IndexNode} indexNode - indexNode.
  29830. * @return {WorkgroupInfoElementNode} A reference to an element.
  29831. */
  29832. element( indexNode ) {
  29833. return new WorkgroupInfoElementNode( this, indexNode );
  29834. }
  29835. generate( builder ) {
  29836. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  29837. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  29838. }
  29839. }
  29840. /**
  29841. * TSL function for creating a workgroup info node.
  29842. * Creates a new 'workgroup' scoped array buffer.
  29843. *
  29844. * @tsl
  29845. * @function
  29846. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  29847. * @param {number} [count=0] - The number of elements in the buffer.
  29848. * @returns {WorkgroupInfoNode}
  29849. */
  29850. const workgroupArray = ( type, count ) => new WorkgroupInfoNode( 'Workgroup', type, count );
  29851. /**
  29852. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  29853. * within a shader. In an atomic function, any modification to an atomic variable will
  29854. * occur as an indivisible step with a defined order relative to other modifications.
  29855. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  29856. * atomic operations will not interfere with each other.
  29857. *
  29858. * This node can only be used with a WebGPU backend.
  29859. *
  29860. * @augments Node
  29861. */
  29862. class AtomicFunctionNode extends Node {
  29863. static get type() {
  29864. return 'AtomicFunctionNode';
  29865. }
  29866. /**
  29867. * Constructs a new atomic function node.
  29868. *
  29869. * @param {string} method - The signature of the atomic function to construct.
  29870. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29871. * @param {Node} valueNode - The value that mutates the atomic variable.
  29872. */
  29873. constructor( method, pointerNode, valueNode ) {
  29874. super( 'uint' );
  29875. /**
  29876. * The signature of the atomic function to construct.
  29877. *
  29878. * @type {string}
  29879. */
  29880. this.method = method;
  29881. /**
  29882. * An atomic variable or element of an atomic buffer.
  29883. *
  29884. * @type {Node}
  29885. */
  29886. this.pointerNode = pointerNode;
  29887. /**
  29888. * A value that modifies the atomic variable.
  29889. *
  29890. * @type {Node}
  29891. */
  29892. this.valueNode = valueNode;
  29893. /**
  29894. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  29895. *
  29896. * @type {boolean}
  29897. * @default true
  29898. */
  29899. this.parents = true;
  29900. }
  29901. /**
  29902. * Overwrites the default implementation to return the type of
  29903. * the pointer node.
  29904. *
  29905. * @param {NodeBuilder} builder - The current node builder.
  29906. * @return {string} The input type.
  29907. */
  29908. getInputType( builder ) {
  29909. return this.pointerNode.getNodeType( builder );
  29910. }
  29911. /**
  29912. * Overwritten since the node type is inferred from the input type.
  29913. *
  29914. * @param {NodeBuilder} builder - The current node builder.
  29915. * @return {string} The node type.
  29916. */
  29917. generateNodeType( builder ) {
  29918. return this.getInputType( builder );
  29919. }
  29920. generate( builder ) {
  29921. const properties = builder.getNodeProperties( this );
  29922. const parents = properties.parents;
  29923. const method = this.method;
  29924. const type = this.getNodeType( builder );
  29925. const inputType = this.getInputType( builder );
  29926. const a = this.pointerNode;
  29927. const b = this.valueNode;
  29928. const params = [];
  29929. params.push( `&${ a.build( builder, inputType ) }` );
  29930. if ( b !== null ) {
  29931. params.push( b.build( builder, inputType ) );
  29932. }
  29933. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  29934. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  29935. if ( isVoid ) {
  29936. builder.addLineFlowCode( methodSnippet, this );
  29937. } else {
  29938. if ( properties.constNode === undefined ) {
  29939. properties.constNode = expression( methodSnippet, type ).toConst();
  29940. }
  29941. return properties.constNode.build( builder );
  29942. }
  29943. }
  29944. }
  29945. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  29946. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  29947. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  29948. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  29949. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  29950. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  29951. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  29952. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  29953. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  29954. /**
  29955. * TSL function for creating an atomic function node.
  29956. *
  29957. * @tsl
  29958. * @function
  29959. * @param {string} method - The signature of the atomic function to construct.
  29960. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29961. * @param {Node} valueNode - The value that mutates the atomic variable.
  29962. * @returns {AtomicFunctionNode}
  29963. */
  29964. const atomicNode = nodeProxy( AtomicFunctionNode );
  29965. /**
  29966. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  29967. *
  29968. * @tsl
  29969. * @function
  29970. * @param {string} method - The signature of the atomic function to construct.
  29971. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29972. * @param {Node} valueNode - The value that mutates the atomic variable.
  29973. * @returns {AtomicFunctionNode}
  29974. */
  29975. const atomicFunc = ( method, pointerNode, valueNode ) => {
  29976. return atomicNode( method, pointerNode, valueNode ).toStack();
  29977. };
  29978. /**
  29979. * Loads the value stored in the atomic variable.
  29980. *
  29981. * @tsl
  29982. * @function
  29983. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29984. * @returns {AtomicFunctionNode}
  29985. */
  29986. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  29987. /**
  29988. * Stores a value in the atomic variable.
  29989. *
  29990. * @tsl
  29991. * @function
  29992. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29993. * @param {Node} valueNode - The value that mutates the atomic variable.
  29994. * @returns {AtomicFunctionNode}
  29995. */
  29996. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  29997. /**
  29998. * Increments the value stored in the atomic variable.
  29999. *
  30000. * @tsl
  30001. * @function
  30002. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30003. * @param {Node} valueNode - The value that mutates the atomic variable.
  30004. * @returns {AtomicFunctionNode}
  30005. */
  30006. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  30007. /**
  30008. * Decrements the value stored in the atomic variable.
  30009. *
  30010. * @tsl
  30011. * @function
  30012. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30013. * @param {Node} valueNode - The value that mutates the atomic variable.
  30014. * @returns {AtomicFunctionNode}
  30015. */
  30016. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  30017. /**
  30018. * Stores in an atomic variable the maximum between its current value and a parameter.
  30019. *
  30020. * @tsl
  30021. * @function
  30022. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30023. * @param {Node} valueNode - The value that mutates the atomic variable.
  30024. * @returns {AtomicFunctionNode}
  30025. */
  30026. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  30027. /**
  30028. * Stores in an atomic variable the minimum between its current value and a parameter.
  30029. *
  30030. * @tsl
  30031. * @function
  30032. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30033. * @param {Node} valueNode - The value that mutates the atomic variable.
  30034. * @returns {AtomicFunctionNode}
  30035. */
  30036. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  30037. /**
  30038. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  30039. *
  30040. * @tsl
  30041. * @function
  30042. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30043. * @param {Node} valueNode - The value that mutates the atomic variable.
  30044. * @returns {AtomicFunctionNode}
  30045. */
  30046. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  30047. /**
  30048. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  30049. *
  30050. * @tsl
  30051. * @function
  30052. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30053. * @param {Node} valueNode - The value that mutates the atomic variable.
  30054. * @returns {AtomicFunctionNode}
  30055. */
  30056. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  30057. /**
  30058. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  30059. *
  30060. * @tsl
  30061. * @function
  30062. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  30063. * @param {Node} valueNode - The value that mutates the atomic variable.
  30064. * @returns {AtomicFunctionNode}
  30065. */
  30066. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  30067. /**
  30068. * This class represents a set of built in WGSL shader functions that sync
  30069. * synchronously execute an operation across a subgroup, or 'warp', of compute
  30070. * or fragment shader invocations within a workgroup. Typically, these functions
  30071. * will synchronously execute an operation using data from all active invocations
  30072. * within the subgroup, then broadcast that result to all active invocations. In
  30073. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  30074. * (DirectX/HLSL) or warp intrinsics (CUDA).
  30075. *
  30076. * @augments TempNode
  30077. */
  30078. class SubgroupFunctionNode extends TempNode {
  30079. static get type() {
  30080. return 'SubgroupFunctionNode';
  30081. }
  30082. /**
  30083. * Constructs a new function node.
  30084. *
  30085. * @param {string} method - The subgroup/wave intrinsic method to construct.
  30086. * @param {Node} [aNode=null] - The method's first argument.
  30087. * @param {Node} [bNode=null] - The method's second argument.
  30088. */
  30089. constructor( method, aNode = null, bNode = null ) {
  30090. super();
  30091. /**
  30092. * The subgroup/wave intrinsic method to construct.
  30093. *
  30094. * @type {string}
  30095. */
  30096. this.method = method;
  30097. /**
  30098. * The method's first argument.
  30099. *
  30100. * @type {Node}
  30101. */
  30102. this.aNode = aNode;
  30103. /**
  30104. * The method's second argument.
  30105. *
  30106. * @type {Node}
  30107. */
  30108. this.bNode = bNode;
  30109. }
  30110. getInputType( builder ) {
  30111. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  30112. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  30113. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  30114. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  30115. if ( aLen > bLen ) {
  30116. return aType;
  30117. } else {
  30118. return bType;
  30119. }
  30120. }
  30121. generateNodeType( builder ) {
  30122. const method = this.method;
  30123. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  30124. return 'bool';
  30125. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  30126. return 'uvec4';
  30127. } else {
  30128. return this.getInputType( builder );
  30129. }
  30130. }
  30131. generate( builder, output ) {
  30132. const method = this.method;
  30133. const type = this.getNodeType( builder );
  30134. const inputType = this.getInputType( builder );
  30135. const a = this.aNode;
  30136. const b = this.bNode;
  30137. const params = [];
  30138. if (
  30139. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  30140. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  30141. method === SubgroupFunctionNode.QUAD_BROADCAST
  30142. ) {
  30143. const bType = b.getNodeType( builder );
  30144. params.push(
  30145. a.build( builder, type ),
  30146. b.build( builder, bType === 'float' ? 'int' : type )
  30147. );
  30148. } else if (
  30149. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  30150. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  30151. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  30152. ) {
  30153. params.push(
  30154. a.build( builder, type ),
  30155. b.build( builder, 'uint' )
  30156. );
  30157. } else {
  30158. if ( a !== null ) params.push( a.build( builder, inputType ) );
  30159. if ( b !== null ) params.push( b.build( builder, inputType ) );
  30160. }
  30161. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  30162. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  30163. }
  30164. serialize( data ) {
  30165. super.serialize( data );
  30166. data.method = this.method;
  30167. }
  30168. deserialize( data ) {
  30169. super.deserialize( data );
  30170. this.method = data.method;
  30171. }
  30172. }
  30173. // 0 inputs
  30174. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  30175. // 1 input
  30176. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  30177. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  30178. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  30179. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  30180. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  30181. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  30182. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  30183. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  30184. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  30185. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  30186. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  30187. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  30188. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  30189. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  30190. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  30191. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  30192. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  30193. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  30194. // 2 inputs
  30195. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  30196. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  30197. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  30198. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  30199. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  30200. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  30201. /**
  30202. * Returns true if this invocation has the lowest subgroup_invocation_id
  30203. * among active invocations in the subgroup.
  30204. *
  30205. * @tsl
  30206. * @method
  30207. * @return {bool} The result of the computation.
  30208. */
  30209. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  30210. /**
  30211. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  30212. * is 1 if pred is true for that active invocation and 0 otherwise.
  30213. *
  30214. * @tsl
  30215. * @method
  30216. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  30217. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  30218. */
  30219. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  30220. /**
  30221. * A reduction that adds e among all active invocations and returns that result.
  30222. *
  30223. * @tsl
  30224. * @method
  30225. * @param {number} e - The value provided to the reduction by the current invocation.
  30226. * @return {number} The accumulated result of the reduction operation.
  30227. */
  30228. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  30229. /**
  30230. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30231. *
  30232. * @tsl
  30233. * @method
  30234. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30235. * @return {number} The accumulated result of the inclusive scan operation.
  30236. */
  30237. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  30238. /**
  30239. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  30240. *
  30241. * @tsl
  30242. * @method
  30243. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30244. * @return {number} The accumulated result of the exclusive scan operation.
  30245. */
  30246. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  30247. /**
  30248. * A reduction that multiplies e among all active invocations and returns that result.
  30249. *
  30250. * @tsl
  30251. * @method
  30252. * @param {number} e - The value provided to the reduction by the current invocation.
  30253. * @return {number} The accumulated result of the reduction operation.
  30254. */
  30255. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  30256. /**
  30257. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30258. *
  30259. * @tsl
  30260. * @method
  30261. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30262. * @return {number} The accumulated result of the inclusive scan operation.
  30263. */
  30264. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  30265. /**
  30266. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  30267. *
  30268. * @tsl
  30269. * @method
  30270. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30271. * @return {number} The accumulated result of the exclusive scan operation.
  30272. */
  30273. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  30274. /**
  30275. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  30276. *
  30277. * @tsl
  30278. * @method
  30279. * @param {number} e - The value provided to the reduction by the current invocation.
  30280. * @return {number} The result of the reduction operation.
  30281. */
  30282. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  30283. /**
  30284. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  30285. *
  30286. * @tsl
  30287. * @method
  30288. * @param {number} e - The value provided to the reduction by the current invocation.
  30289. * @return {number} The result of the reduction operation.
  30290. */
  30291. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  30292. /**
  30293. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  30294. *
  30295. * @tsl
  30296. * @method
  30297. * @param {number} e - The value provided to the reduction by the current invocation.
  30298. * @return {number} The result of the reduction operation.
  30299. */
  30300. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  30301. /**
  30302. * A reduction that performs a min of e among all active invocations and returns that result.
  30303. *
  30304. * @tsl
  30305. * @method
  30306. * @param {number} e - The value provided to the reduction by the current invocation.
  30307. * @return {number} The result of the reduction operation.
  30308. */
  30309. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  30310. /**
  30311. * A reduction that performs a max of e among all active invocations and returns that result.
  30312. *
  30313. * @tsl
  30314. * @method
  30315. * @param {number} e - The value provided to the reduction by the current invocation.
  30316. * @return {number} The result of the reduction operation.
  30317. */
  30318. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  30319. /**
  30320. * Returns true if e is true for all active invocations in the subgroup.
  30321. *
  30322. * @tsl
  30323. * @method
  30324. * @return {bool} The result of the computation.
  30325. */
  30326. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  30327. /**
  30328. * Returns true if e is true for any active invocation in the subgroup
  30329. *
  30330. * @tsl
  30331. * @method
  30332. * @return {bool} The result of the computation.
  30333. */
  30334. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  30335. /**
  30336. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  30337. *
  30338. * @tsl
  30339. * @method
  30340. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  30341. * @param {number} id - The subgroup invocation to broadcast from.
  30342. * @return {number} The broadcast value.
  30343. */
  30344. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  30345. /**
  30346. * Swaps e between invocations in the quad in the X direction.
  30347. *
  30348. * @tsl
  30349. * @method
  30350. * @param {number} e - The value to swap from the current invocation.
  30351. * @return {number} The value received from the swap operation.
  30352. */
  30353. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  30354. /**
  30355. * Swaps e between invocations in the quad in the Y direction.
  30356. *
  30357. * @tsl
  30358. * @method
  30359. * @param {number} e - The value to swap from the current invocation.
  30360. * @return {number} The value received from the swap operation.
  30361. */
  30362. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  30363. /**
  30364. * Swaps e between invocations in the quad diagonally.
  30365. *
  30366. * @tsl
  30367. * @method
  30368. * @param {number} e - The value to swap from the current invocation.
  30369. * @return {number} The value received from the swap operation.
  30370. */
  30371. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  30372. /**
  30373. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  30374. *
  30375. * @tsl
  30376. * @method
  30377. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  30378. * @param {number} id - The subgroup invocation to broadcast from.
  30379. * @return {number} The broadcast value.
  30380. */
  30381. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  30382. /**
  30383. * Returns v from the active invocation whose subgroup_invocation_id matches id
  30384. *
  30385. * @tsl
  30386. * @method
  30387. * @param {number} v - The value to return from subgroup invocation id^mask.
  30388. * @param {number} id - The subgroup invocation which returns the value v.
  30389. * @return {number} The broadcast value.
  30390. */
  30391. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  30392. /**
  30393. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  30394. *
  30395. * @tsl
  30396. * @method
  30397. * @param {number} v - The value to return from subgroup invocation id^mask.
  30398. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  30399. * @return {number} The broadcast value.
  30400. */
  30401. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  30402. /**
  30403. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  30404. *
  30405. * @tsl
  30406. * @method
  30407. * @param {number} v - The value to return from subgroup invocation id^mask.
  30408. * @param {number} delta - A value that offsets the current in.
  30409. * @return {number} The broadcast value.
  30410. */
  30411. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  30412. /**
  30413. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  30414. *
  30415. * @tsl
  30416. * @method
  30417. * @param {number} v - The value to return from subgroup invocation id^mask.
  30418. * @param {number} delta - A value that offsets the current subgroup invocation.
  30419. * @return {number} The broadcast value.
  30420. */
  30421. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  30422. /**
  30423. * Broadcasts e from the quad invocation with id equal to id.
  30424. *
  30425. * @tsl
  30426. * @method
  30427. * @param {number} e - The value to broadcast.
  30428. * @return {number} The broadcast value.
  30429. */
  30430. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  30431. let uniformsLib;
  30432. function getLightData( light ) {
  30433. uniformsLib = uniformsLib || new WeakMap();
  30434. let uniforms = uniformsLib.get( light );
  30435. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  30436. return uniforms;
  30437. }
  30438. /**
  30439. * TSL function for getting a shadow matrix uniform node for the given light.
  30440. *
  30441. * @tsl
  30442. * @function
  30443. * @param {Light} light -The light source.
  30444. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  30445. */
  30446. function lightShadowMatrix( light ) {
  30447. const data = getLightData( light );
  30448. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  30449. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  30450. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  30451. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  30452. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  30453. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  30454. light.shadow.camera.updateProjectionMatrix();
  30455. }
  30456. light.shadow.updateMatrices( light );
  30457. }
  30458. return light.shadow.matrix;
  30459. } ) );
  30460. }
  30461. /**
  30462. * TSL function for getting projected uv coordinates for the given light.
  30463. * Relevant when using maps with spot lights.
  30464. *
  30465. * @tsl
  30466. * @function
  30467. * @param {Light} light -The light source.
  30468. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  30469. * @returns {Node<vec3>} The projected uvs.
  30470. */
  30471. function lightProjectionUV( light, position = positionWorld ) {
  30472. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  30473. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  30474. return projectionUV;
  30475. }
  30476. /**
  30477. * TSL function for getting the position in world space for the given light.
  30478. *
  30479. * @tsl
  30480. * @function
  30481. * @param {Light} light -The light source.
  30482. * @returns {UniformNode<vec3>} The light's position in world space.
  30483. */
  30484. function lightPosition( light ) {
  30485. const data = getLightData( light );
  30486. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  30487. }
  30488. /**
  30489. * TSL function for getting the light target position in world space for the given light.
  30490. *
  30491. * @tsl
  30492. * @function
  30493. * @param {Light} light -The light source.
  30494. * @returns {UniformNode<vec3>} The light target position in world space.
  30495. */
  30496. function lightTargetPosition( light ) {
  30497. const data = getLightData( light );
  30498. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  30499. }
  30500. /**
  30501. * TSL function for getting the position in view space for the given light.
  30502. *
  30503. * @tsl
  30504. * @function
  30505. * @param {Light} light - The light source.
  30506. * @returns {UniformNode<vec3>} The light's position in view space.
  30507. */
  30508. function lightViewPosition( light ) {
  30509. const data = getLightData( light );
  30510. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  30511. self.value = self.value || new Vector3();
  30512. self.value.setFromMatrixPosition( light.matrixWorld );
  30513. self.value.applyMatrix4( camera.matrixWorldInverse );
  30514. } ) );
  30515. }
  30516. /**
  30517. * TSL function for getting the light target direction for the given light.
  30518. *
  30519. * @tsl
  30520. * @function
  30521. * @param {Light} light -The light source.
  30522. * @returns {Node<vec3>} The light's target direction.
  30523. */
  30524. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  30525. const sortLights = ( lights ) => {
  30526. return lights.sort( ( a, b ) => a.id - b.id );
  30527. };
  30528. const getLightNodeById = ( id, lightNodes ) => {
  30529. for ( const lightNode of lightNodes ) {
  30530. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  30531. return lightNode;
  30532. }
  30533. }
  30534. return null;
  30535. };
  30536. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  30537. const _hashData = [];
  30538. /**
  30539. * This node represents the scene's lighting and manages the lighting model's life cycle
  30540. * for the current build 3D object. It is responsible for computing the total outgoing
  30541. * light in a given lighting context.
  30542. *
  30543. * @augments Node
  30544. */
  30545. class LightsNode extends Node {
  30546. static get type() {
  30547. return 'LightsNode';
  30548. }
  30549. /**
  30550. * Constructs a new lights node.
  30551. */
  30552. constructor() {
  30553. super( 'vec3' );
  30554. /**
  30555. * A node representing the total diffuse light.
  30556. *
  30557. * @type {Node<vec3>}
  30558. */
  30559. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  30560. /**
  30561. * A node representing the total specular light.
  30562. *
  30563. * @type {Node<vec3>}
  30564. */
  30565. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  30566. /**
  30567. * A node representing the outgoing light.
  30568. *
  30569. * @type {Node<vec3>}
  30570. */
  30571. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  30572. /**
  30573. * An array representing the lights in the scene.
  30574. *
  30575. * @private
  30576. * @type {Array<Light>}
  30577. */
  30578. this._lights = [];
  30579. /**
  30580. * For each light in the scene, this node will create a
  30581. * corresponding light node.
  30582. *
  30583. * @private
  30584. * @type {?Array<LightingNode>}
  30585. * @default null
  30586. */
  30587. this._lightNodes = null;
  30588. /**
  30589. * A hash for identifying the current light nodes setup.
  30590. *
  30591. * @private
  30592. * @type {?string}
  30593. * @default null
  30594. */
  30595. this._lightNodesHash = null;
  30596. /**
  30597. * `LightsNode` sets this property to `true` by default.
  30598. *
  30599. * @type {boolean}
  30600. * @default true
  30601. */
  30602. this.global = true;
  30603. }
  30604. /**
  30605. * Overwrites the default {@link Node#customCacheKey} implementation by including
  30606. * light data into the cache key.
  30607. *
  30608. * @return {number} The custom cache key.
  30609. */
  30610. customCacheKey() {
  30611. const lights = this._lights;
  30612. for ( let i = 0; i < lights.length; i ++ ) {
  30613. const light = lights[ i ];
  30614. _hashData.push( light.id );
  30615. _hashData.push( light.castShadow ? 1 : 0 );
  30616. if ( light.isSpotLight === true ) {
  30617. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  30618. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  30619. _hashData.push( hashMap, hashColorNode );
  30620. }
  30621. }
  30622. const cacheKey = hashArray( _hashData );
  30623. _hashData.length = 0;
  30624. return cacheKey;
  30625. }
  30626. /**
  30627. * Computes a hash value for identifying the current light nodes setup.
  30628. *
  30629. * @param {NodeBuilder} builder - A reference to the current node builder.
  30630. * @return {string} The computed hash.
  30631. */
  30632. getHash( builder ) {
  30633. if ( this._lightNodesHash === null ) {
  30634. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30635. const hash = [];
  30636. for ( const lightNode of this._lightNodes ) {
  30637. hash.push( lightNode.getHash() );
  30638. }
  30639. this._lightNodesHash = 'lights-' + hash.join( ',' );
  30640. }
  30641. return this._lightNodesHash;
  30642. }
  30643. analyze( builder ) {
  30644. const properties = builder.getNodeProperties( this );
  30645. for ( const node of properties.nodes ) {
  30646. node.build( builder );
  30647. }
  30648. properties.outputNode.build( builder );
  30649. }
  30650. /**
  30651. * Creates lighting nodes for each scene light. This makes it possible to further
  30652. * process lights in the node system.
  30653. *
  30654. * @param {NodeBuilder} builder - A reference to the current node builder.
  30655. */
  30656. setupLightsNode( builder ) {
  30657. const lightNodes = [];
  30658. const previousLightNodes = this._lightNodes;
  30659. const lights = sortLights( this._lights );
  30660. const nodeLibrary = builder.renderer.library;
  30661. for ( const light of lights ) {
  30662. if ( light.isNode ) {
  30663. lightNodes.push( nodeObject( light ) );
  30664. } else {
  30665. let lightNode = null;
  30666. if ( previousLightNodes !== null ) {
  30667. lightNode = getLightNodeById( light.id, previousLightNodes );
  30668. }
  30669. if ( lightNode === null ) {
  30670. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  30671. if ( lightNodeClass === null ) {
  30672. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  30673. continue;
  30674. }
  30675. if ( _lightsNodeRef.has( light ) === false ) {
  30676. _lightsNodeRef.set( light, new lightNodeClass( light ) );
  30677. }
  30678. lightNode = _lightsNodeRef.get( light );
  30679. }
  30680. lightNodes.push( lightNode );
  30681. }
  30682. }
  30683. this._lightNodes = lightNodes;
  30684. }
  30685. /**
  30686. * Sets up a direct light in the lighting model.
  30687. *
  30688. * @param {Object} builder - The builder object containing the context and stack.
  30689. * @param {Object} lightNode - The light node.
  30690. * @param {Object} lightData - The light object containing color and direction properties.
  30691. */
  30692. setupDirectLight( builder, lightNode, lightData ) {
  30693. const { lightingModel, reflectedLight } = builder.context;
  30694. lightingModel.direct( {
  30695. ...lightData,
  30696. lightNode,
  30697. reflectedLight
  30698. }, builder );
  30699. }
  30700. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  30701. const { lightingModel, reflectedLight } = builder.context;
  30702. lightingModel.directRectArea( {
  30703. ...lightData,
  30704. lightNode,
  30705. reflectedLight
  30706. }, builder );
  30707. }
  30708. /**
  30709. * Setups the internal lights by building all respective
  30710. * light nodes.
  30711. *
  30712. * @param {NodeBuilder} builder - A reference to the current node builder.
  30713. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  30714. */
  30715. setupLights( builder, lightNodes ) {
  30716. for ( const lightNode of lightNodes ) {
  30717. lightNode.build( builder );
  30718. }
  30719. }
  30720. getLightNodes( builder ) {
  30721. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30722. return this._lightNodes;
  30723. }
  30724. /**
  30725. * The implementation makes sure that for each light in the scene
  30726. * there is a corresponding light node. By building the light nodes
  30727. * and evaluating the lighting model the outgoing light is computed.
  30728. *
  30729. * @param {NodeBuilder} builder - A reference to the current node builder.
  30730. * @return {Node<vec3>} A node representing the outgoing light.
  30731. */
  30732. setup( builder ) {
  30733. const currentLightsNode = builder.lightsNode;
  30734. builder.lightsNode = this;
  30735. let outgoingLightNode = this.outgoingLightNode;
  30736. const context = builder.context;
  30737. const lightingModel = context.lightingModel;
  30738. const properties = builder.getNodeProperties( this );
  30739. if ( lightingModel ) {
  30740. const { totalDiffuseNode, totalSpecularNode } = this;
  30741. context.outgoingLight = outgoingLightNode;
  30742. const stack = builder.addStack();
  30743. properties.nodes = stack.nodes;
  30744. lightingModel.start( builder );
  30745. const { backdrop, backdropAlpha } = context;
  30746. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  30747. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  30748. if ( backdrop !== null ) {
  30749. if ( backdropAlpha !== null ) {
  30750. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  30751. } else {
  30752. totalDiffuse = vec3( backdrop );
  30753. }
  30754. }
  30755. totalDiffuseNode.assign( totalDiffuse );
  30756. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  30757. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  30758. lightingModel.finish( builder );
  30759. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  30760. } else {
  30761. properties.nodes = [];
  30762. }
  30763. builder.lightsNode = currentLightsNode;
  30764. return outgoingLightNode;
  30765. }
  30766. /**
  30767. * Configures this node with an array of lights.
  30768. *
  30769. * @param {Array<Light>} lights - An array of lights.
  30770. * @return {LightsNode} A reference to this node.
  30771. */
  30772. setLights( lights ) {
  30773. this._lights = lights;
  30774. this._lightNodes = null;
  30775. this._lightNodesHash = null;
  30776. return this;
  30777. }
  30778. /**
  30779. * Returns an array of the scene's lights.
  30780. *
  30781. * @return {Array<Light>} The scene's lights.
  30782. */
  30783. getLights() {
  30784. return this._lights;
  30785. }
  30786. /**
  30787. * Whether the scene has lights or not.
  30788. *
  30789. * @type {boolean}
  30790. */
  30791. get hasLights() {
  30792. return this._lights.length > 0;
  30793. }
  30794. }
  30795. /**
  30796. * TSL function for creating an instance of `LightsNode` and configuring
  30797. * it with the given array of lights.
  30798. *
  30799. * @tsl
  30800. * @function
  30801. * @param {Array<Light>} lights - An array of lights.
  30802. * @return {LightsNode} The created lights node.
  30803. */
  30804. const lights = ( lights = [] ) => new LightsNode().setLights( lights );
  30805. /**
  30806. * Base class for all shadow nodes.
  30807. *
  30808. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  30809. * Lighting nodes might share the same shadow node type or use specific ones depending on
  30810. * their requirements.
  30811. *
  30812. * @augments Node
  30813. */
  30814. class ShadowBaseNode extends Node {
  30815. static get type() {
  30816. return 'ShadowBaseNode';
  30817. }
  30818. /**
  30819. * Constructs a new shadow base node.
  30820. *
  30821. * @param {Light} light - The shadow casting light.
  30822. */
  30823. constructor( light ) {
  30824. super();
  30825. /**
  30826. * The shadow casting light.
  30827. *
  30828. * @type {Light}
  30829. */
  30830. this.light = light;
  30831. /**
  30832. * Overwritten since shadows are updated by default per render.
  30833. *
  30834. * @type {string}
  30835. * @default 'render'
  30836. */
  30837. this.updateBeforeType = NodeUpdateType.RENDER;
  30838. /**
  30839. * This flag can be used for type testing.
  30840. *
  30841. * @type {boolean}
  30842. * @readonly
  30843. * @default true
  30844. */
  30845. this.isShadowBaseNode = true;
  30846. }
  30847. /**
  30848. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  30849. *
  30850. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  30851. */
  30852. setupShadowPosition( { context, material } ) {
  30853. // Use assign inside an Fn()
  30854. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  30855. }
  30856. }
  30857. /**
  30858. * TSL object that represents the vertex position in world space during the shadow pass.
  30859. *
  30860. * @tsl
  30861. * @type {Node<vec3>}
  30862. */
  30863. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  30864. /**
  30865. * Saves the state of the given renderer and stores it into the given state object.
  30866. *
  30867. * If not state object is provided, the function creates one.
  30868. *
  30869. * @private
  30870. * @function
  30871. * @param {Renderer} renderer - The renderer.
  30872. * @param {Object} [state={}] - The state.
  30873. * @return {Object} The state.
  30874. */
  30875. function saveRendererState( renderer, state = {} ) {
  30876. state.toneMapping = renderer.toneMapping;
  30877. state.toneMappingExposure = renderer.toneMappingExposure;
  30878. state.outputColorSpace = renderer.outputColorSpace;
  30879. state.renderTarget = renderer.getRenderTarget();
  30880. state.activeCubeFace = renderer.getActiveCubeFace();
  30881. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  30882. state.renderObjectFunction = renderer.getRenderObjectFunction();
  30883. state.pixelRatio = renderer.getPixelRatio();
  30884. state.mrt = renderer.getMRT();
  30885. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  30886. state.clearAlpha = renderer.getClearAlpha();
  30887. state.autoClear = renderer.autoClear;
  30888. state.scissorTest = renderer.getScissorTest();
  30889. return state;
  30890. }
  30891. /**
  30892. * Saves the state of the given renderer and stores it into the given state object.
  30893. * Besides, the function also resets the state of the renderer to its default values.
  30894. *
  30895. * If not state object is provided, the function creates one.
  30896. *
  30897. * @private
  30898. * @function
  30899. * @param {Renderer} renderer - The renderer.
  30900. * @param {Object} [state={}] - The state.
  30901. * @return {Object} The state.
  30902. */
  30903. function resetRendererState( renderer, state ) {
  30904. state = saveRendererState( renderer, state );
  30905. renderer.setMRT( null );
  30906. renderer.setRenderObjectFunction( null );
  30907. renderer.setClearColor( 0x000000, 1 );
  30908. renderer.autoClear = true;
  30909. return state;
  30910. }
  30911. /**
  30912. * Restores the state of the given renderer from the given state object.
  30913. *
  30914. * @private
  30915. * @function
  30916. * @param {Renderer} renderer - The renderer.
  30917. * @param {Object} state - The state to restore.
  30918. */
  30919. function restoreRendererState( renderer, state ) {
  30920. renderer.toneMapping = state.toneMapping;
  30921. renderer.toneMappingExposure = state.toneMappingExposure;
  30922. renderer.outputColorSpace = state.outputColorSpace;
  30923. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  30924. renderer.setRenderObjectFunction( state.renderObjectFunction );
  30925. renderer.setPixelRatio( state.pixelRatio );
  30926. renderer.setMRT( state.mrt );
  30927. renderer.setClearColor( state.clearColor, state.clearAlpha );
  30928. renderer.autoClear = state.autoClear;
  30929. renderer.setScissorTest( state.scissorTest );
  30930. }
  30931. /**
  30932. * Saves the state of the given scene and stores it into the given state object.
  30933. *
  30934. * If not state object is provided, the function creates one.
  30935. *
  30936. * @private
  30937. * @function
  30938. * @param {Scene} scene - The scene.
  30939. * @param {Object} [state={}] - The state.
  30940. * @return {Object} The state.
  30941. */
  30942. function saveSceneState( scene, state = {} ) {
  30943. state.background = scene.background;
  30944. state.backgroundNode = scene.backgroundNode;
  30945. state.overrideMaterial = scene.overrideMaterial;
  30946. return state;
  30947. }
  30948. /**
  30949. * Saves the state of the given scene and stores it into the given state object.
  30950. * Besides, the function also resets the state of the scene to its default values.
  30951. *
  30952. * If not state object is provided, the function creates one.
  30953. *
  30954. * @private
  30955. * @function
  30956. * @param {Scene} scene - The scene.
  30957. * @param {Object} [state={}] - The state.
  30958. * @return {Object} The state.
  30959. */
  30960. function resetSceneState( scene, state ) {
  30961. state = saveSceneState( scene, state );
  30962. scene.background = null;
  30963. scene.backgroundNode = null;
  30964. scene.overrideMaterial = null;
  30965. return state;
  30966. }
  30967. /**
  30968. * Restores the state of the given scene from the given state object.
  30969. *
  30970. * @private
  30971. * @function
  30972. * @param {Scene} scene - The scene.
  30973. * @param {Object} state - The state to restore.
  30974. */
  30975. function restoreSceneState( scene, state ) {
  30976. scene.background = state.background;
  30977. scene.backgroundNode = state.backgroundNode;
  30978. scene.overrideMaterial = state.overrideMaterial;
  30979. }
  30980. /**
  30981. * Saves the state of the given renderer and scene and stores it into the given state object.
  30982. *
  30983. * If not state object is provided, the function creates one.
  30984. *
  30985. * @private
  30986. * @function
  30987. * @param {Renderer} renderer - The renderer.
  30988. * @param {Scene} scene - The scene.
  30989. * @param {Object} [state={}] - The state.
  30990. * @return {Object} The state.
  30991. */
  30992. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  30993. state = saveRendererState( renderer, state );
  30994. state = saveSceneState( scene, state );
  30995. return state;
  30996. }
  30997. /**
  30998. * Saves the state of the given renderer and scene and stores it into the given state object.
  30999. * Besides, the function also resets the state of the renderer and scene to its default values.
  31000. *
  31001. * If not state object is provided, the function creates one.
  31002. *
  31003. * @private
  31004. * @function
  31005. * @param {Renderer} renderer - The renderer.
  31006. * @param {Scene} scene - The scene.
  31007. * @param {Object} [state={}] - The state.
  31008. * @return {Object} The state.
  31009. */
  31010. function resetRendererAndSceneState( renderer, scene, state ) {
  31011. state = resetRendererState( renderer, state );
  31012. state = resetSceneState( scene, state );
  31013. return state;
  31014. }
  31015. /**
  31016. * Restores the state of the given renderer and scene from the given state object.
  31017. *
  31018. * @private
  31019. * @function
  31020. * @param {Renderer} renderer - The renderer.
  31021. * @param {Scene} scene - The scene.
  31022. * @param {Object} state - The state to restore.
  31023. */
  31024. function restoreRendererAndSceneState( renderer, scene, state ) {
  31025. restoreRendererState( renderer, state );
  31026. restoreSceneState( scene, state );
  31027. }
  31028. var RendererUtils = /*#__PURE__*/Object.freeze({
  31029. __proto__: null,
  31030. resetRendererAndSceneState: resetRendererAndSceneState,
  31031. resetRendererState: resetRendererState,
  31032. resetSceneState: resetSceneState,
  31033. restoreRendererAndSceneState: restoreRendererAndSceneState,
  31034. restoreRendererState: restoreRendererState,
  31035. restoreSceneState: restoreSceneState,
  31036. saveRendererAndSceneState: saveRendererAndSceneState,
  31037. saveRendererState: saveRendererState,
  31038. saveSceneState: saveSceneState
  31039. });
  31040. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  31041. /**
  31042. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  31043. * with a binary `[0,1]` result.
  31044. *
  31045. * @method
  31046. * @param {Object} inputs - The input parameter object.
  31047. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31048. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31049. * @return {Node<float>} The filtering result.
  31050. */
  31051. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  31052. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  31053. if ( depthTexture.isArrayTexture ) {
  31054. basic = basic.depth( depthLayer );
  31055. }
  31056. return basic.compare( shadowCoord.z );
  31057. } );
  31058. /**
  31059. * A shadow filtering function performing PCF filtering with Vogel disk sampling and IGN.
  31060. *
  31061. * Uses 5 samples distributed via Vogel disk pattern, rotated per-pixel using Interleaved
  31062. * Gradient Noise (IGN) to break up banding artifacts. Combined with hardware PCF (4-tap
  31063. * filtering per sample), this effectively provides 20 filtered taps with better distribution.
  31064. *
  31065. * @method
  31066. * @param {Object} inputs - The input parameter object.
  31067. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31068. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31069. * @param {LightShadow} inputs.shadow - The light shadow.
  31070. * @return {Node<float>} The filtering result.
  31071. */
  31072. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  31073. const depthCompare = ( uv, compare ) => {
  31074. let depth = texture( depthTexture, uv );
  31075. if ( depthTexture.isArrayTexture ) {
  31076. depth = depth.depth( depthLayer );
  31077. }
  31078. return depth.compare( compare );
  31079. };
  31080. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31081. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31082. const texelSize = vec2( 1 ).div( mapSize );
  31083. const radiusScaled = radius.mul( texelSize.x );
  31084. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  31085. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  31086. // 5 samples using Vogel disk distribution
  31087. return add(
  31088. depthCompare( shadowCoord.xy.add( vogelDiskSample( 0, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31089. depthCompare( shadowCoord.xy.add( vogelDiskSample( 1, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31090. depthCompare( shadowCoord.xy.add( vogelDiskSample( 2, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31091. depthCompare( shadowCoord.xy.add( vogelDiskSample( 3, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  31092. depthCompare( shadowCoord.xy.add( vogelDiskSample( 4, 5, phi ).mul( radiusScaled ) ), shadowCoord.z )
  31093. ).mul( 1 / 5 );
  31094. } );
  31095. /**
  31096. * A shadow filtering function performing PCF soft filtering.
  31097. *
  31098. * @method
  31099. * @param {Object} inputs - The input parameter object.
  31100. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31101. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31102. * @param {LightShadow} inputs.shadow - The light shadow.
  31103. * @return {Node<float>} The filtering result.
  31104. */
  31105. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  31106. const depthCompare = ( uv, compare ) => {
  31107. let depth = texture( depthTexture, uv );
  31108. if ( depthTexture.isArrayTexture ) {
  31109. depth = depth.depth( depthLayer );
  31110. }
  31111. return depth.compare( compare );
  31112. };
  31113. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31114. const texelSize = vec2( 1 ).div( mapSize );
  31115. const dx = texelSize.x;
  31116. const dy = texelSize.y;
  31117. const uv = shadowCoord.xy;
  31118. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  31119. uv.subAssign( f.mul( texelSize ) );
  31120. return add(
  31121. depthCompare( uv, shadowCoord.z ),
  31122. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  31123. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  31124. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  31125. mix(
  31126. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  31127. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  31128. f.x
  31129. ),
  31130. mix(
  31131. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  31132. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  31133. f.x
  31134. ),
  31135. mix(
  31136. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  31137. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  31138. f.y
  31139. ),
  31140. mix(
  31141. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  31142. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  31143. f.y
  31144. ),
  31145. mix(
  31146. mix(
  31147. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  31148. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  31149. f.x
  31150. ),
  31151. mix(
  31152. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  31153. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  31154. f.x
  31155. ),
  31156. f.y
  31157. )
  31158. ).mul( 1 / 9 );
  31159. } );
  31160. /**
  31161. * A shadow filtering function performing VSM filtering.
  31162. *
  31163. * @method
  31164. * @param {Object} inputs - The input parameter object.
  31165. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31166. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31167. * @return {Node<float>} The filtering result.
  31168. */
  31169. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer }, builder ) => {
  31170. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  31171. if ( depthTexture.isArrayTexture ) {
  31172. distribution = distribution.depth( depthLayer );
  31173. }
  31174. distribution = distribution.rg;
  31175. const mean = distribution.x;
  31176. const variance = max$1( 0.0000001, distribution.y.mul( distribution.y ) );
  31177. const hardShadow = ( builder.renderer.reversedDepthBuffer ) ? step( mean, shadowCoord.z ) : step( shadowCoord.z, mean );
  31178. const output = float( 1 ).toVar(); // default, fully lit
  31179. If( hardShadow.notEqual( 1.0 ), () => {
  31180. // Distance from mean
  31181. const d = shadowCoord.z.sub( mean );
  31182. // Chebyshev's inequality for upper bound on probability
  31183. let p_max = variance.div( variance.add( d.mul( d ) ) );
  31184. // Reduce light bleeding by remapping [amount, 1] to [0, 1]
  31185. p_max = clamp( sub( p_max, 0.3 ).div( 0.65 ) );
  31186. output.assign( max$1( hardShadow, p_max ) );
  31187. } );
  31188. return output;
  31189. } );
  31190. /**
  31191. * Retrieves or creates a shadow material for the given light source.
  31192. *
  31193. * This function checks if a shadow material already exists for the provided light.
  31194. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  31195. * in the `shadowMaterialLib` for future use.
  31196. *
  31197. * @tsl
  31198. * @function
  31199. * @param {Light} light - The light source for which the shadow material is needed.
  31200. * If the light is a point light, a depth node is calculated
  31201. * using the linear shadow distance.
  31202. * @returns {NodeMaterial} The shadow material associated with the given light.
  31203. */
  31204. const getShadowMaterial = ( light ) => {
  31205. let material = shadowMaterialLib.get( light );
  31206. if ( material === undefined ) {
  31207. material = new NodeMaterial();
  31208. material.colorNode = vec4( 0, 0, 0, 1 );
  31209. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  31210. material.name = 'ShadowMaterial';
  31211. material.blending = NoBlending;
  31212. material.fog = false;
  31213. shadowMaterialLib.set( light, material );
  31214. }
  31215. return material;
  31216. };
  31217. /**
  31218. * Disposes the shadow material for the given light source.
  31219. *
  31220. * @param {Light} light - The light source.
  31221. */
  31222. const disposeShadowMaterial = ( light ) => {
  31223. const material = shadowMaterialLib.get( light );
  31224. if ( material !== undefined ) {
  31225. material.dispose();
  31226. shadowMaterialLib.delete( light );
  31227. }
  31228. };
  31229. //
  31230. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  31231. const _shadowRenderObjectKeys = [];
  31232. /**
  31233. * Creates a function to render shadow objects in a scene.
  31234. *
  31235. * @tsl
  31236. * @function
  31237. * @param {Renderer} renderer - The renderer.
  31238. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  31239. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  31240. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  31241. * @return {shadowRenderObjectFunction} A function that renders shadow objects.
  31242. */
  31243. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  31244. _shadowRenderObjectKeys[ 0 ] = renderer;
  31245. _shadowRenderObjectKeys[ 1 ] = shadow;
  31246. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  31247. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  31248. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  31249. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  31250. if ( useVelocity ) {
  31251. getDataFromObject( object ).useVelocity = true;
  31252. }
  31253. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31254. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  31255. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31256. }
  31257. };
  31258. renderObjectFunction.shadowType = shadowType;
  31259. renderObjectFunction.useVelocity = useVelocity;
  31260. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  31261. }
  31262. _shadowRenderObjectKeys[ 0 ] = null;
  31263. _shadowRenderObjectKeys[ 1 ] = null;
  31264. return renderObjectFunction;
  31265. };
  31266. /**
  31267. * Represents the shader code for the first VSM render pass.
  31268. *
  31269. * @private
  31270. * @method
  31271. * @param {Object} inputs - The input parameter object.
  31272. * @param {Node<float>} inputs.samples - The number of samples
  31273. * @param {Node<float>} inputs.radius - The radius.
  31274. * @param {Node<float>} inputs.size - The size.
  31275. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  31276. * @return {Node<vec2>} The VSM output.
  31277. */
  31278. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31279. const mean = float( 0 ).toVar( 'meanVertical' );
  31280. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  31281. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31282. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31283. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31284. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31285. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  31286. if ( shadowPass.value.isArrayTexture ) {
  31287. depth = depth.depth( depthLayer );
  31288. }
  31289. depth = depth.x;
  31290. mean.addAssign( depth );
  31291. squaredMean.addAssign( depth.mul( depth ) );
  31292. } );
  31293. mean.divAssign( samples );
  31294. squaredMean.divAssign( samples );
  31295. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31296. return vec2( mean, std_dev );
  31297. } );
  31298. /**
  31299. * Represents the shader code for the second VSM render pass.
  31300. *
  31301. * @private
  31302. * @method
  31303. * @param {Object} inputs - The input parameter object.
  31304. * @param {Node<float>} inputs.samples - The number of samples
  31305. * @param {Node<float>} inputs.radius - The radius.
  31306. * @param {Node<float>} inputs.size - The size.
  31307. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  31308. * @return {Node<vec2>} The VSM output.
  31309. */
  31310. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31311. const mean = float( 0 ).toVar( 'meanHorizontal' );
  31312. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  31313. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31314. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31315. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31316. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31317. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  31318. if ( shadowPass.value.isArrayTexture ) {
  31319. distribution = distribution.depth( depthLayer );
  31320. }
  31321. mean.addAssign( distribution.x );
  31322. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  31323. } );
  31324. mean.divAssign( samples );
  31325. squaredMean.divAssign( samples );
  31326. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31327. return vec2( mean, std_dev );
  31328. } );
  31329. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  31330. //
  31331. let _rendererState;
  31332. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  31333. /**
  31334. * Represents the default shadow implementation for lighting nodes.
  31335. *
  31336. * @augments ShadowBaseNode
  31337. */
  31338. class ShadowNode extends ShadowBaseNode {
  31339. static get type() {
  31340. return 'ShadowNode';
  31341. }
  31342. /**
  31343. * Constructs a new shadow node.
  31344. *
  31345. * @param {Light} light - The shadow casting light.
  31346. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  31347. */
  31348. constructor( light, shadow = null ) {
  31349. super( light );
  31350. /**
  31351. * The light shadow which defines the properties light's
  31352. * shadow.
  31353. *
  31354. * @type {?LightShadow}
  31355. * @default null
  31356. */
  31357. this.shadow = shadow || light.shadow;
  31358. /**
  31359. * A reference to the shadow map which is a render target.
  31360. *
  31361. * @type {?RenderTarget}
  31362. * @default null
  31363. */
  31364. this.shadowMap = null;
  31365. /**
  31366. * Only relevant for VSM shadows. Render target for the
  31367. * first VSM render pass.
  31368. *
  31369. * @type {?RenderTarget}
  31370. * @default null
  31371. */
  31372. this.vsmShadowMapVertical = null;
  31373. /**
  31374. * Only relevant for VSM shadows. Render target for the
  31375. * second VSM render pass.
  31376. *
  31377. * @type {?RenderTarget}
  31378. * @default null
  31379. */
  31380. this.vsmShadowMapHorizontal = null;
  31381. /**
  31382. * Only relevant for VSM shadows. Node material which
  31383. * is used to render the first VSM pass.
  31384. *
  31385. * @type {?NodeMaterial}
  31386. * @default null
  31387. */
  31388. this.vsmMaterialVertical = null;
  31389. /**
  31390. * Only relevant for VSM shadows. Node material which
  31391. * is used to render the second VSM pass.
  31392. *
  31393. * @type {?NodeMaterial}
  31394. * @default null
  31395. */
  31396. this.vsmMaterialHorizontal = null;
  31397. /**
  31398. * A reference to the output node which defines the
  31399. * final result of this shadow node.
  31400. *
  31401. * @type {?Node}
  31402. * @private
  31403. * @default null
  31404. */
  31405. this._node = null;
  31406. /**
  31407. * The current shadow map type of this shadow node.
  31408. *
  31409. * @type {?number}
  31410. * @private
  31411. * @default null
  31412. */
  31413. this._currentShadowType = null;
  31414. /**
  31415. * A Weak Map holding the current frame ID per camera. Used
  31416. * to control the update of shadow maps.
  31417. *
  31418. * @type {WeakMap<Camera,number>}
  31419. * @private
  31420. */
  31421. this._cameraFrameId = new WeakMap();
  31422. /**
  31423. * This flag can be used for type testing.
  31424. *
  31425. * @type {boolean}
  31426. * @readonly
  31427. * @default true
  31428. */
  31429. this.isShadowNode = true;
  31430. /**
  31431. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  31432. *
  31433. * @type {number}
  31434. * @readonly
  31435. * @default true
  31436. */
  31437. this.depthLayer = 0;
  31438. }
  31439. /**
  31440. * Setups the shadow filtering.
  31441. *
  31442. * @param {NodeBuilder} builder - A reference to the current node builder.
  31443. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31444. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31445. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31446. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31447. * @param {LightShadow} inputs.shadow - The light shadow.
  31448. * @return {Node<float>} The result node of the shadow filtering.
  31449. */
  31450. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  31451. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  31452. .and( shadowCoord.x.lessThanEqual( 1 ) )
  31453. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  31454. .and( shadowCoord.y.lessThanEqual( 1 ) )
  31455. .and( shadowCoord.z.lessThanEqual( 1 ) );
  31456. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  31457. return frustumTest.select( shadowNode, float( 1 ) );
  31458. }
  31459. /**
  31460. * Setups the shadow coordinates.
  31461. *
  31462. * @param {NodeBuilder} builder - A reference to the current node builder.
  31463. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31464. * @return {Node<vec3>} The shadow coordinates.
  31465. */
  31466. setupShadowCoord( builder, shadowPosition ) {
  31467. const { shadow } = this;
  31468. const { renderer } = builder;
  31469. const bias = shadow.biasNode || reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31470. let shadowCoord = shadowPosition;
  31471. let coordZ;
  31472. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  31473. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  31474. coordZ = shadowCoord.z;
  31475. } else {
  31476. const w = shadowCoord.w;
  31477. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  31478. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  31479. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  31480. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  31481. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  31482. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  31483. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  31484. }
  31485. shadowCoord = vec3(
  31486. shadowCoord.x,
  31487. shadowCoord.y.oneMinus(), // follow webgpu standards
  31488. renderer.reversedDepthBuffer ? coordZ.sub( bias ) : coordZ.add( bias )
  31489. );
  31490. return shadowCoord;
  31491. }
  31492. /**
  31493. * Returns the shadow filtering function for the given shadow type.
  31494. *
  31495. * @param {number} type - The shadow type.
  31496. * @return {Function} The filtering function.
  31497. */
  31498. getShadowFilterFn( type ) {
  31499. return _shadowFilterLib[ type ];
  31500. }
  31501. setupRenderTarget( shadow, builder ) {
  31502. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  31503. depthTexture.name = 'ShadowDepthTexture';
  31504. depthTexture.compareFunction = builder.renderer.reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  31505. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  31506. shadowMap.texture.name = 'ShadowMap';
  31507. shadowMap.texture.type = shadow.mapType;
  31508. shadowMap.depthTexture = depthTexture;
  31509. return { shadowMap, depthTexture };
  31510. }
  31511. /**
  31512. * Setups the shadow output node.
  31513. *
  31514. * @param {NodeBuilder} builder - A reference to the current node builder.
  31515. * @return {Node<vec3>} The shadow output node.
  31516. */
  31517. setupShadow( builder ) {
  31518. const { renderer, camera } = builder;
  31519. const { light, shadow } = this;
  31520. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  31521. const shadowMapType = renderer.shadowMap.type;
  31522. const hasTextureCompare = renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE );
  31523. if ( ( shadowMapType === PCFShadowMap || shadowMapType === PCFSoftShadowMap ) && hasTextureCompare ) {
  31524. depthTexture.minFilter = LinearFilter;
  31525. depthTexture.magFilter = LinearFilter;
  31526. } else {
  31527. depthTexture.minFilter = NearestFilter;
  31528. depthTexture.magFilter = NearestFilter;
  31529. }
  31530. shadow.camera.coordinateSystem = camera.coordinateSystem;
  31531. shadow.camera.updateProjectionMatrix();
  31532. // VSM
  31533. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31534. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  31535. if ( shadowMap.depth > 1 ) {
  31536. if ( ! shadowMap._vsmShadowMapVertical ) {
  31537. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31538. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  31539. }
  31540. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  31541. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  31542. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31543. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  31544. }
  31545. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  31546. } else {
  31547. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31548. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31549. }
  31550. let shadowPassVertical = texture( depthTexture );
  31551. if ( depthTexture.isArrayTexture ) {
  31552. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  31553. }
  31554. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  31555. if ( depthTexture.isArrayTexture ) {
  31556. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  31557. }
  31558. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  31559. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31560. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31561. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  31562. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31563. material.name = 'VSMVertical';
  31564. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  31565. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31566. material.name = 'VSMHorizontal';
  31567. }
  31568. //
  31569. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  31570. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  31571. const shadowMatrix = lightShadowMatrix( light );
  31572. const shadowNormalBias = normalWorld.mul( normalBias );
  31573. let shadowPosition;
  31574. if ( ! renderer.highPrecision || builder.material.receivedShadowPositionNode || builder.context.shadowPositionWorld ) {
  31575. shadowPosition = shadowMatrix.mul( shadowPositionWorld.add( shadowNormalBias ) );
  31576. } else {
  31577. const highpShadowModelMatrix = uniform( 'mat4' ).onObjectUpdate( ( { object }, self ) => {
  31578. return self.value.multiplyMatrices( shadowMatrix.value, object.matrixWorld );
  31579. } );
  31580. shadowPosition = highpShadowModelMatrix.mul( positionLocal ).add( shadowMatrix.mul( vec4( shadowNormalBias, 0 ) ) );
  31581. }
  31582. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  31583. //
  31584. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  31585. if ( filterFn === null ) {
  31586. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  31587. }
  31588. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  31589. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  31590. let shadowColor;
  31591. if ( renderer.shadowMap.transmitted === true ) {
  31592. if ( shadowMap.texture.isCubeTexture ) {
  31593. // For cube shadow maps (point lights), use cubeTexture with vec3 coordinates
  31594. shadowColor = cubeTexture( shadowMap.texture, shadowCoord.xyz );
  31595. } else {
  31596. shadowColor = texture( shadowMap.texture, shadowCoord );
  31597. if ( depthTexture.isArrayTexture ) {
  31598. shadowColor = shadowColor.depth( this.depthLayer );
  31599. }
  31600. }
  31601. }
  31602. //
  31603. let shadowOutput;
  31604. if ( shadowColor ) {
  31605. shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  31606. } else {
  31607. shadowOutput = mix( 1, shadowNode, shadowIntensity ).toVar();
  31608. }
  31609. this.shadowMap = shadowMap;
  31610. this.shadow.map = shadowMap;
  31611. // Shadow Output + Inspector
  31612. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  31613. if ( shadowColor ) {
  31614. shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  31615. if ( this.shadowMap.texture.isCubeTexture ) {
  31616. return cubeTexture( this.shadowMap.texture );
  31617. }
  31618. return texture( this.shadowMap.texture );
  31619. } );
  31620. }
  31621. return shadowOutput.toInspector( `${ inspectName } / Depth`, () => {
  31622. // TODO: Use linear depth
  31623. if ( this.shadowMap.texture.isCubeTexture ) {
  31624. return cubeTexture( this.shadowMap.texture ).r.oneMinus();
  31625. }
  31626. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).r.oneMinus();
  31627. } );
  31628. }
  31629. /**
  31630. * The implementation performs the setup of the output node. An output is only
  31631. * produces if shadow mapping is globally enabled in the renderer.
  31632. *
  31633. * @param {NodeBuilder} builder - A reference to the current node builder.
  31634. * @return {ShaderCallNodeInternal} The output node.
  31635. */
  31636. setup( builder ) {
  31637. if ( builder.renderer.shadowMap.enabled === false ) return;
  31638. return Fn( () => {
  31639. const currentShadowType = builder.renderer.shadowMap.type;
  31640. if ( this._currentShadowType !== currentShadowType ) {
  31641. this._reset();
  31642. this._node = null;
  31643. }
  31644. let node = this._node;
  31645. this.setupShadowPosition( builder );
  31646. if ( node === null ) {
  31647. this._node = node = this.setupShadow( builder );
  31648. this._currentShadowType = currentShadowType;
  31649. }
  31650. if ( builder.material.receivedShadowNode ) {
  31651. node = builder.material.receivedShadowNode( node );
  31652. }
  31653. return node;
  31654. } )();
  31655. }
  31656. /**
  31657. * Renders the shadow. The logic of this function could be included
  31658. * into {@link ShadowNode#updateShadow} however more specialized shadow
  31659. * nodes might require a custom shadow map rendering. By having a
  31660. * dedicated method, it's easier to overwrite the default behavior.
  31661. *
  31662. * @param {NodeFrame} frame - A reference to the current node frame.
  31663. */
  31664. renderShadow( frame ) {
  31665. const { shadow, shadowMap, light } = this;
  31666. const { renderer, scene } = frame;
  31667. shadow.updateMatrices( light );
  31668. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  31669. const currentSceneName = scene.name;
  31670. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  31671. renderer.render( scene, shadow.camera );
  31672. scene.name = currentSceneName;
  31673. }
  31674. /**
  31675. * Updates the shadow.
  31676. *
  31677. * @param {NodeFrame} frame - A reference to the current node frame.
  31678. */
  31679. updateShadow( frame ) {
  31680. const { shadowMap, light, shadow } = this;
  31681. const { renderer, scene, camera } = frame;
  31682. const shadowType = renderer.shadowMap.type;
  31683. const depthVersion = shadowMap.depthTexture.version;
  31684. this._depthVersionCached = depthVersion;
  31685. const _shadowCameraLayer = shadow.camera.layers.mask;
  31686. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  31687. shadow.camera.layers.mask = camera.layers.mask;
  31688. }
  31689. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  31690. const currentMRT = renderer.getMRT();
  31691. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  31692. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  31693. scene.overrideMaterial = getShadowMaterial( light );
  31694. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  31695. renderer.setClearColor( 0x000000, 0 );
  31696. renderer.setRenderTarget( shadowMap );
  31697. this.renderShadow( frame );
  31698. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  31699. // vsm blur pass
  31700. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31701. this.vsmPass( renderer );
  31702. }
  31703. shadow.camera.layers.mask = _shadowCameraLayer;
  31704. restoreRendererAndSceneState( renderer, scene, _rendererState );
  31705. }
  31706. /**
  31707. * For VSM additional render passes are required.
  31708. *
  31709. * @param {Renderer} renderer - A reference to the current renderer.
  31710. */
  31711. vsmPass( renderer ) {
  31712. const { shadow } = this;
  31713. const depth = this.shadowMap.depth;
  31714. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31715. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31716. renderer.setRenderTarget( this.vsmShadowMapVertical );
  31717. _quadMesh.material = this.vsmMaterialVertical;
  31718. _quadMesh.render( renderer );
  31719. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  31720. _quadMesh.material = this.vsmMaterialHorizontal;
  31721. _quadMesh.render( renderer );
  31722. }
  31723. /**
  31724. * Frees the internal resources of this shadow node.
  31725. */
  31726. dispose() {
  31727. this._reset();
  31728. super.dispose();
  31729. }
  31730. /**
  31731. * Resets the resouce state of this shadow node.
  31732. *
  31733. * @private
  31734. */
  31735. _reset() {
  31736. this._currentShadowType = null;
  31737. disposeShadowMaterial( this.light );
  31738. if ( this.shadowMap ) {
  31739. this.shadowMap.dispose();
  31740. this.shadowMap = null;
  31741. }
  31742. if ( this.vsmShadowMapVertical !== null ) {
  31743. this.vsmShadowMapVertical.dispose();
  31744. this.vsmShadowMapVertical = null;
  31745. this.vsmMaterialVertical.dispose();
  31746. this.vsmMaterialVertical = null;
  31747. }
  31748. if ( this.vsmShadowMapHorizontal !== null ) {
  31749. this.vsmShadowMapHorizontal.dispose();
  31750. this.vsmShadowMapHorizontal = null;
  31751. this.vsmMaterialHorizontal.dispose();
  31752. this.vsmMaterialHorizontal = null;
  31753. }
  31754. }
  31755. /**
  31756. * The implementation performs the update of the shadow map if necessary.
  31757. *
  31758. * @param {NodeFrame} frame - A reference to the current node frame.
  31759. */
  31760. updateBefore( frame ) {
  31761. const { shadow } = this;
  31762. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  31763. if ( needsUpdate ) {
  31764. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  31765. needsUpdate = false;
  31766. }
  31767. this._cameraFrameId[ frame.camera ] = frame.frameId;
  31768. }
  31769. if ( needsUpdate ) {
  31770. this.updateShadow( frame );
  31771. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  31772. shadow.needsUpdate = false;
  31773. }
  31774. }
  31775. }
  31776. }
  31777. /**
  31778. * Shadow Render Object Function.
  31779. *
  31780. * @function shadowRenderObjectFunction
  31781. * @param {Object3D} object - The 3D object to render.
  31782. * @param {Scene} scene - The scene containing the object.
  31783. * @param {Camera} _camera - The camera used for rendering.
  31784. * @param {BufferGeometry} geometry - The geometry of the object.
  31785. * @param {Material} material - The material of the object.
  31786. * @param {Group} group - The group the object belongs to.
  31787. * @param {...any} params - Additional parameters for rendering.
  31788. */
  31789. /**
  31790. * TSL function for creating an instance of `ShadowNode`.
  31791. *
  31792. * @tsl
  31793. * @function
  31794. * @param {Light} light - The shadow casting light.
  31795. * @param {?LightShadow} [shadow] - The light shadow.
  31796. * @return {ShadowNode} The created shadow node.
  31797. */
  31798. const shadow = ( light, shadow ) => new ShadowNode( light, shadow );
  31799. const _clearColor$1 = /*@__PURE__*/ new Color();
  31800. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  31801. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  31802. const _lookTarget = /*@__PURE__*/ new Vector3();
  31803. // Cube map face directions and up vectors for point light shadows
  31804. // Face order: +X, -X, +Y, -Y, +Z, -Z
  31805. // WebGPU coordinate system - Y faces swapped to match texture sampling convention
  31806. const _cubeDirectionsWebGPU = [
  31807. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ),
  31808. /*@__PURE__*/ new Vector3( 0, 1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  31809. ];
  31810. const _cubeUpsWebGPU = [
  31811. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, -1 ),
  31812. /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  31813. ];
  31814. // WebGL coordinate system - standard OpenGL convention
  31815. const _cubeDirectionsWebGL = [
  31816. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  31817. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  31818. ];
  31819. const _cubeUpsWebGL = [
  31820. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  31821. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  31822. ];
  31823. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp } ) => {
  31824. return cubeTexture( depthTexture, bd3D ).compare( dp );
  31825. } );
  31826. /**
  31827. * A shadow filtering function for point lights using Vogel disk sampling and IGN.
  31828. *
  31829. * Uses 5 samples distributed via Vogel disk pattern in tangent space around the
  31830. * sample direction, rotated per-pixel using Interleaved Gradient Noise (IGN).
  31831. *
  31832. * @method
  31833. * @param {Object} inputs - The input parameter object.
  31834. * @param {CubeDepthTexture} inputs.depthTexture - A reference to the shadow cube map.
  31835. * @param {Node<vec3>} inputs.bd3D - The normalized direction from light to fragment.
  31836. * @param {Node<float>} inputs.dp - The depth value to compare against.
  31837. * @param {LightShadow} inputs.shadow - The light shadow.
  31838. * @return {Node<float>} The filtering result.
  31839. */
  31840. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, shadow } ) => {
  31841. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31842. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31843. const texelSize = radius.div( mapSize.x );
  31844. // Build a tangent-space coordinate system for applying offsets
  31845. const absDir = abs( bd3D );
  31846. const tangent = normalize( cross( bd3D, absDir.x.greaterThan( absDir.z ).select( vec3( 0, 1, 0 ), vec3( 1, 0, 0 ) ) ) );
  31847. const bitangent = cross( bd3D, tangent );
  31848. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  31849. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  31850. // 5 samples using Vogel disk distribution in tangent space
  31851. const sample0 = vogelDiskSample( 0, 5, phi );
  31852. const sample1 = vogelDiskSample( 1, 5, phi );
  31853. const sample2 = vogelDiskSample( 2, 5, phi );
  31854. const sample3 = vogelDiskSample( 3, 5, phi );
  31855. const sample4 = vogelDiskSample( 4, 5, phi );
  31856. return cubeTexture( depthTexture, bd3D.add( tangent.mul( sample0.x ).add( bitangent.mul( sample0.y ) ).mul( texelSize ) ) ).compare( dp )
  31857. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample1.x ).add( bitangent.mul( sample1.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31858. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample2.x ).add( bitangent.mul( sample2.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31859. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample3.x ).add( bitangent.mul( sample3.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31860. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample4.x ).add( bitangent.mul( sample4.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31861. .mul( 1.0 / 5.0 );
  31862. } );
  31863. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow }, builder ) => {
  31864. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  31865. // the vector from the light to the world-space position of the fragment.
  31866. const shadowPosition = shadowCoord.xyz.toConst();
  31867. const shadowPositionAbs = shadowPosition.abs().toConst();
  31868. const viewZ = shadowPositionAbs.x.max( shadowPositionAbs.y ).max( shadowPositionAbs.z );
  31869. const shadowCameraNear = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  31870. const shadowCameraFar = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  31871. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31872. const result = float( 1.0 ).toVar();
  31873. If( viewZ.sub( shadowCameraFar ).lessThanEqual( 0.0 ).and( viewZ.sub( shadowCameraNear ).greaterThanEqual( 0.0 ) ), () => {
  31874. let dp;
  31875. if ( builder.renderer.reversedDepthBuffer ) {
  31876. dp = viewZToReversedPerspectiveDepth( viewZ.negate(), shadowCameraNear, shadowCameraFar );
  31877. dp.subAssign( bias );
  31878. } else {
  31879. dp = viewZToPerspectiveDepth( viewZ.negate(), shadowCameraNear, shadowCameraFar );
  31880. dp.addAssign( bias );
  31881. }
  31882. // bd3D = base direction 3D (direction from light to fragment)
  31883. const bd3D = shadowPosition.normalize();
  31884. // percentage-closer filtering using cube texture sampling
  31885. result.assign( filterFn( { depthTexture, bd3D, dp, shadow } ) );
  31886. } );
  31887. return result;
  31888. } );
  31889. /**
  31890. * Represents the shadow implementation for point light nodes.
  31891. *
  31892. * @augments ShadowNode
  31893. */
  31894. class PointShadowNode extends ShadowNode {
  31895. static get type() {
  31896. return 'PointShadowNode';
  31897. }
  31898. /**
  31899. * Constructs a new point shadow node.
  31900. *
  31901. * @param {PointLight} light - The shadow casting point light.
  31902. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31903. */
  31904. constructor( light, shadow = null ) {
  31905. super( light, shadow );
  31906. }
  31907. /**
  31908. * Overwrites the default implementation to return point light shadow specific
  31909. * filtering functions.
  31910. *
  31911. * @param {number} type - The shadow type.
  31912. * @return {Function} The filtering function.
  31913. */
  31914. getShadowFilterFn( type ) {
  31915. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  31916. }
  31917. /**
  31918. * Overwrites the default implementation so the unaltered shadow position is used.
  31919. *
  31920. * @param {NodeBuilder} builder - A reference to the current node builder.
  31921. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31922. * @return {Node<vec3>} The shadow coordinates.
  31923. */
  31924. setupShadowCoord( builder, shadowPosition ) {
  31925. return shadowPosition;
  31926. }
  31927. /**
  31928. * Overwrites the default implementation to only use point light specific
  31929. * shadow filter functions.
  31930. *
  31931. * @param {NodeBuilder} builder - A reference to the current node builder.
  31932. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31933. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31934. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's depth texture.
  31935. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31936. * @param {LightShadow} inputs.shadow - The light shadow.
  31937. * @return {Node<float>} The result node of the shadow filtering.
  31938. */
  31939. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  31940. return pointShadowFilter( { filterFn, depthTexture, shadowCoord, shadow } );
  31941. }
  31942. /**
  31943. * Overwrites the default implementation to create a CubeRenderTarget with CubeDepthTexture.
  31944. *
  31945. * @param {LightShadow} shadow - The light shadow object.
  31946. * @param {NodeBuilder} builder - A reference to the current node builder.
  31947. * @return {Object} An object containing the shadow map and depth texture.
  31948. */
  31949. setupRenderTarget( shadow, builder ) {
  31950. const depthTexture = new CubeDepthTexture( shadow.mapSize.width );
  31951. depthTexture.name = 'PointShadowDepthTexture';
  31952. depthTexture.compareFunction = builder.renderer.reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  31953. const shadowMap = builder.createCubeRenderTarget( shadow.mapSize.width );
  31954. shadowMap.texture.name = 'PointShadowMap';
  31955. shadowMap.depthTexture = depthTexture;
  31956. return { shadowMap, depthTexture };
  31957. }
  31958. /**
  31959. * Overwrites the default implementation with point light specific
  31960. * rendering code.
  31961. *
  31962. * @param {NodeFrame} frame - A reference to the current node frame.
  31963. */
  31964. renderShadow( frame ) {
  31965. const { shadow, shadowMap, light } = this;
  31966. const { renderer, scene } = frame;
  31967. const camera = shadow.camera;
  31968. const shadowMatrix = shadow.matrix;
  31969. // Select cube directions/ups based on coordinate system
  31970. const isWebGPU = renderer.coordinateSystem === WebGPUCoordinateSystem;
  31971. const cubeDirections = isWebGPU ? _cubeDirectionsWebGPU : _cubeDirectionsWebGL;
  31972. const cubeUps = isWebGPU ? _cubeUpsWebGPU : _cubeUpsWebGL;
  31973. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.width );
  31974. //
  31975. const previousAutoClear = renderer.autoClear;
  31976. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  31977. const previousClearAlpha = renderer.getClearAlpha();
  31978. renderer.autoClear = false;
  31979. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  31980. // Render each cube face
  31981. for ( let face = 0; face < 6; face ++ ) {
  31982. // Set render target to the specific cube face
  31983. renderer.setRenderTarget( shadowMap, face );
  31984. renderer.clear();
  31985. // Update shadow camera matrices for this face
  31986. const far = light.distance || camera.far;
  31987. if ( far !== camera.far ) {
  31988. camera.far = far;
  31989. camera.updateProjectionMatrix();
  31990. }
  31991. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  31992. camera.position.copy( _lightPositionWorld );
  31993. _lookTarget.copy( camera.position );
  31994. _lookTarget.add( cubeDirections[ face ] );
  31995. camera.up.copy( cubeUps[ face ] );
  31996. camera.lookAt( _lookTarget );
  31997. camera.updateMatrixWorld();
  31998. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  31999. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  32000. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix$1, camera.coordinateSystem, camera.reversedDepth );
  32001. //
  32002. const currentSceneName = scene.name;
  32003. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ face + 1 }`;
  32004. renderer.render( scene, camera );
  32005. scene.name = currentSceneName;
  32006. }
  32007. //
  32008. renderer.autoClear = previousAutoClear;
  32009. renderer.setClearColor( previousClearColor, previousClearAlpha );
  32010. }
  32011. }
  32012. /**
  32013. * TSL function for creating an instance of `PointShadowNode`.
  32014. *
  32015. * @tsl
  32016. * @function
  32017. * @param {PointLight} light - The shadow casting point light.
  32018. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  32019. * @return {PointShadowNode} The created point shadow node.
  32020. */
  32021. const pointShadow = ( light, shadow ) => new PointShadowNode( light, shadow );
  32022. /**
  32023. * Base class for analytic light nodes.
  32024. *
  32025. * @augments LightingNode
  32026. */
  32027. class AnalyticLightNode extends LightingNode {
  32028. static get type() {
  32029. return 'AnalyticLightNode';
  32030. }
  32031. /**
  32032. * Constructs a new analytic light node.
  32033. *
  32034. * @param {?Light} [light=null] - The light source.
  32035. */
  32036. constructor( light = null ) {
  32037. super();
  32038. /**
  32039. * The light source.
  32040. *
  32041. * @type {?Light}
  32042. * @default null
  32043. */
  32044. this.light = light;
  32045. /**
  32046. * The light's color value.
  32047. *
  32048. * @type {Color}
  32049. */
  32050. this.color = new Color();
  32051. /**
  32052. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  32053. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  32054. *
  32055. * @type {Node}
  32056. */
  32057. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  32058. /**
  32059. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  32060. * The final color node is represented by a different node when using shadows.
  32061. *
  32062. * @type {?Node}
  32063. * @default null
  32064. */
  32065. this.baseColorNode = null;
  32066. /**
  32067. * Represents the light's shadow.
  32068. *
  32069. * @type {?ShadowNode}
  32070. * @default null
  32071. */
  32072. this.shadowNode = null;
  32073. /**
  32074. * Represents the light's shadow color.
  32075. *
  32076. * @type {?Node}
  32077. * @default null
  32078. */
  32079. this.shadowColorNode = null;
  32080. /**
  32081. * This flag can be used for type testing.
  32082. *
  32083. * @type {boolean}
  32084. * @readonly
  32085. * @default true
  32086. */
  32087. this.isAnalyticLightNode = true;
  32088. /**
  32089. * Overwritten since analytic light nodes are updated
  32090. * once per frame.
  32091. *
  32092. * @type {string}
  32093. * @default 'frame'
  32094. */
  32095. this.updateType = NodeUpdateType.FRAME;
  32096. if ( light && light.shadow ) {
  32097. this._shadowDisposeListener = () => {
  32098. this.disposeShadow();
  32099. };
  32100. light.addEventListener( 'dispose', this._shadowDisposeListener );
  32101. }
  32102. }
  32103. dispose() {
  32104. if ( this._shadowDisposeListener ) {
  32105. this.light.removeEventListener( 'dispose', this._shadowDisposeListener );
  32106. }
  32107. super.dispose();
  32108. }
  32109. /**
  32110. * Frees internal resources related to shadows.
  32111. */
  32112. disposeShadow() {
  32113. if ( this.shadowNode !== null ) {
  32114. this.shadowNode.dispose();
  32115. this.shadowNode = null;
  32116. }
  32117. this.shadowColorNode = null;
  32118. if ( this.baseColorNode !== null ) {
  32119. this.colorNode = this.baseColorNode;
  32120. this.baseColorNode = null;
  32121. }
  32122. }
  32123. getHash() {
  32124. return this.light.uuid;
  32125. }
  32126. /**
  32127. * Returns a node representing a direction vector which points from the current
  32128. * position in view space to the light's position in view space.
  32129. *
  32130. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32131. * @return {Node<vec3>} The light vector node.
  32132. */
  32133. getLightVector( builder ) {
  32134. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  32135. }
  32136. /**
  32137. * Sets up the direct lighting for the analytic light node.
  32138. *
  32139. * @abstract
  32140. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32141. * @return {Object|undefined} The direct light data (color and direction).
  32142. */
  32143. setupDirect( /*builder*/ ) { }
  32144. /**
  32145. * Sets up the direct rect area lighting for the analytic light node.
  32146. *
  32147. * @abstract
  32148. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32149. * @return {Object|undefined} The direct rect area light data.
  32150. */
  32151. setupDirectRectArea( /*builder*/ ) { }
  32152. /**
  32153. * Setups the shadow node for this light. The method exists so concrete light classes
  32154. * can setup different types of shadow nodes.
  32155. *
  32156. * @return {ShadowNode} The created shadow node.
  32157. */
  32158. setupShadowNode() {
  32159. return shadow( this.light );
  32160. }
  32161. /**
  32162. * Setups the shadow for this light. This method is only executed if the light
  32163. * cast shadows and the current build object receives shadows. It incorporates
  32164. * shadows into the lighting computation.
  32165. *
  32166. * @param {NodeBuilder} builder - The current node builder.
  32167. */
  32168. setupShadow( builder ) {
  32169. const { renderer } = builder;
  32170. if ( renderer.shadowMap.enabled === false ) return;
  32171. let shadowColorNode = this.shadowColorNode;
  32172. if ( shadowColorNode === null ) {
  32173. const customShadowNode = this.light.shadow.shadowNode;
  32174. let shadowNode;
  32175. if ( customShadowNode !== undefined ) {
  32176. shadowNode = nodeObject( customShadowNode );
  32177. } else {
  32178. shadowNode = this.setupShadowNode();
  32179. }
  32180. this.shadowNode = shadowNode;
  32181. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  32182. this.baseColorNode = this.colorNode;
  32183. }
  32184. //
  32185. if ( builder.context.getShadow ) {
  32186. shadowColorNode = builder.context.getShadow( this, builder );
  32187. }
  32188. this.colorNode = shadowColorNode;
  32189. }
  32190. /**
  32191. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  32192. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  32193. * invocate the respective interface methods.
  32194. *
  32195. * @param {NodeBuilder} builder - The current node builder.
  32196. */
  32197. setup( builder ) {
  32198. this.colorNode = this.baseColorNode || this.colorNode;
  32199. if ( this.light.castShadow ) {
  32200. if ( builder.object.receiveShadow ) {
  32201. this.setupShadow( builder );
  32202. }
  32203. } else if ( this.shadowNode !== null ) {
  32204. this.shadowNode.dispose();
  32205. this.shadowNode = null;
  32206. this.shadowColorNode = null;
  32207. }
  32208. const directLightData = this.setupDirect( builder );
  32209. const directRectAreaLightData = this.setupDirectRectArea( builder );
  32210. if ( directLightData ) {
  32211. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  32212. }
  32213. if ( directRectAreaLightData ) {
  32214. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  32215. }
  32216. }
  32217. /**
  32218. * The update method is used to update light uniforms per frame.
  32219. * Potentially overwritten in concrete light nodes to update light
  32220. * specific uniforms.
  32221. *
  32222. * @param {NodeFrame} frame - A reference to the current node frame.
  32223. */
  32224. update( /*frame*/ ) {
  32225. const { light } = this;
  32226. this.color.copy( light.color ).multiplyScalar( light.intensity );
  32227. }
  32228. }
  32229. /**
  32230. * Represents a `discard` shader operation in TSL.
  32231. *
  32232. * @method
  32233. * @param {Object} inputs - The input parameter object.
  32234. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  32235. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  32236. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  32237. * @return {Node<float>} The distance falloff.
  32238. */
  32239. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  32240. // based upon Frostbite 3 Moving to Physically-based Rendering
  32241. // page 32, equation 26: E[window1]
  32242. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32243. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  32244. return cutoffDistance.greaterThan( 0 ).select(
  32245. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  32246. distanceFalloff
  32247. );
  32248. } ); // validated
  32249. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  32250. const lightDirection = lightVector.normalize();
  32251. const lightDistance = lightVector.length();
  32252. const attenuation = getDistanceAttenuation( {
  32253. lightDistance,
  32254. cutoffDistance,
  32255. decayExponent
  32256. } );
  32257. const lightColor = color.mul( attenuation );
  32258. return { lightDirection, lightColor };
  32259. };
  32260. /**
  32261. * Module for representing point lights as nodes.
  32262. *
  32263. * @augments AnalyticLightNode
  32264. */
  32265. class PointLightNode extends AnalyticLightNode {
  32266. static get type() {
  32267. return 'PointLightNode';
  32268. }
  32269. /**
  32270. * Constructs a new point light node.
  32271. *
  32272. * @param {?PointLight} [light=null] - The point light source.
  32273. */
  32274. constructor( light = null ) {
  32275. super( light );
  32276. /**
  32277. * Uniform node representing the cutoff distance.
  32278. *
  32279. * @type {UniformNode<float>}
  32280. */
  32281. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  32282. /**
  32283. * Uniform node representing the decay exponent.
  32284. *
  32285. * @type {UniformNode<float>}
  32286. */
  32287. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  32288. }
  32289. /**
  32290. * Overwritten to updated point light specific uniforms.
  32291. *
  32292. * @param {NodeFrame} frame - A reference to the current node frame.
  32293. */
  32294. update( frame ) {
  32295. const { light } = this;
  32296. super.update( frame );
  32297. this.cutoffDistanceNode.value = light.distance;
  32298. this.decayExponentNode.value = light.decay;
  32299. }
  32300. /**
  32301. * Overwritten to setup point light specific shadow.
  32302. *
  32303. * @return {PointShadowNode}
  32304. */
  32305. setupShadowNode() {
  32306. return pointShadow( this.light );
  32307. }
  32308. setupDirect( builder ) {
  32309. return directPointLight( {
  32310. color: this.colorNode,
  32311. lightVector: this.getLightVector( builder ),
  32312. cutoffDistance: this.cutoffDistanceNode,
  32313. decayExponent: this.decayExponentNode
  32314. } );
  32315. }
  32316. }
  32317. /**
  32318. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  32319. *
  32320. * @tsl
  32321. * @function
  32322. * @param {Node<vec2>} coord - The uv coordinates.
  32323. * @return {Node<float>} The result data.
  32324. */
  32325. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  32326. const uv = coord.mul( 2.0 );
  32327. const cx = uv.x.floor();
  32328. const cy = uv.y.floor();
  32329. const result = cx.add( cy ).mod( 2.0 );
  32330. return result.sign();
  32331. } );
  32332. /**
  32333. * Generates a circle based on the uv coordinates.
  32334. *
  32335. * @tsl
  32336. * @function
  32337. * @param {Node<vec2>} coord - The uv to generate the circle.
  32338. * @return {Node<float>} The circle shape.
  32339. */
  32340. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  32341. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  32342. let alpha;
  32343. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  32344. const dlen = float( len2.fwidth() ).toVar();
  32345. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  32346. } else {
  32347. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  32348. }
  32349. return alpha;
  32350. } );
  32351. // Three.js Transpiler
  32352. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  32353. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  32354. const f = float( f_immutable ).toVar();
  32355. const t = float( t_immutable ).toVar();
  32356. const b = bool( b_immutable ).toVar();
  32357. return select( b, t, f );
  32358. } ).setLayout( {
  32359. name: 'mx_select',
  32360. type: 'float',
  32361. inputs: [
  32362. { name: 'b', type: 'bool' },
  32363. { name: 't', type: 'float' },
  32364. { name: 'f', type: 'float' }
  32365. ]
  32366. } );
  32367. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  32368. const b = bool( b_immutable ).toVar();
  32369. const val = float( val_immutable ).toVar();
  32370. return select( b, val.negate(), val );
  32371. } ).setLayout( {
  32372. name: 'mx_negate_if',
  32373. type: 'float',
  32374. inputs: [
  32375. { name: 'val', type: 'float' },
  32376. { name: 'b', type: 'bool' }
  32377. ]
  32378. } );
  32379. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32380. const x = float( x_immutable ).toVar();
  32381. return int( floor( x ) );
  32382. } ).setLayout( {
  32383. name: 'mx_floor',
  32384. type: 'int',
  32385. inputs: [
  32386. { name: 'x', type: 'float' }
  32387. ]
  32388. } );
  32389. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  32390. const x = float( x_immutable ).toVar();
  32391. i.assign( mx_floor( x ) );
  32392. return x.sub( float( i ) );
  32393. } );
  32394. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32395. const t = float( t_immutable ).toVar();
  32396. const s = float( s_immutable ).toVar();
  32397. const v3 = float( v3_immutable ).toVar();
  32398. const v2 = float( v2_immutable ).toVar();
  32399. const v1 = float( v1_immutable ).toVar();
  32400. const v0 = float( v0_immutable ).toVar();
  32401. const s1 = float( sub( 1.0, s ) ).toVar();
  32402. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32403. } ).setLayout( {
  32404. name: 'mx_bilerp_0',
  32405. type: 'float',
  32406. inputs: [
  32407. { name: 'v0', type: 'float' },
  32408. { name: 'v1', type: 'float' },
  32409. { name: 'v2', type: 'float' },
  32410. { name: 'v3', type: 'float' },
  32411. { name: 's', type: 'float' },
  32412. { name: 't', type: 'float' }
  32413. ]
  32414. } );
  32415. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32416. const t = float( t_immutable ).toVar();
  32417. const s = float( s_immutable ).toVar();
  32418. const v3 = vec3( v3_immutable ).toVar();
  32419. const v2 = vec3( v2_immutable ).toVar();
  32420. const v1 = vec3( v1_immutable ).toVar();
  32421. const v0 = vec3( v0_immutable ).toVar();
  32422. const s1 = float( sub( 1.0, s ) ).toVar();
  32423. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32424. } ).setLayout( {
  32425. name: 'mx_bilerp_1',
  32426. type: 'vec3',
  32427. inputs: [
  32428. { name: 'v0', type: 'vec3' },
  32429. { name: 'v1', type: 'vec3' },
  32430. { name: 'v2', type: 'vec3' },
  32431. { name: 'v3', type: 'vec3' },
  32432. { name: 's', type: 'float' },
  32433. { name: 't', type: 'float' }
  32434. ]
  32435. } );
  32436. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  32437. 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 ] ) => {
  32438. const r = float( r_immutable ).toVar();
  32439. const t = float( t_immutable ).toVar();
  32440. const s = float( s_immutable ).toVar();
  32441. const v7 = float( v7_immutable ).toVar();
  32442. const v6 = float( v6_immutable ).toVar();
  32443. const v5 = float( v5_immutable ).toVar();
  32444. const v4 = float( v4_immutable ).toVar();
  32445. const v3 = float( v3_immutable ).toVar();
  32446. const v2 = float( v2_immutable ).toVar();
  32447. const v1 = float( v1_immutable ).toVar();
  32448. const v0 = float( v0_immutable ).toVar();
  32449. const s1 = float( sub( 1.0, s ) ).toVar();
  32450. const t1 = float( sub( 1.0, t ) ).toVar();
  32451. const r1 = float( sub( 1.0, r ) ).toVar();
  32452. 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 ) ) ) ) ) );
  32453. } ).setLayout( {
  32454. name: 'mx_trilerp_0',
  32455. type: 'float',
  32456. inputs: [
  32457. { name: 'v0', type: 'float' },
  32458. { name: 'v1', type: 'float' },
  32459. { name: 'v2', type: 'float' },
  32460. { name: 'v3', type: 'float' },
  32461. { name: 'v4', type: 'float' },
  32462. { name: 'v5', type: 'float' },
  32463. { name: 'v6', type: 'float' },
  32464. { name: 'v7', type: 'float' },
  32465. { name: 's', type: 'float' },
  32466. { name: 't', type: 'float' },
  32467. { name: 'r', type: 'float' }
  32468. ]
  32469. } );
  32470. 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 ] ) => {
  32471. const r = float( r_immutable ).toVar();
  32472. const t = float( t_immutable ).toVar();
  32473. const s = float( s_immutable ).toVar();
  32474. const v7 = vec3( v7_immutable ).toVar();
  32475. const v6 = vec3( v6_immutable ).toVar();
  32476. const v5 = vec3( v5_immutable ).toVar();
  32477. const v4 = vec3( v4_immutable ).toVar();
  32478. const v3 = vec3( v3_immutable ).toVar();
  32479. const v2 = vec3( v2_immutable ).toVar();
  32480. const v1 = vec3( v1_immutable ).toVar();
  32481. const v0 = vec3( v0_immutable ).toVar();
  32482. const s1 = float( sub( 1.0, s ) ).toVar();
  32483. const t1 = float( sub( 1.0, t ) ).toVar();
  32484. const r1 = float( sub( 1.0, r ) ).toVar();
  32485. 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 ) ) ) ) ) );
  32486. } ).setLayout( {
  32487. name: 'mx_trilerp_1',
  32488. type: 'vec3',
  32489. inputs: [
  32490. { name: 'v0', type: 'vec3' },
  32491. { name: 'v1', type: 'vec3' },
  32492. { name: 'v2', type: 'vec3' },
  32493. { name: 'v3', type: 'vec3' },
  32494. { name: 'v4', type: 'vec3' },
  32495. { name: 'v5', type: 'vec3' },
  32496. { name: 'v6', type: 'vec3' },
  32497. { name: 'v7', type: 'vec3' },
  32498. { name: 's', type: 'float' },
  32499. { name: 't', type: 'float' },
  32500. { name: 'r', type: 'float' }
  32501. ]
  32502. } );
  32503. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  32504. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32505. const y = float( y_immutable ).toVar();
  32506. const x = float( x_immutable ).toVar();
  32507. const hash = uint( hash_immutable ).toVar();
  32508. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  32509. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  32510. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  32511. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32512. } ).setLayout( {
  32513. name: 'mx_gradient_float_0',
  32514. type: 'float',
  32515. inputs: [
  32516. { name: 'hash', type: 'uint' },
  32517. { name: 'x', type: 'float' },
  32518. { name: 'y', type: 'float' }
  32519. ]
  32520. } );
  32521. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32522. const z = float( z_immutable ).toVar();
  32523. const y = float( y_immutable ).toVar();
  32524. const x = float( x_immutable ).toVar();
  32525. const hash = uint( hash_immutable ).toVar();
  32526. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  32527. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  32528. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  32529. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32530. } ).setLayout( {
  32531. name: 'mx_gradient_float_1',
  32532. type: 'float',
  32533. inputs: [
  32534. { name: 'hash', type: 'uint' },
  32535. { name: 'x', type: 'float' },
  32536. { name: 'y', type: 'float' },
  32537. { name: 'z', type: 'float' }
  32538. ]
  32539. } );
  32540. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  32541. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32542. const y = float( y_immutable ).toVar();
  32543. const x = float( x_immutable ).toVar();
  32544. const hash = uvec3( hash_immutable ).toVar();
  32545. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  32546. } ).setLayout( {
  32547. name: 'mx_gradient_vec3_0',
  32548. type: 'vec3',
  32549. inputs: [
  32550. { name: 'hash', type: 'uvec3' },
  32551. { name: 'x', type: 'float' },
  32552. { name: 'y', type: 'float' }
  32553. ]
  32554. } );
  32555. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32556. const z = float( z_immutable ).toVar();
  32557. const y = float( y_immutable ).toVar();
  32558. const x = float( x_immutable ).toVar();
  32559. const hash = uvec3( hash_immutable ).toVar();
  32560. 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 ) );
  32561. } ).setLayout( {
  32562. name: 'mx_gradient_vec3_1',
  32563. type: 'vec3',
  32564. inputs: [
  32565. { name: 'hash', type: 'uvec3' },
  32566. { name: 'x', type: 'float' },
  32567. { name: 'y', type: 'float' },
  32568. { name: 'z', type: 'float' }
  32569. ]
  32570. } );
  32571. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  32572. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32573. const v = float( v_immutable ).toVar();
  32574. return mul( 0.6616, v );
  32575. } ).setLayout( {
  32576. name: 'mx_gradient_scale2d_0',
  32577. type: 'float',
  32578. inputs: [
  32579. { name: 'v', type: 'float' }
  32580. ]
  32581. } );
  32582. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32583. const v = float( v_immutable ).toVar();
  32584. return mul( 0.9820, v );
  32585. } ).setLayout( {
  32586. name: 'mx_gradient_scale3d_0',
  32587. type: 'float',
  32588. inputs: [
  32589. { name: 'v', type: 'float' }
  32590. ]
  32591. } );
  32592. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32593. const v = vec3( v_immutable ).toVar();
  32594. return mul( 0.6616, v );
  32595. } ).setLayout( {
  32596. name: 'mx_gradient_scale2d_1',
  32597. type: 'vec3',
  32598. inputs: [
  32599. { name: 'v', type: 'vec3' }
  32600. ]
  32601. } );
  32602. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  32603. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32604. const v = vec3( v_immutable ).toVar();
  32605. return mul( 0.9820, v );
  32606. } ).setLayout( {
  32607. name: 'mx_gradient_scale3d_1',
  32608. type: 'vec3',
  32609. inputs: [
  32610. { name: 'v', type: 'vec3' }
  32611. ]
  32612. } );
  32613. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  32614. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  32615. const k = int( k_immutable ).toVar();
  32616. const x = uint( x_immutable ).toVar();
  32617. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  32618. } ).setLayout( {
  32619. name: 'mx_rotl32',
  32620. type: 'uint',
  32621. inputs: [
  32622. { name: 'x', type: 'uint' },
  32623. { name: 'k', type: 'int' }
  32624. ]
  32625. } );
  32626. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  32627. a.subAssign( c );
  32628. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  32629. c.addAssign( b );
  32630. b.subAssign( a );
  32631. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  32632. a.addAssign( c );
  32633. c.subAssign( b );
  32634. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  32635. b.addAssign( a );
  32636. a.subAssign( c );
  32637. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  32638. c.addAssign( b );
  32639. b.subAssign( a );
  32640. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  32641. a.addAssign( c );
  32642. c.subAssign( b );
  32643. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  32644. b.addAssign( a );
  32645. } );
  32646. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  32647. const c = uint( c_immutable ).toVar();
  32648. const b = uint( b_immutable ).toVar();
  32649. const a = uint( a_immutable ).toVar();
  32650. c.bitXorAssign( b );
  32651. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  32652. a.bitXorAssign( c );
  32653. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  32654. b.bitXorAssign( a );
  32655. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  32656. c.bitXorAssign( b );
  32657. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  32658. a.bitXorAssign( c );
  32659. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  32660. b.bitXorAssign( a );
  32661. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  32662. c.bitXorAssign( b );
  32663. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  32664. return c;
  32665. } ).setLayout( {
  32666. name: 'mx_bjfinal',
  32667. type: 'uint',
  32668. inputs: [
  32669. { name: 'a', type: 'uint' },
  32670. { name: 'b', type: 'uint' },
  32671. { name: 'c', type: 'uint' }
  32672. ]
  32673. } );
  32674. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  32675. const bits = uint( bits_immutable ).toVar();
  32676. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  32677. } ).setLayout( {
  32678. name: 'mx_bits_to_01',
  32679. type: 'float',
  32680. inputs: [
  32681. { name: 'bits', type: 'uint' }
  32682. ]
  32683. } );
  32684. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  32685. const t = float( t_immutable ).toVar();
  32686. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  32687. } ).setLayout( {
  32688. name: 'mx_fade',
  32689. type: 'float',
  32690. inputs: [
  32691. { name: 't', type: 'float' }
  32692. ]
  32693. } );
  32694. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32695. const x = int( x_immutable ).toVar();
  32696. const len = uint( uint( 1 ) ).toVar();
  32697. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  32698. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  32699. } ).setLayout( {
  32700. name: 'mx_hash_int_0',
  32701. type: 'uint',
  32702. inputs: [
  32703. { name: 'x', type: 'int' }
  32704. ]
  32705. } );
  32706. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32707. const y = int( y_immutable ).toVar();
  32708. const x = int( x_immutable ).toVar();
  32709. const len = uint( uint( 2 ) ).toVar();
  32710. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32711. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32712. a.addAssign( uint( x ) );
  32713. b.addAssign( uint( y ) );
  32714. return mx_bjfinal( a, b, c );
  32715. } ).setLayout( {
  32716. name: 'mx_hash_int_1',
  32717. type: 'uint',
  32718. inputs: [
  32719. { name: 'x', type: 'int' },
  32720. { name: 'y', type: 'int' }
  32721. ]
  32722. } );
  32723. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32724. const z = int( z_immutable ).toVar();
  32725. const y = int( y_immutable ).toVar();
  32726. const x = int( x_immutable ).toVar();
  32727. const len = uint( uint( 3 ) ).toVar();
  32728. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32729. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32730. a.addAssign( uint( x ) );
  32731. b.addAssign( uint( y ) );
  32732. c.addAssign( uint( z ) );
  32733. return mx_bjfinal( a, b, c );
  32734. } ).setLayout( {
  32735. name: 'mx_hash_int_2',
  32736. type: 'uint',
  32737. inputs: [
  32738. { name: 'x', type: 'int' },
  32739. { name: 'y', type: 'int' },
  32740. { name: 'z', type: 'int' }
  32741. ]
  32742. } );
  32743. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  32744. const xx = int( xx_immutable ).toVar();
  32745. const z = int( z_immutable ).toVar();
  32746. const y = int( y_immutable ).toVar();
  32747. const x = int( x_immutable ).toVar();
  32748. const len = uint( uint( 4 ) ).toVar();
  32749. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32750. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32751. a.addAssign( uint( x ) );
  32752. b.addAssign( uint( y ) );
  32753. c.addAssign( uint( z ) );
  32754. mx_bjmix( a, b, c );
  32755. a.addAssign( uint( xx ) );
  32756. return mx_bjfinal( a, b, c );
  32757. } ).setLayout( {
  32758. name: 'mx_hash_int_3',
  32759. type: 'uint',
  32760. inputs: [
  32761. { name: 'x', type: 'int' },
  32762. { name: 'y', type: 'int' },
  32763. { name: 'z', type: 'int' },
  32764. { name: 'xx', type: 'int' }
  32765. ]
  32766. } );
  32767. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  32768. const yy = int( yy_immutable ).toVar();
  32769. const xx = int( xx_immutable ).toVar();
  32770. const z = int( z_immutable ).toVar();
  32771. const y = int( y_immutable ).toVar();
  32772. const x = int( x_immutable ).toVar();
  32773. const len = uint( uint( 5 ) ).toVar();
  32774. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32775. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32776. a.addAssign( uint( x ) );
  32777. b.addAssign( uint( y ) );
  32778. c.addAssign( uint( z ) );
  32779. mx_bjmix( a, b, c );
  32780. a.addAssign( uint( xx ) );
  32781. b.addAssign( uint( yy ) );
  32782. return mx_bjfinal( a, b, c );
  32783. } ).setLayout( {
  32784. name: 'mx_hash_int_4',
  32785. type: 'uint',
  32786. inputs: [
  32787. { name: 'x', type: 'int' },
  32788. { name: 'y', type: 'int' },
  32789. { name: 'z', type: 'int' },
  32790. { name: 'xx', type: 'int' },
  32791. { name: 'yy', type: 'int' }
  32792. ]
  32793. } );
  32794. 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 ] );
  32795. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32796. const y = int( y_immutable ).toVar();
  32797. const x = int( x_immutable ).toVar();
  32798. const h = uint( mx_hash_int( x, y ) ).toVar();
  32799. const result = uvec3().toVar();
  32800. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32801. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32802. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32803. return result;
  32804. } ).setLayout( {
  32805. name: 'mx_hash_vec3_0',
  32806. type: 'uvec3',
  32807. inputs: [
  32808. { name: 'x', type: 'int' },
  32809. { name: 'y', type: 'int' }
  32810. ]
  32811. } );
  32812. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32813. const z = int( z_immutable ).toVar();
  32814. const y = int( y_immutable ).toVar();
  32815. const x = int( x_immutable ).toVar();
  32816. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  32817. const result = uvec3().toVar();
  32818. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32819. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32820. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32821. return result;
  32822. } ).setLayout( {
  32823. name: 'mx_hash_vec3_1',
  32824. type: 'uvec3',
  32825. inputs: [
  32826. { name: 'x', type: 'int' },
  32827. { name: 'y', type: 'int' },
  32828. { name: 'z', type: 'int' }
  32829. ]
  32830. } );
  32831. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  32832. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32833. const p = vec2( p_immutable ).toVar();
  32834. const X = int().toVar(), Y = int().toVar();
  32835. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32836. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32837. const u = float( mx_fade( fx ) ).toVar();
  32838. const v = float( mx_fade( fy ) ).toVar();
  32839. 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();
  32840. return mx_gradient_scale2d( result );
  32841. } ).setLayout( {
  32842. name: 'mx_perlin_noise_float_0',
  32843. type: 'float',
  32844. inputs: [
  32845. { name: 'p', type: 'vec2' }
  32846. ]
  32847. } );
  32848. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32849. const p = vec3( p_immutable ).toVar();
  32850. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32851. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32852. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32853. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32854. const u = float( mx_fade( fx ) ).toVar();
  32855. const v = float( mx_fade( fy ) ).toVar();
  32856. const w = float( mx_fade( fz ) ).toVar();
  32857. 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();
  32858. return mx_gradient_scale3d( result );
  32859. } ).setLayout( {
  32860. name: 'mx_perlin_noise_float_1',
  32861. type: 'float',
  32862. inputs: [
  32863. { name: 'p', type: 'vec3' }
  32864. ]
  32865. } );
  32866. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  32867. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32868. const p = vec2( p_immutable ).toVar();
  32869. const X = int().toVar(), Y = int().toVar();
  32870. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32871. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32872. const u = float( mx_fade( fx ) ).toVar();
  32873. const v = float( mx_fade( fy ) ).toVar();
  32874. 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();
  32875. return mx_gradient_scale2d( result );
  32876. } ).setLayout( {
  32877. name: 'mx_perlin_noise_vec3_0',
  32878. type: 'vec3',
  32879. inputs: [
  32880. { name: 'p', type: 'vec2' }
  32881. ]
  32882. } );
  32883. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32884. const p = vec3( p_immutable ).toVar();
  32885. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32886. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32887. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32888. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32889. const u = float( mx_fade( fx ) ).toVar();
  32890. const v = float( mx_fade( fy ) ).toVar();
  32891. const w = float( mx_fade( fz ) ).toVar();
  32892. 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();
  32893. return mx_gradient_scale3d( result );
  32894. } ).setLayout( {
  32895. name: 'mx_perlin_noise_vec3_1',
  32896. type: 'vec3',
  32897. inputs: [
  32898. { name: 'p', type: 'vec3' }
  32899. ]
  32900. } );
  32901. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  32902. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32903. const p = float( p_immutable ).toVar();
  32904. const ix = int( mx_floor( p ) ).toVar();
  32905. return mx_bits_to_01( mx_hash_int( ix ) );
  32906. } ).setLayout( {
  32907. name: 'mx_cell_noise_float_0',
  32908. type: 'float',
  32909. inputs: [
  32910. { name: 'p', type: 'float' }
  32911. ]
  32912. } );
  32913. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32914. const p = vec2( p_immutable ).toVar();
  32915. const ix = int( mx_floor( p.x ) ).toVar();
  32916. const iy = int( mx_floor( p.y ) ).toVar();
  32917. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  32918. } ).setLayout( {
  32919. name: 'mx_cell_noise_float_1',
  32920. type: 'float',
  32921. inputs: [
  32922. { name: 'p', type: 'vec2' }
  32923. ]
  32924. } );
  32925. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32926. const p = vec3( p_immutable ).toVar();
  32927. const ix = int( mx_floor( p.x ) ).toVar();
  32928. const iy = int( mx_floor( p.y ) ).toVar();
  32929. const iz = int( mx_floor( p.z ) ).toVar();
  32930. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  32931. } ).setLayout( {
  32932. name: 'mx_cell_noise_float_2',
  32933. type: 'float',
  32934. inputs: [
  32935. { name: 'p', type: 'vec3' }
  32936. ]
  32937. } );
  32938. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32939. const p = vec4( p_immutable ).toVar();
  32940. const ix = int( mx_floor( p.x ) ).toVar();
  32941. const iy = int( mx_floor( p.y ) ).toVar();
  32942. const iz = int( mx_floor( p.z ) ).toVar();
  32943. const iw = int( mx_floor( p.w ) ).toVar();
  32944. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  32945. } ).setLayout( {
  32946. name: 'mx_cell_noise_float_3',
  32947. type: 'float',
  32948. inputs: [
  32949. { name: 'p', type: 'vec4' }
  32950. ]
  32951. } );
  32952. 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 ] );
  32953. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32954. const p = float( p_immutable ).toVar();
  32955. const ix = int( mx_floor( p ) ).toVar();
  32956. 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 ) ) ) );
  32957. } ).setLayout( {
  32958. name: 'mx_cell_noise_vec3_0',
  32959. type: 'vec3',
  32960. inputs: [
  32961. { name: 'p', type: 'float' }
  32962. ]
  32963. } );
  32964. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32965. const p = vec2( p_immutable ).toVar();
  32966. const ix = int( mx_floor( p.x ) ).toVar();
  32967. const iy = int( mx_floor( p.y ) ).toVar();
  32968. 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 ) ) ) );
  32969. } ).setLayout( {
  32970. name: 'mx_cell_noise_vec3_1',
  32971. type: 'vec3',
  32972. inputs: [
  32973. { name: 'p', type: 'vec2' }
  32974. ]
  32975. } );
  32976. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32977. const p = vec3( p_immutable ).toVar();
  32978. const ix = int( mx_floor( p.x ) ).toVar();
  32979. const iy = int( mx_floor( p.y ) ).toVar();
  32980. const iz = int( mx_floor( p.z ) ).toVar();
  32981. 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 ) ) ) );
  32982. } ).setLayout( {
  32983. name: 'mx_cell_noise_vec3_2',
  32984. type: 'vec3',
  32985. inputs: [
  32986. { name: 'p', type: 'vec3' }
  32987. ]
  32988. } );
  32989. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32990. const p = vec4( p_immutable ).toVar();
  32991. const ix = int( mx_floor( p.x ) ).toVar();
  32992. const iy = int( mx_floor( p.y ) ).toVar();
  32993. const iz = int( mx_floor( p.z ) ).toVar();
  32994. const iw = int( mx_floor( p.w ) ).toVar();
  32995. 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 ) ) ) );
  32996. } ).setLayout( {
  32997. name: 'mx_cell_noise_vec3_3',
  32998. type: 'vec3',
  32999. inputs: [
  33000. { name: 'p', type: 'vec4' }
  33001. ]
  33002. } );
  33003. 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 ] );
  33004. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33005. const diminish = float( diminish_immutable ).toVar();
  33006. const lacunarity = float( lacunarity_immutable ).toVar();
  33007. const octaves = int( octaves_immutable ).toVar();
  33008. const p = vec3( p_immutable ).toVar();
  33009. const result = float( 0.0 ).toVar();
  33010. const amplitude = float( 1.0 ).toVar();
  33011. Loop( octaves, () => {
  33012. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  33013. amplitude.mulAssign( diminish );
  33014. p.mulAssign( lacunarity );
  33015. } );
  33016. return result;
  33017. } ).setLayout( {
  33018. name: 'mx_fractal_noise_float',
  33019. type: 'float',
  33020. inputs: [
  33021. { name: 'p', type: 'vec3' },
  33022. { name: 'octaves', type: 'int' },
  33023. { name: 'lacunarity', type: 'float' },
  33024. { name: 'diminish', type: 'float' }
  33025. ]
  33026. } );
  33027. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33028. const diminish = float( diminish_immutable ).toVar();
  33029. const lacunarity = float( lacunarity_immutable ).toVar();
  33030. const octaves = int( octaves_immutable ).toVar();
  33031. const p = vec3( p_immutable ).toVar();
  33032. const result = vec3( 0.0 ).toVar();
  33033. const amplitude = float( 1.0 ).toVar();
  33034. Loop( octaves, () => {
  33035. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  33036. amplitude.mulAssign( diminish );
  33037. p.mulAssign( lacunarity );
  33038. } );
  33039. return result;
  33040. } ).setLayout( {
  33041. name: 'mx_fractal_noise_vec3',
  33042. type: 'vec3',
  33043. inputs: [
  33044. { name: 'p', type: 'vec3' },
  33045. { name: 'octaves', type: 'int' },
  33046. { name: 'lacunarity', type: 'float' },
  33047. { name: 'diminish', type: 'float' }
  33048. ]
  33049. } );
  33050. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33051. const diminish = float( diminish_immutable ).toVar();
  33052. const lacunarity = float( lacunarity_immutable ).toVar();
  33053. const octaves = int( octaves_immutable ).toVar();
  33054. const p = vec3( p_immutable ).toVar();
  33055. 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 ) );
  33056. } ).setLayout( {
  33057. name: 'mx_fractal_noise_vec2',
  33058. type: 'vec2',
  33059. inputs: [
  33060. { name: 'p', type: 'vec3' },
  33061. { name: 'octaves', type: 'int' },
  33062. { name: 'lacunarity', type: 'float' },
  33063. { name: 'diminish', type: 'float' }
  33064. ]
  33065. } );
  33066. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  33067. const diminish = float( diminish_immutable ).toVar();
  33068. const lacunarity = float( lacunarity_immutable ).toVar();
  33069. const octaves = int( octaves_immutable ).toVar();
  33070. const p = vec3( p_immutable ).toVar();
  33071. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  33072. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  33073. return vec4( c, f );
  33074. } ).setLayout( {
  33075. name: 'mx_fractal_noise_vec4',
  33076. type: 'vec4',
  33077. inputs: [
  33078. { name: 'p', type: 'vec3' },
  33079. { name: 'octaves', type: 'int' },
  33080. { name: 'lacunarity', type: 'float' },
  33081. { name: 'diminish', type: 'float' }
  33082. ]
  33083. } );
  33084. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  33085. const metric = int( metric_immutable ).toVar();
  33086. const jitter = float( jitter_immutable ).toVar();
  33087. const yoff = int( yoff_immutable ).toVar();
  33088. const xoff = int( xoff_immutable ).toVar();
  33089. const y = int( y_immutable ).toVar();
  33090. const x = int( x_immutable ).toVar();
  33091. const p = vec2( p_immutable ).toVar();
  33092. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  33093. const off = vec2( tmp.x, tmp.y ).toVar();
  33094. off.subAssign( 0.5 );
  33095. off.mulAssign( jitter );
  33096. off.addAssign( 0.5 );
  33097. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  33098. const diff = vec2( cellpos.sub( p ) ).toVar();
  33099. If( metric.equal( int( 2 ) ), () => {
  33100. return abs( diff.x ).add( abs( diff.y ) );
  33101. } );
  33102. If( metric.equal( int( 3 ) ), () => {
  33103. return max$1( abs( diff.x ), abs( diff.y ) );
  33104. } );
  33105. return dot( diff, diff );
  33106. } ).setLayout( {
  33107. name: 'mx_worley_distance_0',
  33108. type: 'float',
  33109. inputs: [
  33110. { name: 'p', type: 'vec2' },
  33111. { name: 'x', type: 'int' },
  33112. { name: 'y', type: 'int' },
  33113. { name: 'xoff', type: 'int' },
  33114. { name: 'yoff', type: 'int' },
  33115. { name: 'jitter', type: 'float' },
  33116. { name: 'metric', type: 'int' }
  33117. ]
  33118. } );
  33119. 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 ] ) => {
  33120. const metric = int( metric_immutable ).toVar();
  33121. const jitter = float( jitter_immutable ).toVar();
  33122. const zoff = int( zoff_immutable ).toVar();
  33123. const yoff = int( yoff_immutable ).toVar();
  33124. const xoff = int( xoff_immutable ).toVar();
  33125. const z = int( z_immutable ).toVar();
  33126. const y = int( y_immutable ).toVar();
  33127. const x = int( x_immutable ).toVar();
  33128. const p = vec3( p_immutable ).toVar();
  33129. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  33130. off.subAssign( 0.5 );
  33131. off.mulAssign( jitter );
  33132. off.addAssign( 0.5 );
  33133. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  33134. const diff = vec3( cellpos.sub( p ) ).toVar();
  33135. If( metric.equal( int( 2 ) ), () => {
  33136. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  33137. } );
  33138. If( metric.equal( int( 3 ) ), () => {
  33139. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  33140. } );
  33141. return dot( diff, diff );
  33142. } ).setLayout( {
  33143. name: 'mx_worley_distance_1',
  33144. type: 'float',
  33145. inputs: [
  33146. { name: 'p', type: 'vec3' },
  33147. { name: 'x', type: 'int' },
  33148. { name: 'y', type: 'int' },
  33149. { name: 'z', type: 'int' },
  33150. { name: 'xoff', type: 'int' },
  33151. { name: 'yoff', type: 'int' },
  33152. { name: 'zoff', type: 'int' },
  33153. { name: 'jitter', type: 'float' },
  33154. { name: 'metric', type: 'int' }
  33155. ]
  33156. } );
  33157. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  33158. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33159. const metric = int( metric_immutable ).toVar();
  33160. const jitter = float( jitter_immutable ).toVar();
  33161. const p = vec2( p_immutable ).toVar();
  33162. const X = int().toVar(), Y = int().toVar();
  33163. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33164. const sqdist = float( 1e6 ).toVar();
  33165. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33166. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33167. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33168. sqdist.assign( min$1( sqdist, dist ) );
  33169. } );
  33170. } );
  33171. If( metric.equal( int( 0 ) ), () => {
  33172. sqdist.assign( sqrt( sqdist ) );
  33173. } );
  33174. return sqdist;
  33175. } ).setLayout( {
  33176. name: 'mx_worley_noise_float_0',
  33177. type: 'float',
  33178. inputs: [
  33179. { name: 'p', type: 'vec2' },
  33180. { name: 'jitter', type: 'float' },
  33181. { name: 'metric', type: 'int' }
  33182. ]
  33183. } );
  33184. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33185. const metric = int( metric_immutable ).toVar();
  33186. const jitter = float( jitter_immutable ).toVar();
  33187. const p = vec2( p_immutable ).toVar();
  33188. const X = int().toVar(), Y = int().toVar();
  33189. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33190. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33191. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33192. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33193. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33194. If( dist.lessThan( sqdist.x ), () => {
  33195. sqdist.y.assign( sqdist.x );
  33196. sqdist.x.assign( dist );
  33197. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33198. sqdist.y.assign( dist );
  33199. } );
  33200. } );
  33201. } );
  33202. If( metric.equal( int( 0 ) ), () => {
  33203. sqdist.assign( sqrt( sqdist ) );
  33204. } );
  33205. return sqdist;
  33206. } ).setLayout( {
  33207. name: 'mx_worley_noise_vec2_0',
  33208. type: 'vec2',
  33209. inputs: [
  33210. { name: 'p', type: 'vec2' },
  33211. { name: 'jitter', type: 'float' },
  33212. { name: 'metric', type: 'int' }
  33213. ]
  33214. } );
  33215. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33216. const metric = int( metric_immutable ).toVar();
  33217. const jitter = float( jitter_immutable ).toVar();
  33218. const p = vec2( p_immutable ).toVar();
  33219. const X = int().toVar(), Y = int().toVar();
  33220. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33221. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33222. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33223. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33224. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33225. If( dist.lessThan( sqdist.x ), () => {
  33226. sqdist.z.assign( sqdist.y );
  33227. sqdist.y.assign( sqdist.x );
  33228. sqdist.x.assign( dist );
  33229. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33230. sqdist.z.assign( sqdist.y );
  33231. sqdist.y.assign( dist );
  33232. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33233. sqdist.z.assign( dist );
  33234. } );
  33235. } );
  33236. } );
  33237. If( metric.equal( int( 0 ) ), () => {
  33238. sqdist.assign( sqrt( sqdist ) );
  33239. } );
  33240. return sqdist;
  33241. } ).setLayout( {
  33242. name: 'mx_worley_noise_vec3_0',
  33243. type: 'vec3',
  33244. inputs: [
  33245. { name: 'p', type: 'vec2' },
  33246. { name: 'jitter', type: 'float' },
  33247. { name: 'metric', type: 'int' }
  33248. ]
  33249. } );
  33250. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33251. const metric = int( metric_immutable ).toVar();
  33252. const jitter = float( jitter_immutable ).toVar();
  33253. const p = vec3( p_immutable ).toVar();
  33254. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33255. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33256. const sqdist = float( 1e6 ).toVar();
  33257. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33258. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33259. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33260. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33261. sqdist.assign( min$1( sqdist, dist ) );
  33262. } );
  33263. } );
  33264. } );
  33265. If( metric.equal( int( 0 ) ), () => {
  33266. sqdist.assign( sqrt( sqdist ) );
  33267. } );
  33268. return sqdist;
  33269. } ).setLayout( {
  33270. name: 'mx_worley_noise_float_1',
  33271. type: 'float',
  33272. inputs: [
  33273. { name: 'p', type: 'vec3' },
  33274. { name: 'jitter', type: 'float' },
  33275. { name: 'metric', type: 'int' }
  33276. ]
  33277. } );
  33278. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  33279. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33280. const metric = int( metric_immutable ).toVar();
  33281. const jitter = float( jitter_immutable ).toVar();
  33282. const p = vec3( p_immutable ).toVar();
  33283. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33284. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33285. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33286. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33287. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33288. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33289. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33290. If( dist.lessThan( sqdist.x ), () => {
  33291. sqdist.y.assign( sqdist.x );
  33292. sqdist.x.assign( dist );
  33293. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33294. sqdist.y.assign( dist );
  33295. } );
  33296. } );
  33297. } );
  33298. } );
  33299. If( metric.equal( int( 0 ) ), () => {
  33300. sqdist.assign( sqrt( sqdist ) );
  33301. } );
  33302. return sqdist;
  33303. } ).setLayout( {
  33304. name: 'mx_worley_noise_vec2_1',
  33305. type: 'vec2',
  33306. inputs: [
  33307. { name: 'p', type: 'vec3' },
  33308. { name: 'jitter', type: 'float' },
  33309. { name: 'metric', type: 'int' }
  33310. ]
  33311. } );
  33312. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  33313. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33314. const metric = int( metric_immutable ).toVar();
  33315. const jitter = float( jitter_immutable ).toVar();
  33316. const p = vec3( p_immutable ).toVar();
  33317. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33318. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33319. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33320. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33321. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33322. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33323. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33324. If( dist.lessThan( sqdist.x ), () => {
  33325. sqdist.z.assign( sqdist.y );
  33326. sqdist.y.assign( sqdist.x );
  33327. sqdist.x.assign( dist );
  33328. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33329. sqdist.z.assign( sqdist.y );
  33330. sqdist.y.assign( dist );
  33331. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33332. sqdist.z.assign( dist );
  33333. } );
  33334. } );
  33335. } );
  33336. } );
  33337. If( metric.equal( int( 0 ) ), () => {
  33338. sqdist.assign( sqrt( sqdist ) );
  33339. } );
  33340. return sqdist;
  33341. } ).setLayout( {
  33342. name: 'mx_worley_noise_vec3_1',
  33343. type: 'vec3',
  33344. inputs: [
  33345. { name: 'p', type: 'vec3' },
  33346. { name: 'jitter', type: 'float' },
  33347. { name: 'metric', type: 'int' }
  33348. ]
  33349. } );
  33350. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  33351. // Unified Noise 2D
  33352. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  33353. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  33354. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33355. octaves_immutable, lacunarity_immutable, diminish_immutable
  33356. ] ) => {
  33357. const noiseType = int( noiseType_immutable ).toVar();
  33358. const texcoord = vec2( texcoord_immutable ).toVar();
  33359. const freq = vec2( freq_immutable ).toVar();
  33360. const offset = vec2( offset_immutable ).toVar();
  33361. const jitter = float( jitter_immutable ).toVar();
  33362. const outmin = float( outmin_immutable ).toVar();
  33363. const outmax = float( outmax_immutable ).toVar();
  33364. const clampoutput = bool( clampoutput_immutable ).toVar();
  33365. const octaves = int( octaves_immutable ).toVar();
  33366. const lacunarity = float( lacunarity_immutable ).toVar();
  33367. const diminish = float( diminish_immutable ).toVar();
  33368. // Compute input position
  33369. const p = texcoord.mul( freq ).add( offset );
  33370. const result = float( 0.0 ).toVar();
  33371. // Perlin
  33372. If( noiseType.equal( int( 0 ) ), () => {
  33373. result.assign( mx_perlin_noise_vec3( p ) );
  33374. } );
  33375. // Cell
  33376. If( noiseType.equal( int( 1 ) ), () => {
  33377. result.assign( mx_cell_noise_vec3( p ) );
  33378. } );
  33379. // Worley (metric=0 = euclidean)
  33380. If( noiseType.equal( int( 2 ) ), () => {
  33381. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33382. } );
  33383. // Fractal (use vec3(p, 0.0) for 2D input)
  33384. If( noiseType.equal( int( 3 ) ), () => {
  33385. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  33386. } );
  33387. // Remap output to [outmin, outmax]
  33388. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33389. // Clamp if requested
  33390. If( clampoutput, () => {
  33391. result.assign( clamp( result, outmin, outmax ) );
  33392. } );
  33393. return result;
  33394. } ).setLayout( {
  33395. name: 'mx_unifiednoise2d',
  33396. type: 'float',
  33397. inputs: [
  33398. { name: 'noiseType', type: 'int' },
  33399. { name: 'texcoord', type: 'vec2' },
  33400. { name: 'freq', type: 'vec2' },
  33401. { name: 'offset', type: 'vec2' },
  33402. { name: 'jitter', type: 'float' },
  33403. { name: 'outmin', type: 'float' },
  33404. { name: 'outmax', type: 'float' },
  33405. { name: 'clampoutput', type: 'bool' },
  33406. { name: 'octaves', type: 'int' },
  33407. { name: 'lacunarity', type: 'float' },
  33408. { name: 'diminish', type: 'float' }
  33409. ]
  33410. } );
  33411. // Unified Noise 3D
  33412. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  33413. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  33414. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33415. octaves_immutable, lacunarity_immutable, diminish_immutable
  33416. ] ) => {
  33417. const noiseType = int( noiseType_immutable ).toVar();
  33418. const position = vec3( position_immutable ).toVar();
  33419. const freq = vec3( freq_immutable ).toVar();
  33420. const offset = vec3( offset_immutable ).toVar();
  33421. const jitter = float( jitter_immutable ).toVar();
  33422. const outmin = float( outmin_immutable ).toVar();
  33423. const outmax = float( outmax_immutable ).toVar();
  33424. const clampoutput = bool( clampoutput_immutable ).toVar();
  33425. const octaves = int( octaves_immutable ).toVar();
  33426. const lacunarity = float( lacunarity_immutable ).toVar();
  33427. const diminish = float( diminish_immutable ).toVar();
  33428. // Compute input position
  33429. const p = position.mul( freq ).add( offset );
  33430. const result = float( 0.0 ).toVar();
  33431. // Perlin
  33432. If( noiseType.equal( int( 0 ) ), () => {
  33433. result.assign( mx_perlin_noise_vec3( p ) );
  33434. } );
  33435. // Cell
  33436. If( noiseType.equal( int( 1 ) ), () => {
  33437. result.assign( mx_cell_noise_vec3( p ) );
  33438. } );
  33439. // Worley (metric=0 = euclidean)
  33440. If( noiseType.equal( int( 2 ) ), () => {
  33441. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33442. } );
  33443. // Fractal
  33444. If( noiseType.equal( int( 3 ) ), () => {
  33445. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  33446. } );
  33447. // Remap output to [outmin, outmax]
  33448. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33449. // Clamp if requested
  33450. If( clampoutput, () => {
  33451. result.assign( clamp( result, outmin, outmax ) );
  33452. } );
  33453. return result;
  33454. } ).setLayout( {
  33455. name: 'mx_unifiednoise3d',
  33456. type: 'float',
  33457. inputs: [
  33458. { name: 'noiseType', type: 'int' },
  33459. { name: 'position', type: 'vec3' },
  33460. { name: 'freq', type: 'vec3' },
  33461. { name: 'offset', type: 'vec3' },
  33462. { name: 'jitter', type: 'float' },
  33463. { name: 'outmin', type: 'float' },
  33464. { name: 'outmax', type: 'float' },
  33465. { name: 'clampoutput', type: 'bool' },
  33466. { name: 'octaves', type: 'int' },
  33467. { name: 'lacunarity', type: 'float' },
  33468. { name: 'diminish', type: 'float' }
  33469. ]
  33470. } );
  33471. // Three.js Transpiler
  33472. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  33473. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  33474. const s = hsv.y;
  33475. const v = hsv.z;
  33476. const result = vec3().toVar();
  33477. If( s.lessThan( 0.0001 ), () => {
  33478. result.assign( vec3( v, v, v ) );
  33479. } ).Else( () => {
  33480. let h = hsv.x;
  33481. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  33482. const hi = int( trunc( h ) );
  33483. const f = h.sub( float( hi ) );
  33484. const p = v.mul( s.oneMinus() );
  33485. const q = v.mul( s.mul( f ).oneMinus() );
  33486. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  33487. If( hi.equal( int( 0 ) ), () => {
  33488. result.assign( vec3( v, t, p ) );
  33489. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  33490. result.assign( vec3( q, v, p ) );
  33491. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  33492. result.assign( vec3( p, v, t ) );
  33493. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  33494. result.assign( vec3( p, q, v ) );
  33495. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  33496. result.assign( vec3( t, p, v ) );
  33497. } ).Else( () => {
  33498. result.assign( vec3( v, p, q ) );
  33499. } );
  33500. } );
  33501. return result;
  33502. } ).setLayout( {
  33503. name: 'mx_hsvtorgb',
  33504. type: 'vec3',
  33505. inputs: [
  33506. { name: 'hsv', type: 'vec3' }
  33507. ]
  33508. } );
  33509. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  33510. const c = vec3( c_immutable ).toVar();
  33511. const r = float( c.x ).toVar();
  33512. const g = float( c.y ).toVar();
  33513. const b = float( c.z ).toVar();
  33514. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  33515. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  33516. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  33517. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  33518. v.assign( maxcomp );
  33519. If( maxcomp.greaterThan( 0.0 ), () => {
  33520. s.assign( delta.div( maxcomp ) );
  33521. } ).Else( () => {
  33522. s.assign( 0.0 );
  33523. } );
  33524. If( s.lessThanEqual( 0.0 ), () => {
  33525. h.assign( 0.0 );
  33526. } ).Else( () => {
  33527. If( r.greaterThanEqual( maxcomp ), () => {
  33528. h.assign( g.sub( b ).div( delta ) );
  33529. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  33530. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  33531. } ).Else( () => {
  33532. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  33533. } );
  33534. h.mulAssign( 1.0 / 6.0 );
  33535. If( h.lessThan( 0.0 ), () => {
  33536. h.addAssign( 1.0 );
  33537. } );
  33538. } );
  33539. return vec3( h, s, v );
  33540. } ).setLayout( {
  33541. name: 'mx_rgbtohsv',
  33542. type: 'vec3',
  33543. inputs: [
  33544. { name: 'c', type: 'vec3' }
  33545. ]
  33546. } );
  33547. // Three.js Transpiler
  33548. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  33549. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  33550. const color = vec3( color_immutable ).toVar();
  33551. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  33552. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  33553. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  33554. return mix( linSeg, powSeg, isAbove );
  33555. } ).setLayout( {
  33556. name: 'mx_srgb_texture_to_lin_rec709',
  33557. type: 'vec3',
  33558. inputs: [
  33559. { name: 'color', type: 'vec3' }
  33560. ]
  33561. } );
  33562. const mx_aastep = ( threshold, value ) => {
  33563. threshold = float( threshold );
  33564. value = float( value );
  33565. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  33566. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  33567. };
  33568. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  33569. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  33570. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  33571. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  33572. const mx_ramp4 = (
  33573. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  33574. ) => {
  33575. const u = texcoord.x.clamp();
  33576. const v = texcoord.y.clamp();
  33577. const top = mix( valuetl, valuetr, u );
  33578. const bottom = mix( valuebl, valuebr, u );
  33579. return mix( top, bottom, v );
  33580. };
  33581. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  33582. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  33583. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  33584. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  33585. const mx_safepower = ( in1, in2 = 1 ) => {
  33586. in1 = float( in1 );
  33587. return in1.abs().pow( in2 ).mul( in1.sign() );
  33588. };
  33589. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  33590. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33591. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33592. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33593. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  33594. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  33595. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  33596. return noise_vec4.mul( amplitude ).add( pivot );
  33597. };
  33598. const mx_unifiednoise2d = ( noiseType, texcoord = uv$1(), freq = vec2( 1, 1 ), offset = vec2( 0, 0 ), jitter = 1, outmin = 0, outmax = 1, clampoutput = false, octaves = 1, lacunarity = 2, diminish = .5 ) => mx_unifiednoise2d$1( noiseType, texcoord.convert( 'vec2|vec3' ), freq, offset, jitter, outmin, outmax, clampoutput, octaves, lacunarity, diminish );
  33599. const mx_unifiednoise3d = ( noiseType, texcoord = uv$1(), freq = vec2( 1, 1 ), offset = vec2( 0, 0 ), jitter = 1, outmin = 0, outmax = 1, clampoutput = false, octaves = 1, lacunarity = 2, diminish = .5 ) => mx_unifiednoise3d$1( noiseType, texcoord.convert( 'vec2|vec3' ), freq, offset, jitter, outmin, outmax, clampoutput, octaves, lacunarity, diminish );
  33600. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33601. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33602. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33603. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  33604. const mx_fractal_noise_float = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  33605. const mx_fractal_noise_vec2 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  33606. const mx_fractal_noise_vec3 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  33607. const mx_fractal_noise_vec4 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  33608. // === Moved from MaterialXLoader.js ===
  33609. // Math ops
  33610. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  33611. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  33612. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  33613. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  33614. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  33615. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  33616. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  33617. const mx_timer = () => time;
  33618. const mx_frame = () => frameId;
  33619. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  33620. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  33621. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  33622. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  33623. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  33624. const mx_separate = ( in1, channelOrOut = null ) => {
  33625. if ( typeof channelOrOut === 'string' ) {
  33626. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33627. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  33628. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  33629. }
  33630. if ( typeof channelOrOut === 'number' ) {
  33631. return in1.element( channelOrOut );
  33632. }
  33633. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  33634. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33635. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  33636. }
  33637. return in1;
  33638. };
  33639. const mx_place2d = (
  33640. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  33641. ) => {
  33642. let uv = texcoord;
  33643. if ( pivot ) uv = uv.sub( pivot );
  33644. if ( scale ) uv = uv.mul( scale );
  33645. if ( rotate ) {
  33646. const rad = rotate.mul( Math.PI / 180.0 );
  33647. const cosR = rad.cos();
  33648. const sinR = rad.sin();
  33649. uv = vec2(
  33650. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  33651. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  33652. );
  33653. }
  33654. if ( pivot ) uv = uv.add( pivot );
  33655. if ( offset ) uv = uv.add( offset );
  33656. return uv;
  33657. };
  33658. const mx_rotate2d = ( input, amount ) => {
  33659. input = vec2( input );
  33660. amount = float( amount );
  33661. const radians = amount.mul( Math.PI / 180.0 );
  33662. return rotate( input, radians );
  33663. };
  33664. const mx_rotate3d = ( input, amount, axis ) => {
  33665. input = vec3( input );
  33666. amount = float( amount );
  33667. axis = vec3( axis );
  33668. const radians = amount.mul( Math.PI / 180.0 );
  33669. const nAxis = axis.normalize();
  33670. const cosA = radians.cos();
  33671. const sinA = radians.sin();
  33672. const oneMinusCosA = float( 1 ).sub( cosA );
  33673. const rot =
  33674. input.mul( cosA )
  33675. .add( nAxis.cross( input ).mul( sinA ) )
  33676. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  33677. return rot;
  33678. };
  33679. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  33680. input = vec3( input );
  33681. scale = float( scale );
  33682. return bumpMap( input, scale );
  33683. };
  33684. /**
  33685. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  33686. *
  33687. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  33688. *
  33689. * ```js
  33690. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  33691. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  33692. * ```
  33693. *
  33694. * @tsl
  33695. * @function
  33696. * @param {Node<vec3>} normal - The normal to correct.
  33697. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  33698. * @param {Node<vec3>} cubePos - The cube position.
  33699. * @return {Node<vec3>} The parallax corrected normal.
  33700. */
  33701. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  33702. const nDir = normalize( normal ).toVar();
  33703. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33704. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33705. const rbminmax = vec3().toVar();
  33706. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  33707. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  33708. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  33709. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  33710. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  33711. return boxIntersection.sub( cubePos );
  33712. } );
  33713. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  33714. // normal is assumed to have unit length
  33715. const x = normal.x, y = normal.y, z = normal.z;
  33716. // band 0
  33717. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  33718. // band 1
  33719. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  33720. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  33721. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  33722. // band 2
  33723. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  33724. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  33725. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  33726. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  33727. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  33728. return result;
  33729. } );
  33730. // constants
  33731. var TSL = /*#__PURE__*/Object.freeze({
  33732. __proto__: null,
  33733. BRDF_GGX: BRDF_GGX,
  33734. BRDF_Lambert: BRDF_Lambert,
  33735. BasicPointShadowFilter: BasicPointShadowFilter,
  33736. BasicShadowFilter: BasicShadowFilter,
  33737. Break: Break,
  33738. Const: Const,
  33739. Continue: Continue,
  33740. DFGLUT: DFGLUT,
  33741. D_GGX: D_GGX,
  33742. Discard: Discard,
  33743. EPSILON: EPSILON,
  33744. F_Schlick: F_Schlick,
  33745. Fn: Fn,
  33746. HALF_PI: HALF_PI,
  33747. INFINITY: INFINITY,
  33748. If: If,
  33749. Loop: Loop,
  33750. NodeAccess: NodeAccess,
  33751. NodeShaderStage: NodeShaderStage,
  33752. NodeType: NodeType,
  33753. NodeUpdateType: NodeUpdateType,
  33754. OnBeforeMaterialUpdate: OnBeforeMaterialUpdate,
  33755. OnBeforeObjectUpdate: OnBeforeObjectUpdate,
  33756. OnMaterialUpdate: OnMaterialUpdate,
  33757. OnObjectUpdate: OnObjectUpdate,
  33758. PCFShadowFilter: PCFShadowFilter,
  33759. PCFSoftShadowFilter: PCFSoftShadowFilter,
  33760. PI: PI,
  33761. PI2: PI2,
  33762. PointShadowFilter: PointShadowFilter,
  33763. Return: Return,
  33764. Schlick_to_F0: Schlick_to_F0,
  33765. ShaderNode: ShaderNode,
  33766. Stack: Stack,
  33767. Switch: Switch,
  33768. TBNViewMatrix: TBNViewMatrix,
  33769. TWO_PI: TWO_PI,
  33770. VSMShadowFilter: VSMShadowFilter,
  33771. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  33772. Var: Var,
  33773. VarIntent: VarIntent,
  33774. abs: abs,
  33775. acesFilmicToneMapping: acesFilmicToneMapping,
  33776. acos: acos,
  33777. acosh: acosh,
  33778. add: add,
  33779. addMethodChaining: addMethodChaining,
  33780. addNodeElement: addNodeElement,
  33781. agxToneMapping: agxToneMapping,
  33782. all: all,
  33783. alphaT: alphaT,
  33784. and: and,
  33785. anisotropy: anisotropy,
  33786. anisotropyB: anisotropyB,
  33787. anisotropyT: anisotropyT,
  33788. any: any,
  33789. append: append,
  33790. array: array,
  33791. arrayBuffer: arrayBuffer,
  33792. asin: asin,
  33793. asinh: asinh,
  33794. assign: assign,
  33795. atan: atan,
  33796. atanh: atanh,
  33797. atomicAdd: atomicAdd,
  33798. atomicAnd: atomicAnd,
  33799. atomicFunc: atomicFunc,
  33800. atomicLoad: atomicLoad,
  33801. atomicMax: atomicMax,
  33802. atomicMin: atomicMin,
  33803. atomicOr: atomicOr,
  33804. atomicStore: atomicStore,
  33805. atomicSub: atomicSub,
  33806. atomicXor: atomicXor,
  33807. attenuationColor: attenuationColor,
  33808. attenuationDistance: attenuationDistance,
  33809. attribute: attribute,
  33810. attributeArray: attributeArray,
  33811. backgroundBlurriness: backgroundBlurriness,
  33812. backgroundIntensity: backgroundIntensity,
  33813. backgroundRotation: backgroundRotation,
  33814. batch: batch,
  33815. bentNormalView: bentNormalView,
  33816. billboarding: billboarding,
  33817. bitAnd: bitAnd,
  33818. bitNot: bitNot,
  33819. bitOr: bitOr,
  33820. bitXor: bitXor,
  33821. bitangentGeometry: bitangentGeometry,
  33822. bitangentLocal: bitangentLocal,
  33823. bitangentView: bitangentView,
  33824. bitangentWorld: bitangentWorld,
  33825. bitcast: bitcast,
  33826. blendBurn: blendBurn,
  33827. blendColor: blendColor,
  33828. blendDodge: blendDodge,
  33829. blendOverlay: blendOverlay,
  33830. blendScreen: blendScreen,
  33831. blur: blur,
  33832. bool: bool,
  33833. buffer: buffer,
  33834. bufferAttribute: bufferAttribute,
  33835. builtin: builtin,
  33836. builtinAOContext: builtinAOContext,
  33837. builtinShadowContext: builtinShadowContext,
  33838. bumpMap: bumpMap,
  33839. bvec2: bvec2,
  33840. bvec3: bvec3,
  33841. bvec4: bvec4,
  33842. bypass: bypass,
  33843. cache: cache,
  33844. call: call,
  33845. cameraFar: cameraFar,
  33846. cameraIndex: cameraIndex,
  33847. cameraNear: cameraNear,
  33848. cameraNormalMatrix: cameraNormalMatrix,
  33849. cameraPosition: cameraPosition,
  33850. cameraProjectionMatrix: cameraProjectionMatrix,
  33851. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  33852. cameraViewMatrix: cameraViewMatrix,
  33853. cameraViewport: cameraViewport,
  33854. cameraWorldMatrix: cameraWorldMatrix,
  33855. cbrt: cbrt,
  33856. cdl: cdl,
  33857. ceil: ceil,
  33858. checker: checker,
  33859. cineonToneMapping: cineonToneMapping,
  33860. clamp: clamp,
  33861. clearcoat: clearcoat,
  33862. clearcoatNormalView: clearcoatNormalView,
  33863. clearcoatRoughness: clearcoatRoughness,
  33864. clipSpace: clipSpace,
  33865. code: code,
  33866. color: color,
  33867. colorSpaceToWorking: colorSpaceToWorking,
  33868. colorToDirection: colorToDirection,
  33869. compute: compute,
  33870. computeKernel: computeKernel,
  33871. computeSkinning: computeSkinning,
  33872. context: context,
  33873. convert: convert,
  33874. convertColorSpace: convertColorSpace,
  33875. convertToTexture: convertToTexture,
  33876. cos: cos,
  33877. cosh: cosh,
  33878. countLeadingZeros: countLeadingZeros,
  33879. countOneBits: countOneBits,
  33880. countTrailingZeros: countTrailingZeros,
  33881. cross: cross,
  33882. cubeTexture: cubeTexture,
  33883. cubeTextureBase: cubeTextureBase,
  33884. dFdx: dFdx,
  33885. dFdy: dFdy,
  33886. dashSize: dashSize,
  33887. debug: debug,
  33888. decrement: decrement,
  33889. decrementBefore: decrementBefore,
  33890. defaultBuildStages: defaultBuildStages,
  33891. defaultShaderStages: defaultShaderStages,
  33892. defined: defined,
  33893. degrees: degrees,
  33894. deltaTime: deltaTime,
  33895. densityFogFactor: densityFogFactor,
  33896. depth: depth,
  33897. depthPass: depthPass,
  33898. determinant: determinant,
  33899. difference: difference,
  33900. diffuseColor: diffuseColor,
  33901. diffuseContribution: diffuseContribution,
  33902. directPointLight: directPointLight,
  33903. directionToColor: directionToColor,
  33904. directionToFaceDirection: directionToFaceDirection,
  33905. dispersion: dispersion,
  33906. disposeShadowMaterial: disposeShadowMaterial,
  33907. distance: distance,
  33908. div: div,
  33909. dot: dot,
  33910. drawIndex: drawIndex,
  33911. dynamicBufferAttribute: dynamicBufferAttribute,
  33912. element: element,
  33913. emissive: emissive,
  33914. equal: equal,
  33915. equirectUV: equirectUV,
  33916. exp: exp,
  33917. exp2: exp2,
  33918. exponentialHeightFogFactor: exponentialHeightFogFactor,
  33919. expression: expression,
  33920. faceDirection: faceDirection,
  33921. faceForward: faceForward,
  33922. faceforward: faceforward,
  33923. float: float,
  33924. floatBitsToInt: floatBitsToInt,
  33925. floatBitsToUint: floatBitsToUint,
  33926. floor: floor,
  33927. fog: fog,
  33928. fract: fract,
  33929. frameGroup: frameGroup,
  33930. frameId: frameId,
  33931. frontFacing: frontFacing,
  33932. fwidth: fwidth,
  33933. gain: gain,
  33934. gapSize: gapSize,
  33935. getConstNodeType: getConstNodeType,
  33936. getCurrentStack: getCurrentStack,
  33937. getDirection: getDirection,
  33938. getDistanceAttenuation: getDistanceAttenuation,
  33939. getGeometryRoughness: getGeometryRoughness,
  33940. getNormalFromDepth: getNormalFromDepth,
  33941. getParallaxCorrectNormal: getParallaxCorrectNormal,
  33942. getRoughness: getRoughness,
  33943. getScreenPosition: getScreenPosition,
  33944. getShIrradianceAt: getShIrradianceAt,
  33945. getShadowMaterial: getShadowMaterial,
  33946. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  33947. getTextureIndex: getTextureIndex,
  33948. getViewPosition: getViewPosition,
  33949. ggxConvolution: ggxConvolution,
  33950. globalId: globalId,
  33951. glsl: glsl,
  33952. glslFn: glslFn,
  33953. grayscale: grayscale,
  33954. greaterThan: greaterThan,
  33955. greaterThanEqual: greaterThanEqual,
  33956. hash: hash,
  33957. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  33958. highpModelViewMatrix: highpModelViewMatrix,
  33959. hue: hue,
  33960. increment: increment,
  33961. incrementBefore: incrementBefore,
  33962. inspector: inspector,
  33963. instance: instance,
  33964. instanceIndex: instanceIndex,
  33965. instancedArray: instancedArray,
  33966. instancedBufferAttribute: instancedBufferAttribute,
  33967. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  33968. instancedMesh: instancedMesh,
  33969. int: int,
  33970. intBitsToFloat: intBitsToFloat,
  33971. interleavedGradientNoise: interleavedGradientNoise,
  33972. inverse: inverse,
  33973. inverseSqrt: inverseSqrt,
  33974. inversesqrt: inversesqrt,
  33975. invocationLocalIndex: invocationLocalIndex,
  33976. invocationSubgroupIndex: invocationSubgroupIndex,
  33977. ior: ior,
  33978. iridescence: iridescence,
  33979. iridescenceIOR: iridescenceIOR,
  33980. iridescenceThickness: iridescenceThickness,
  33981. isolate: isolate,
  33982. ivec2: ivec2,
  33983. ivec3: ivec3,
  33984. ivec4: ivec4,
  33985. js: js,
  33986. label: label,
  33987. length: length,
  33988. lengthSq: lengthSq,
  33989. lessThan: lessThan,
  33990. lessThanEqual: lessThanEqual,
  33991. lightPosition: lightPosition,
  33992. lightProjectionUV: lightProjectionUV,
  33993. lightShadowMatrix: lightShadowMatrix,
  33994. lightTargetDirection: lightTargetDirection,
  33995. lightTargetPosition: lightTargetPosition,
  33996. lightViewPosition: lightViewPosition,
  33997. lightingContext: lightingContext,
  33998. lights: lights,
  33999. linearDepth: linearDepth,
  34000. linearToneMapping: linearToneMapping,
  34001. localId: localId,
  34002. log: log,
  34003. log2: log2,
  34004. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  34005. luminance: luminance,
  34006. mat2: mat2,
  34007. mat3: mat3,
  34008. mat4: mat4,
  34009. matcapUV: matcapUV,
  34010. materialAO: materialAO,
  34011. materialAlphaTest: materialAlphaTest,
  34012. materialAnisotropy: materialAnisotropy,
  34013. materialAnisotropyVector: materialAnisotropyVector,
  34014. materialAttenuationColor: materialAttenuationColor,
  34015. materialAttenuationDistance: materialAttenuationDistance,
  34016. materialClearcoat: materialClearcoat,
  34017. materialClearcoatNormal: materialClearcoatNormal,
  34018. materialClearcoatRoughness: materialClearcoatRoughness,
  34019. materialColor: materialColor,
  34020. materialDispersion: materialDispersion,
  34021. materialEmissive: materialEmissive,
  34022. materialEnvIntensity: materialEnvIntensity,
  34023. materialEnvRotation: materialEnvRotation,
  34024. materialIOR: materialIOR,
  34025. materialIridescence: materialIridescence,
  34026. materialIridescenceIOR: materialIridescenceIOR,
  34027. materialIridescenceThickness: materialIridescenceThickness,
  34028. materialLightMap: materialLightMap,
  34029. materialLineDashOffset: materialLineDashOffset,
  34030. materialLineDashSize: materialLineDashSize,
  34031. materialLineGapSize: materialLineGapSize,
  34032. materialLineScale: materialLineScale,
  34033. materialLineWidth: materialLineWidth,
  34034. materialMetalness: materialMetalness,
  34035. materialNormal: materialNormal,
  34036. materialOpacity: materialOpacity,
  34037. materialPointSize: materialPointSize,
  34038. materialReference: materialReference,
  34039. materialReflectivity: materialReflectivity,
  34040. materialRefractionRatio: materialRefractionRatio,
  34041. materialRotation: materialRotation,
  34042. materialRoughness: materialRoughness,
  34043. materialSheen: materialSheen,
  34044. materialSheenRoughness: materialSheenRoughness,
  34045. materialShininess: materialShininess,
  34046. materialSpecular: materialSpecular,
  34047. materialSpecularColor: materialSpecularColor,
  34048. materialSpecularIntensity: materialSpecularIntensity,
  34049. materialSpecularStrength: materialSpecularStrength,
  34050. materialThickness: materialThickness,
  34051. materialTransmission: materialTransmission,
  34052. max: max$1,
  34053. maxMipLevel: maxMipLevel,
  34054. mediumpModelViewMatrix: mediumpModelViewMatrix,
  34055. metalness: metalness,
  34056. min: min$1,
  34057. mix: mix,
  34058. mixElement: mixElement,
  34059. mod: mod,
  34060. modInt: modInt,
  34061. modelDirection: modelDirection,
  34062. modelNormalMatrix: modelNormalMatrix,
  34063. modelPosition: modelPosition,
  34064. modelRadius: modelRadius,
  34065. modelScale: modelScale,
  34066. modelViewMatrix: modelViewMatrix,
  34067. modelViewPosition: modelViewPosition,
  34068. modelViewProjection: modelViewProjection,
  34069. modelWorldMatrix: modelWorldMatrix,
  34070. modelWorldMatrixInverse: modelWorldMatrixInverse,
  34071. morphReference: morphReference,
  34072. mrt: mrt,
  34073. mul: mul,
  34074. mx_aastep: mx_aastep,
  34075. mx_add: mx_add,
  34076. mx_atan2: mx_atan2,
  34077. mx_cell_noise_float: mx_cell_noise_float,
  34078. mx_contrast: mx_contrast,
  34079. mx_divide: mx_divide,
  34080. mx_fractal_noise_float: mx_fractal_noise_float,
  34081. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  34082. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  34083. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  34084. mx_frame: mx_frame,
  34085. mx_heighttonormal: mx_heighttonormal,
  34086. mx_hsvtorgb: mx_hsvtorgb,
  34087. mx_ifequal: mx_ifequal,
  34088. mx_ifgreater: mx_ifgreater,
  34089. mx_ifgreatereq: mx_ifgreatereq,
  34090. mx_invert: mx_invert,
  34091. mx_modulo: mx_modulo,
  34092. mx_multiply: mx_multiply,
  34093. mx_noise_float: mx_noise_float,
  34094. mx_noise_vec3: mx_noise_vec3,
  34095. mx_noise_vec4: mx_noise_vec4,
  34096. mx_place2d: mx_place2d,
  34097. mx_power: mx_power,
  34098. mx_ramp4: mx_ramp4,
  34099. mx_ramplr: mx_ramplr,
  34100. mx_ramptb: mx_ramptb,
  34101. mx_rgbtohsv: mx_rgbtohsv,
  34102. mx_rotate2d: mx_rotate2d,
  34103. mx_rotate3d: mx_rotate3d,
  34104. mx_safepower: mx_safepower,
  34105. mx_separate: mx_separate,
  34106. mx_splitlr: mx_splitlr,
  34107. mx_splittb: mx_splittb,
  34108. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  34109. mx_subtract: mx_subtract,
  34110. mx_timer: mx_timer,
  34111. mx_transform_uv: mx_transform_uv,
  34112. mx_unifiednoise2d: mx_unifiednoise2d,
  34113. mx_unifiednoise3d: mx_unifiednoise3d,
  34114. mx_worley_noise_float: mx_worley_noise_float,
  34115. mx_worley_noise_vec2: mx_worley_noise_vec2,
  34116. mx_worley_noise_vec3: mx_worley_noise_vec3,
  34117. negate: negate,
  34118. neutralToneMapping: neutralToneMapping,
  34119. nodeArray: nodeArray,
  34120. nodeImmutable: nodeImmutable,
  34121. nodeObject: nodeObject,
  34122. nodeObjectIntent: nodeObjectIntent,
  34123. nodeObjects: nodeObjects,
  34124. nodeProxy: nodeProxy,
  34125. nodeProxyIntent: nodeProxyIntent,
  34126. normalFlat: normalFlat,
  34127. normalGeometry: normalGeometry,
  34128. normalLocal: normalLocal,
  34129. normalMap: normalMap,
  34130. normalView: normalView,
  34131. normalViewGeometry: normalViewGeometry,
  34132. normalWorld: normalWorld,
  34133. normalWorldGeometry: normalWorldGeometry,
  34134. normalize: normalize,
  34135. not: not,
  34136. notEqual: notEqual,
  34137. numWorkgroups: numWorkgroups,
  34138. objectDirection: objectDirection,
  34139. objectGroup: objectGroup,
  34140. objectPosition: objectPosition,
  34141. objectRadius: objectRadius,
  34142. objectScale: objectScale,
  34143. objectViewPosition: objectViewPosition,
  34144. objectWorldMatrix: objectWorldMatrix,
  34145. oneMinus: oneMinus,
  34146. or: or,
  34147. orthographicDepthToViewZ: orthographicDepthToViewZ,
  34148. oscSawtooth: oscSawtooth,
  34149. oscSine: oscSine,
  34150. oscSquare: oscSquare,
  34151. oscTriangle: oscTriangle,
  34152. output: output,
  34153. outputStruct: outputStruct,
  34154. overloadingFn: overloadingFn,
  34155. packHalf2x16: packHalf2x16,
  34156. packSnorm2x16: packSnorm2x16,
  34157. packUnorm2x16: packUnorm2x16,
  34158. parabola: parabola,
  34159. parallaxDirection: parallaxDirection,
  34160. parallaxUV: parallaxUV,
  34161. parameter: parameter,
  34162. pass: pass,
  34163. passTexture: passTexture,
  34164. pcurve: pcurve,
  34165. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  34166. pmremTexture: pmremTexture,
  34167. pointShadow: pointShadow,
  34168. pointUV: pointUV,
  34169. pointWidth: pointWidth,
  34170. positionGeometry: positionGeometry,
  34171. positionLocal: positionLocal,
  34172. positionPrevious: positionPrevious,
  34173. positionView: positionView,
  34174. positionViewDirection: positionViewDirection,
  34175. positionWorld: positionWorld,
  34176. positionWorldDirection: positionWorldDirection,
  34177. posterize: posterize,
  34178. pow: pow,
  34179. pow2: pow2,
  34180. pow3: pow3,
  34181. pow4: pow4,
  34182. premultiplyAlpha: premultiplyAlpha,
  34183. property: property,
  34184. quadBroadcast: quadBroadcast,
  34185. quadSwapDiagonal: quadSwapDiagonal,
  34186. quadSwapX: quadSwapX,
  34187. quadSwapY: quadSwapY,
  34188. radians: radians,
  34189. rand: rand,
  34190. range: range,
  34191. rangeFogFactor: rangeFogFactor,
  34192. reciprocal: reciprocal,
  34193. reference: reference,
  34194. referenceBuffer: referenceBuffer,
  34195. reflect: reflect,
  34196. reflectVector: reflectVector,
  34197. reflectView: reflectView,
  34198. reflector: reflector,
  34199. refract: refract,
  34200. refractVector: refractVector,
  34201. refractView: refractView,
  34202. reinhardToneMapping: reinhardToneMapping,
  34203. remap: remap,
  34204. remapClamp: remapClamp,
  34205. renderGroup: renderGroup,
  34206. renderOutput: renderOutput,
  34207. rendererReference: rendererReference,
  34208. replaceDefaultUV: replaceDefaultUV,
  34209. rotate: rotate,
  34210. rotateUV: rotateUV,
  34211. roughness: roughness,
  34212. round: round,
  34213. rtt: rtt,
  34214. sRGBTransferEOTF: sRGBTransferEOTF,
  34215. sRGBTransferOETF: sRGBTransferOETF,
  34216. sample: sample,
  34217. sampler: sampler,
  34218. samplerComparison: samplerComparison,
  34219. saturate: saturate,
  34220. saturation: saturation,
  34221. screenCoordinate: screenCoordinate,
  34222. screenDPR: screenDPR,
  34223. screenSize: screenSize,
  34224. screenUV: screenUV,
  34225. select: select,
  34226. setCurrentStack: setCurrentStack,
  34227. setName: setName,
  34228. shaderStages: shaderStages,
  34229. shadow: shadow,
  34230. shadowPositionWorld: shadowPositionWorld,
  34231. shapeCircle: shapeCircle,
  34232. sharedUniformGroup: sharedUniformGroup,
  34233. sheen: sheen,
  34234. sheenRoughness: sheenRoughness,
  34235. shiftLeft: shiftLeft,
  34236. shiftRight: shiftRight,
  34237. shininess: shininess,
  34238. sign: sign,
  34239. sin: sin,
  34240. sinc: sinc,
  34241. sinh: sinh,
  34242. skinning: skinning,
  34243. smoothstep: smoothstep,
  34244. smoothstepElement: smoothstepElement,
  34245. specularColor: specularColor,
  34246. specularColorBlended: specularColorBlended,
  34247. specularF90: specularF90,
  34248. spherizeUV: spherizeUV,
  34249. split: split,
  34250. spritesheetUV: spritesheetUV,
  34251. sqrt: sqrt,
  34252. stack: stack,
  34253. step: step,
  34254. stepElement: stepElement,
  34255. storage: storage,
  34256. storageBarrier: storageBarrier,
  34257. storageTexture: storageTexture,
  34258. string: string,
  34259. struct: struct,
  34260. sub: sub,
  34261. subBuild: subBuild,
  34262. subgroupAdd: subgroupAdd,
  34263. subgroupAll: subgroupAll,
  34264. subgroupAnd: subgroupAnd,
  34265. subgroupAny: subgroupAny,
  34266. subgroupBallot: subgroupBallot,
  34267. subgroupBroadcast: subgroupBroadcast,
  34268. subgroupBroadcastFirst: subgroupBroadcastFirst,
  34269. subgroupElect: subgroupElect,
  34270. subgroupExclusiveAdd: subgroupExclusiveAdd,
  34271. subgroupExclusiveMul: subgroupExclusiveMul,
  34272. subgroupInclusiveAdd: subgroupInclusiveAdd,
  34273. subgroupInclusiveMul: subgroupInclusiveMul,
  34274. subgroupIndex: subgroupIndex,
  34275. subgroupMax: subgroupMax,
  34276. subgroupMin: subgroupMin,
  34277. subgroupMul: subgroupMul,
  34278. subgroupOr: subgroupOr,
  34279. subgroupShuffle: subgroupShuffle,
  34280. subgroupShuffleDown: subgroupShuffleDown,
  34281. subgroupShuffleUp: subgroupShuffleUp,
  34282. subgroupShuffleXor: subgroupShuffleXor,
  34283. subgroupSize: subgroupSize,
  34284. subgroupXor: subgroupXor,
  34285. tan: tan,
  34286. tangentGeometry: tangentGeometry,
  34287. tangentLocal: tangentLocal,
  34288. tangentView: tangentView,
  34289. tangentWorld: tangentWorld,
  34290. tanh: tanh,
  34291. texture: texture,
  34292. texture3D: texture3D,
  34293. texture3DLevel: texture3DLevel,
  34294. texture3DLoad: texture3DLoad,
  34295. textureBarrier: textureBarrier,
  34296. textureBicubic: textureBicubic,
  34297. textureBicubicLevel: textureBicubicLevel,
  34298. textureCubeUV: textureCubeUV,
  34299. textureLevel: textureLevel,
  34300. textureLoad: textureLoad,
  34301. textureSize: textureSize,
  34302. textureStore: textureStore,
  34303. thickness: thickness,
  34304. time: time,
  34305. toneMapping: toneMapping,
  34306. toneMappingExposure: toneMappingExposure,
  34307. toonOutlinePass: toonOutlinePass,
  34308. transformDirection: transformDirection,
  34309. transformNormal: transformNormal,
  34310. transformNormalToView: transformNormalToView,
  34311. transformedClearcoatNormalView: transformedClearcoatNormalView,
  34312. transformedNormalView: transformedNormalView,
  34313. transformedNormalWorld: transformedNormalWorld,
  34314. transmission: transmission,
  34315. transpose: transpose,
  34316. triNoise3D: triNoise3D,
  34317. triplanarTexture: triplanarTexture,
  34318. triplanarTextures: triplanarTextures,
  34319. trunc: trunc,
  34320. uint: uint,
  34321. uintBitsToFloat: uintBitsToFloat,
  34322. uniform: uniform,
  34323. uniformArray: uniformArray,
  34324. uniformCubeTexture: uniformCubeTexture,
  34325. uniformFlow: uniformFlow,
  34326. uniformGroup: uniformGroup,
  34327. uniformTexture: uniformTexture,
  34328. unpackHalf2x16: unpackHalf2x16,
  34329. unpackNormal: unpackNormal,
  34330. unpackSnorm2x16: unpackSnorm2x16,
  34331. unpackUnorm2x16: unpackUnorm2x16,
  34332. unpremultiplyAlpha: unpremultiplyAlpha,
  34333. userData: userData,
  34334. uv: uv$1,
  34335. uvec2: uvec2,
  34336. uvec3: uvec3,
  34337. uvec4: uvec4,
  34338. varying: varying,
  34339. varyingProperty: varyingProperty,
  34340. vec2: vec2,
  34341. vec3: vec3,
  34342. vec4: vec4,
  34343. vectorComponents: vectorComponents,
  34344. velocity: velocity,
  34345. vertexColor: vertexColor,
  34346. vertexIndex: vertexIndex,
  34347. vertexStage: vertexStage,
  34348. vibrance: vibrance,
  34349. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  34350. viewZToOrthographicDepth: viewZToOrthographicDepth,
  34351. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  34352. viewZToReversedOrthographicDepth: viewZToReversedOrthographicDepth,
  34353. viewZToReversedPerspectiveDepth: viewZToReversedPerspectiveDepth,
  34354. viewport: viewport,
  34355. viewportCoordinate: viewportCoordinate,
  34356. viewportDepthTexture: viewportDepthTexture,
  34357. viewportLinearDepth: viewportLinearDepth,
  34358. viewportMipTexture: viewportMipTexture,
  34359. viewportOpaqueMipTexture: viewportOpaqueMipTexture,
  34360. viewportResolution: viewportResolution,
  34361. viewportSafeUV: viewportSafeUV,
  34362. viewportSharedTexture: viewportSharedTexture,
  34363. viewportSize: viewportSize,
  34364. viewportTexture: viewportTexture,
  34365. viewportUV: viewportUV,
  34366. vogelDiskSample: vogelDiskSample,
  34367. wgsl: wgsl,
  34368. wgslFn: wgslFn,
  34369. workgroupArray: workgroupArray,
  34370. workgroupBarrier: workgroupBarrier,
  34371. workgroupId: workgroupId,
  34372. workingToColorSpace: workingToColorSpace,
  34373. xor: xor
  34374. });
  34375. const _clearColor = /*@__PURE__*/ new Color4();
  34376. /**
  34377. * This renderer module manages the background.
  34378. *
  34379. * @private
  34380. * @augments DataMap
  34381. */
  34382. class Background extends DataMap {
  34383. /**
  34384. * Constructs a new background management component.
  34385. *
  34386. * @param {Renderer} renderer - The renderer.
  34387. * @param {NodeManager} nodes - Renderer component for managing nodes related logic.
  34388. */
  34389. constructor( renderer, nodes ) {
  34390. super();
  34391. /**
  34392. * The renderer.
  34393. *
  34394. * @type {Renderer}
  34395. */
  34396. this.renderer = renderer;
  34397. /**
  34398. * Renderer component for managing nodes related logic.
  34399. *
  34400. * @type {NodeManager}
  34401. */
  34402. this.nodes = nodes;
  34403. }
  34404. /**
  34405. * Updates the background for the given scene. Depending on how `Scene.background`
  34406. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  34407. * or add a mesh to the render list for rendering the background as a textured plane
  34408. * or skybox.
  34409. *
  34410. * @param {Scene} scene - The scene.
  34411. * @param {RenderList} renderList - The current render list.
  34412. * @param {RenderContext} renderContext - The current render context.
  34413. */
  34414. update( scene, renderList, renderContext ) {
  34415. const renderer = this.renderer;
  34416. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  34417. let forceClear = false;
  34418. if ( background === null ) {
  34419. // no background settings, use clear color configuration from the renderer
  34420. renderer._clearColor.getRGB( _clearColor );
  34421. _clearColor.a = renderer._clearColor.a;
  34422. } else if ( background.isColor === true ) {
  34423. // background is an opaque color
  34424. background.getRGB( _clearColor );
  34425. _clearColor.a = 1;
  34426. forceClear = true;
  34427. } else if ( background.isNode === true ) {
  34428. const sceneData = this.get( scene );
  34429. const backgroundNode = background;
  34430. _clearColor.copy( renderer._clearColor );
  34431. let backgroundMesh = sceneData.backgroundMesh;
  34432. if ( backgroundMesh === undefined ) {
  34433. const backgroundMeshNode = vec4( backgroundNode ).mul( backgroundIntensity ).context( {
  34434. // @TODO: Add Texture2D support using node context
  34435. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  34436. getTextureLevel: () => backgroundBlurriness
  34437. } );
  34438. // when using orthographic cameras, we must scale the skybox sphere
  34439. // up to exceed the dimensions of the camera's viewing box.
  34440. const isOrtho = cameraProjectionMatrix.element( 3 ).element( 3 ).equal( 1.0 );
  34441. // calculate the orthographic scale
  34442. // projectionMatrix[1][1] is (1 / top). Invert it to get the height and multiply by 3.0
  34443. // (an arbitrary safety factor) to ensure the skybox is large enough to cover the corners
  34444. // of the rectangular screen
  34445. const orthoScale = div( 1.0, cameraProjectionMatrix.element( 1 ).element( 1 ) ).mul( 3.0 );
  34446. // compute vertex position
  34447. const modifiedPosition = isOrtho.select( positionLocal.mul( orthoScale ), positionLocal );
  34448. // by using a w component of 0, the skybox will not translate when the camera moves through the scene
  34449. const viewPosition = modelViewMatrix.mul( vec4( modifiedPosition, 0.0 ) );
  34450. // we force w=1.0 here to prevent the w_clip=0 divide-by-zero error for ortho cameras.
  34451. let viewProj = cameraProjectionMatrix.mul( vec4( viewPosition.xyz, 1.0 ) );
  34452. // force background to far plane so it does not occlude objects
  34453. viewProj = viewProj.setZ( viewProj.w );
  34454. const nodeMaterial = new NodeMaterial();
  34455. nodeMaterial.name = 'Background.material';
  34456. nodeMaterial.side = BackSide;
  34457. nodeMaterial.depthTest = false;
  34458. nodeMaterial.depthWrite = false;
  34459. nodeMaterial.allowOverride = false;
  34460. nodeMaterial.fog = false;
  34461. nodeMaterial.lights = false;
  34462. nodeMaterial.vertexNode = viewProj;
  34463. nodeMaterial.colorNode = backgroundMeshNode;
  34464. sceneData.backgroundMeshNode = backgroundMeshNode;
  34465. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  34466. backgroundMesh.frustumCulled = false;
  34467. backgroundMesh.name = 'Background.mesh';
  34468. function onBackgroundDispose() {
  34469. background.removeEventListener( 'dispose', onBackgroundDispose );
  34470. backgroundMesh.material.dispose();
  34471. backgroundMesh.geometry.dispose();
  34472. }
  34473. background.addEventListener( 'dispose', onBackgroundDispose );
  34474. }
  34475. const backgroundCacheKey = backgroundNode.getCacheKey();
  34476. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  34477. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  34478. sceneData.backgroundMeshNode.needsUpdate = true;
  34479. backgroundMesh.material.needsUpdate = true;
  34480. sceneData.backgroundCacheKey = backgroundCacheKey;
  34481. }
  34482. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  34483. } else {
  34484. error( 'Renderer: Unsupported background configuration.', background );
  34485. }
  34486. //
  34487. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  34488. if ( environmentBlendMode === 'additive' ) {
  34489. _clearColor.set( 0, 0, 0, 1 );
  34490. } else if ( environmentBlendMode === 'alpha-blend' ) {
  34491. _clearColor.set( 0, 0, 0, 0 );
  34492. }
  34493. //
  34494. if ( renderer.autoClear === true || forceClear === true ) {
  34495. const clearColorValue = renderContext.clearColorValue;
  34496. clearColorValue.r = _clearColor.r;
  34497. clearColorValue.g = _clearColor.g;
  34498. clearColorValue.b = _clearColor.b;
  34499. clearColorValue.a = _clearColor.a;
  34500. // premultiply alpha
  34501. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  34502. clearColorValue.r *= clearColorValue.a;
  34503. clearColorValue.g *= clearColorValue.a;
  34504. clearColorValue.b *= clearColorValue.a;
  34505. }
  34506. //
  34507. renderContext.depthClearValue = renderer.getClearDepth();
  34508. renderContext.stencilClearValue = renderer.getClearStencil();
  34509. renderContext.clearColor = renderer.autoClearColor === true;
  34510. renderContext.clearDepth = renderer.autoClearDepth === true;
  34511. renderContext.clearStencil = renderer.autoClearStencil === true;
  34512. } else {
  34513. renderContext.clearColor = false;
  34514. renderContext.clearDepth = false;
  34515. renderContext.clearStencil = false;
  34516. }
  34517. }
  34518. }
  34519. let _id$7 = 0;
  34520. /**
  34521. * A bind group represents a collection of bindings and thus a collection
  34522. * or resources. Bind groups are assigned to pipelines to provide them
  34523. * with the required resources (like uniform buffers or textures).
  34524. *
  34525. * @private
  34526. */
  34527. class BindGroup {
  34528. /**
  34529. * Constructs a new bind group.
  34530. *
  34531. * @param {string} name - The bind group's name.
  34532. * @param {Array<Binding>} bindings - An array of bindings.
  34533. * @param {number} index - The group index.
  34534. */
  34535. constructor( name = '', bindings = [] ) {
  34536. /**
  34537. * The bind group's name.
  34538. *
  34539. * @type {string}
  34540. */
  34541. this.name = name;
  34542. /**
  34543. * An array of bindings.
  34544. *
  34545. * @type {Array<Binding>}
  34546. */
  34547. this.bindings = bindings;
  34548. /**
  34549. * The group's ID.
  34550. *
  34551. * @type {number}
  34552. */
  34553. this.id = _id$7 ++;
  34554. }
  34555. }
  34556. /**
  34557. * This module represents the state of a node builder after it was
  34558. * used to build the nodes for a render object. The state holds the
  34559. * results of the build for further processing in the renderer.
  34560. *
  34561. * Render objects with identical cache keys share the same node builder state.
  34562. *
  34563. * @private
  34564. */
  34565. class NodeBuilderState {
  34566. /**
  34567. * Constructs a new node builder state.
  34568. *
  34569. * @param {string} vertexShader - The native vertex shader code.
  34570. * @param {string} fragmentShader - The native fragment shader code.
  34571. * @param {string} computeShader - The native compute shader code.
  34572. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  34573. * @param {Array<BindGroup>} bindings - An array of bind groups.
  34574. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  34575. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  34576. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  34577. * @param {NodeMaterialObserver} observer - A node material observer.
  34578. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  34579. */
  34580. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  34581. /**
  34582. * The native vertex shader code.
  34583. *
  34584. * @type {string}
  34585. */
  34586. this.vertexShader = vertexShader;
  34587. /**
  34588. * The native fragment shader code.
  34589. *
  34590. * @type {string}
  34591. */
  34592. this.fragmentShader = fragmentShader;
  34593. /**
  34594. * The native compute shader code.
  34595. *
  34596. * @type {string}
  34597. */
  34598. this.computeShader = computeShader;
  34599. /**
  34600. * An array with transform attribute objects.
  34601. * Only relevant when using compute shaders with WebGL 2.
  34602. *
  34603. * @type {Array<Object>}
  34604. */
  34605. this.transforms = transforms;
  34606. /**
  34607. * An array of node attributes representing
  34608. * the attributes of the shaders.
  34609. *
  34610. * @type {Array<NodeAttribute>}
  34611. */
  34612. this.nodeAttributes = nodeAttributes;
  34613. /**
  34614. * An array of bind groups representing the uniform or storage
  34615. * buffers, texture or samplers of the shader.
  34616. *
  34617. * @type {Array<BindGroup>}
  34618. */
  34619. this.bindings = bindings;
  34620. /**
  34621. * An array of nodes that implement their `update()` method.
  34622. *
  34623. * @type {Array<Node>}
  34624. */
  34625. this.updateNodes = updateNodes;
  34626. /**
  34627. * An array of nodes that implement their `updateBefore()` method.
  34628. *
  34629. * @type {Array<Node>}
  34630. */
  34631. this.updateBeforeNodes = updateBeforeNodes;
  34632. /**
  34633. * An array of nodes that implement their `updateAfter()` method.
  34634. *
  34635. * @type {Array<Node>}
  34636. */
  34637. this.updateAfterNodes = updateAfterNodes;
  34638. /**
  34639. * A node material observer.
  34640. *
  34641. * @type {NodeMaterialObserver}
  34642. */
  34643. this.observer = observer;
  34644. /**
  34645. * How often this state is used by render objects.
  34646. *
  34647. * @type {number}
  34648. */
  34649. this.usedTimes = 0;
  34650. }
  34651. /**
  34652. * This method is used to create a array of bind groups based
  34653. * on the existing bind groups of this state. Shared groups are
  34654. * not cloned.
  34655. *
  34656. * @return {Array<BindGroup>} A array of bind groups.
  34657. */
  34658. createBindings() {
  34659. const bindings = [];
  34660. for ( const instanceGroup of this.bindings ) {
  34661. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  34662. if ( shared !== true ) {
  34663. const bindingsGroup = new BindGroup( instanceGroup.name, [] );
  34664. bindings.push( bindingsGroup );
  34665. for ( const instanceBinding of instanceGroup.bindings ) {
  34666. bindingsGroup.bindings.push( instanceBinding.clone() );
  34667. }
  34668. } else {
  34669. bindings.push( instanceGroup );
  34670. }
  34671. }
  34672. return bindings;
  34673. }
  34674. }
  34675. /**
  34676. * {@link NodeBuilder} is going to create instances of this class during the build process
  34677. * of nodes. They represent the final shader attributes that are going to be generated
  34678. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  34679. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  34680. */
  34681. class NodeAttribute {
  34682. /**
  34683. * Constructs a new node attribute.
  34684. *
  34685. * @param {string} name - The name of the attribute.
  34686. * @param {string} type - The type of the attribute.
  34687. * @param {?Node} node - An optional reference to the node.
  34688. */
  34689. constructor( name, type, node = null ) {
  34690. /**
  34691. * This flag can be used for type testing.
  34692. *
  34693. * @type {boolean}
  34694. * @readonly
  34695. * @default true
  34696. */
  34697. this.isNodeAttribute = true;
  34698. /**
  34699. * The name of the attribute.
  34700. *
  34701. * @type {string}
  34702. */
  34703. this.name = name;
  34704. /**
  34705. * The type of the attribute.
  34706. *
  34707. * @type {string}
  34708. */
  34709. this.type = type;
  34710. /**
  34711. * An optional reference to the node.
  34712. *
  34713. * @type {?Node}
  34714. * @default null
  34715. */
  34716. this.node = node;
  34717. }
  34718. }
  34719. /**
  34720. * {@link NodeBuilder} is going to create instances of this class during the build process
  34721. * of nodes. They represent the final shader uniforms that are going to be generated
  34722. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  34723. * for this purpose.
  34724. */
  34725. class NodeUniform {
  34726. /**
  34727. * Constructs a new node uniform.
  34728. *
  34729. * @param {string} name - The name of the uniform.
  34730. * @param {string} type - The type of the uniform.
  34731. * @param {UniformNode} node - An reference to the node.
  34732. */
  34733. constructor( name, type, node ) {
  34734. /**
  34735. * This flag can be used for type testing.
  34736. *
  34737. * @type {boolean}
  34738. * @readonly
  34739. * @default true
  34740. */
  34741. this.isNodeUniform = true;
  34742. /**
  34743. * The name of the uniform.
  34744. *
  34745. * @type {string}
  34746. */
  34747. this.name = name;
  34748. /**
  34749. * The type of the uniform.
  34750. *
  34751. * @type {string}
  34752. */
  34753. this.type = type;
  34754. /**
  34755. * An reference to the node.
  34756. *
  34757. * @type {UniformNode}
  34758. */
  34759. this.node = node;
  34760. }
  34761. /**
  34762. * The value of the uniform node.
  34763. *
  34764. * @type {any}
  34765. */
  34766. get value() {
  34767. return this.node.value;
  34768. }
  34769. set value( val ) {
  34770. this.node.value = val;
  34771. }
  34772. /**
  34773. * The id of the uniform node.
  34774. *
  34775. * @type {number}
  34776. */
  34777. get id() {
  34778. return this.node.id;
  34779. }
  34780. /**
  34781. * The uniform node's group.
  34782. *
  34783. * @type {UniformGroupNode}
  34784. */
  34785. get groupNode() {
  34786. return this.node.groupNode;
  34787. }
  34788. }
  34789. /**
  34790. * {@link NodeBuilder} is going to create instances of this class during the build process
  34791. * of nodes. They represent the final shader variables that are going to be generated
  34792. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  34793. * this purpose.
  34794. */
  34795. class NodeVar {
  34796. /**
  34797. * Constructs a new node variable.
  34798. *
  34799. * @param {string} name - The name of the variable.
  34800. * @param {string} type - The type of the variable.
  34801. * @param {boolean} [readOnly=false] - The read-only flag.
  34802. * @param {?number} [count=null] - The size.
  34803. */
  34804. constructor( name, type, readOnly = false, count = null ) {
  34805. /**
  34806. * This flag can be used for type testing.
  34807. *
  34808. * @type {boolean}
  34809. * @readonly
  34810. * @default true
  34811. */
  34812. this.isNodeVar = true;
  34813. /**
  34814. * The name of the variable.
  34815. *
  34816. * @type {string}
  34817. */
  34818. this.name = name;
  34819. /**
  34820. * The type of the variable.
  34821. *
  34822. * @type {string}
  34823. */
  34824. this.type = type;
  34825. /**
  34826. * The read-only flag.
  34827. *
  34828. * @type {boolean}
  34829. */
  34830. this.readOnly = readOnly;
  34831. /**
  34832. * The size.
  34833. *
  34834. * @type {?number}
  34835. */
  34836. this.count = count;
  34837. }
  34838. }
  34839. /**
  34840. * {@link NodeBuilder} is going to create instances of this class during the build process
  34841. * of nodes. They represent the final shader varyings that are going to be generated
  34842. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  34843. * this purpose.
  34844. *
  34845. * @augments NodeVar
  34846. */
  34847. class NodeVarying extends NodeVar {
  34848. /**
  34849. * Constructs a new node varying.
  34850. *
  34851. * @param {string} name - The name of the varying.
  34852. * @param {string} type - The type of the varying.
  34853. * @param {?string} interpolationType - The interpolation type of the varying.
  34854. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  34855. */
  34856. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  34857. super( name, type );
  34858. /**
  34859. * Whether this varying requires interpolation or not. This property can be used
  34860. * to check if the varying can be optimized for a variable.
  34861. *
  34862. * @type {boolean}
  34863. * @default false
  34864. */
  34865. this.needsInterpolation = false;
  34866. /**
  34867. * This flag can be used for type testing.
  34868. *
  34869. * @type {boolean}
  34870. * @readonly
  34871. * @default true
  34872. */
  34873. this.isNodeVarying = true;
  34874. /**
  34875. * The interpolation type of the varying data.
  34876. *
  34877. * @type {?string}
  34878. * @default null
  34879. */
  34880. this.interpolationType = interpolationType;
  34881. /**
  34882. * The interpolation sampling type of varying data.
  34883. *
  34884. * @type {?string}
  34885. * @default null
  34886. */
  34887. this.interpolationSampling = interpolationSampling;
  34888. }
  34889. }
  34890. /**
  34891. * {@link NodeBuilder} is going to create instances of this class during the build process
  34892. * of nodes. They represent user-defined, native shader code portions that are going to be
  34893. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  34894. * for this purpose.
  34895. */
  34896. class NodeCode {
  34897. /**
  34898. * Constructs a new code node.
  34899. *
  34900. * @param {string} name - The name of the code.
  34901. * @param {string} type - The node type.
  34902. * @param {string} [code=''] - The native shader code.
  34903. */
  34904. constructor( name, type, code = '' ) {
  34905. /**
  34906. * The name of the code.
  34907. *
  34908. * @type {string}
  34909. */
  34910. this.name = name;
  34911. /**
  34912. * The node type.
  34913. *
  34914. * @type {string}
  34915. */
  34916. this.type = type;
  34917. /**
  34918. * The native shader code.
  34919. *
  34920. * @type {string}
  34921. * @default ''
  34922. */
  34923. this.code = code;
  34924. Object.defineProperty( this, 'isNodeCode', { value: true } );
  34925. }
  34926. }
  34927. let _id$6 = 0;
  34928. /**
  34929. * This utility class is used in {@link NodeBuilder} as an internal
  34930. * cache data structure for node data.
  34931. */
  34932. class NodeCache {
  34933. /**
  34934. * Constructs a new node cache.
  34935. *
  34936. * @param {?NodeCache} parent - A reference to a parent cache.
  34937. */
  34938. constructor( parent = null ) {
  34939. /**
  34940. * The id of the cache.
  34941. *
  34942. * @type {number}
  34943. * @readonly
  34944. */
  34945. this.id = _id$6 ++;
  34946. /**
  34947. * A weak map for managing node data.
  34948. *
  34949. * @type {WeakMap<Node, Object>}
  34950. */
  34951. this.nodesData = new WeakMap();
  34952. /**
  34953. * Reference to a parent node cache.
  34954. *
  34955. * @type {?NodeCache}
  34956. * @default null
  34957. */
  34958. this.parent = parent;
  34959. }
  34960. /**
  34961. * Returns the data for the given node.
  34962. *
  34963. * @param {Node} node - The node.
  34964. * @return {?Object} The data for the node.
  34965. */
  34966. getData( node ) {
  34967. let data = this.nodesData.get( node );
  34968. if ( data === undefined && this.parent !== null ) {
  34969. data = this.parent.getData( node );
  34970. }
  34971. return data;
  34972. }
  34973. /**
  34974. * Sets the data for a given node.
  34975. *
  34976. * @param {Node} node - The node.
  34977. * @param {Object} data - The data that should be cached.
  34978. */
  34979. setData( node, data ) {
  34980. this.nodesData.set( node, data );
  34981. }
  34982. }
  34983. class StructType {
  34984. constructor( name, members ) {
  34985. this.name = name;
  34986. this.members = members;
  34987. this.output = false;
  34988. }
  34989. }
  34990. /**
  34991. * Abstract base class for uniforms.
  34992. *
  34993. * @abstract
  34994. * @private
  34995. */
  34996. class Uniform {
  34997. /**
  34998. * Constructs a new uniform.
  34999. *
  35000. * @param {string} name - The uniform's name.
  35001. * @param {any} value - The uniform's value.
  35002. */
  35003. constructor( name, value ) {
  35004. /**
  35005. * The uniform's name.
  35006. *
  35007. * @type {string}
  35008. */
  35009. this.name = name;
  35010. /**
  35011. * The uniform's value.
  35012. *
  35013. * @type {any}
  35014. */
  35015. this.value = value;
  35016. /**
  35017. * Used to build the uniform buffer according to the STD140 layout.
  35018. * Derived uniforms will set this property to a data type specific
  35019. * value.
  35020. *
  35021. * @type {number}
  35022. */
  35023. this.boundary = 0;
  35024. /**
  35025. * The item size. Derived uniforms will set this property to a data
  35026. * type specific value.
  35027. *
  35028. * @type {number}
  35029. */
  35030. this.itemSize = 0;
  35031. /**
  35032. * This property is set by {@link UniformsGroup} and marks
  35033. * the start position in the uniform buffer.
  35034. *
  35035. * @type {number}
  35036. */
  35037. this.offset = 0;
  35038. /**
  35039. * This property is set by {@link UniformsGroup} and marks
  35040. * the index position in the uniform array.
  35041. *
  35042. * @type {number}
  35043. */
  35044. this.index = -1;
  35045. }
  35046. /**
  35047. * Sets the uniform's value.
  35048. *
  35049. * @param {any} value - The value to set.
  35050. */
  35051. setValue( value ) {
  35052. this.value = value;
  35053. }
  35054. /**
  35055. * Returns the uniform's value.
  35056. *
  35057. * @return {any} The value.
  35058. */
  35059. getValue() {
  35060. return this.value;
  35061. }
  35062. }
  35063. /**
  35064. * Represents a Number uniform.
  35065. *
  35066. * @private
  35067. * @augments Uniform
  35068. */
  35069. class NumberUniform extends Uniform {
  35070. /**
  35071. * Constructs a new Number uniform.
  35072. *
  35073. * @param {string} name - The uniform's name.
  35074. * @param {number} value - The uniform's value.
  35075. */
  35076. constructor( name, value = 0 ) {
  35077. super( name, value );
  35078. /**
  35079. * This flag can be used for type testing.
  35080. *
  35081. * @type {boolean}
  35082. * @readonly
  35083. * @default true
  35084. */
  35085. this.isNumberUniform = true;
  35086. this.boundary = 4;
  35087. this.itemSize = 1;
  35088. }
  35089. }
  35090. /**
  35091. * Represents a Vector2 uniform.
  35092. *
  35093. * @private
  35094. * @augments Uniform
  35095. */
  35096. class Vector2Uniform extends Uniform {
  35097. /**
  35098. * Constructs a new Number uniform.
  35099. *
  35100. * @param {string} name - The uniform's name.
  35101. * @param {Vector2} value - The uniform's value.
  35102. */
  35103. constructor( name, value = new Vector2() ) {
  35104. super( name, value );
  35105. /**
  35106. * This flag can be used for type testing.
  35107. *
  35108. * @type {boolean}
  35109. * @readonly
  35110. * @default true
  35111. */
  35112. this.isVector2Uniform = true;
  35113. this.boundary = 8;
  35114. this.itemSize = 2;
  35115. }
  35116. }
  35117. /**
  35118. * Represents a Vector3 uniform.
  35119. *
  35120. * @private
  35121. * @augments Uniform
  35122. */
  35123. class Vector3Uniform extends Uniform {
  35124. /**
  35125. * Constructs a new Number uniform.
  35126. *
  35127. * @param {string} name - The uniform's name.
  35128. * @param {Vector3} value - The uniform's value.
  35129. */
  35130. constructor( name, value = new Vector3() ) {
  35131. super( name, value );
  35132. /**
  35133. * This flag can be used for type testing.
  35134. *
  35135. * @type {boolean}
  35136. * @readonly
  35137. * @default true
  35138. */
  35139. this.isVector3Uniform = true;
  35140. this.boundary = 16;
  35141. this.itemSize = 3;
  35142. }
  35143. }
  35144. /**
  35145. * Represents a Vector4 uniform.
  35146. *
  35147. * @private
  35148. * @augments Uniform
  35149. */
  35150. class Vector4Uniform extends Uniform {
  35151. /**
  35152. * Constructs a new Number uniform.
  35153. *
  35154. * @param {string} name - The uniform's name.
  35155. * @param {Vector4} value - The uniform's value.
  35156. */
  35157. constructor( name, value = new Vector4() ) {
  35158. super( name, value );
  35159. /**
  35160. * This flag can be used for type testing.
  35161. *
  35162. * @type {boolean}
  35163. * @readonly
  35164. * @default true
  35165. */
  35166. this.isVector4Uniform = true;
  35167. this.boundary = 16;
  35168. this.itemSize = 4;
  35169. }
  35170. }
  35171. /**
  35172. * Represents a Color uniform.
  35173. *
  35174. * @private
  35175. * @augments Uniform
  35176. */
  35177. class ColorUniform extends Uniform {
  35178. /**
  35179. * Constructs a new Number uniform.
  35180. *
  35181. * @param {string} name - The uniform's name.
  35182. * @param {Color} value - The uniform's value.
  35183. */
  35184. constructor( name, value = new Color() ) {
  35185. super( name, value );
  35186. /**
  35187. * This flag can be used for type testing.
  35188. *
  35189. * @type {boolean}
  35190. * @readonly
  35191. * @default true
  35192. */
  35193. this.isColorUniform = true;
  35194. this.boundary = 16;
  35195. this.itemSize = 3;
  35196. }
  35197. }
  35198. /**
  35199. * Represents a Matrix2 uniform.
  35200. *
  35201. * @private
  35202. * @augments Uniform
  35203. */
  35204. class Matrix2Uniform extends Uniform {
  35205. /**
  35206. * Constructs a new Number uniform.
  35207. *
  35208. * @param {string} name - The uniform's name.
  35209. * @param {Matrix2} value - The uniform's value.
  35210. */
  35211. constructor( name, value = new Matrix2() ) {
  35212. super( name, value );
  35213. /**
  35214. * This flag can be used for type testing.
  35215. *
  35216. * @type {boolean}
  35217. * @readonly
  35218. * @default true
  35219. */
  35220. this.isMatrix2Uniform = true;
  35221. this.boundary = 8;
  35222. this.itemSize = 4;
  35223. }
  35224. }
  35225. /**
  35226. * Represents a Matrix3 uniform.
  35227. *
  35228. * @private
  35229. * @augments Uniform
  35230. */
  35231. class Matrix3Uniform extends Uniform {
  35232. /**
  35233. * Constructs a new Number uniform.
  35234. *
  35235. * @param {string} name - The uniform's name.
  35236. * @param {Matrix3} value - The uniform's value.
  35237. */
  35238. constructor( name, value = new Matrix3() ) {
  35239. super( name, value );
  35240. /**
  35241. * This flag can be used for type testing.
  35242. *
  35243. * @type {boolean}
  35244. * @readonly
  35245. * @default true
  35246. */
  35247. this.isMatrix3Uniform = true;
  35248. this.boundary = 48;
  35249. this.itemSize = 12;
  35250. }
  35251. }
  35252. /**
  35253. * Represents a Matrix4 uniform.
  35254. *
  35255. * @private
  35256. * @augments Uniform
  35257. */
  35258. class Matrix4Uniform extends Uniform {
  35259. /**
  35260. * Constructs a new Number uniform.
  35261. *
  35262. * @param {string} name - The uniform's name.
  35263. * @param {Matrix4} value - The uniform's value.
  35264. */
  35265. constructor( name, value = new Matrix4() ) {
  35266. super( name, value );
  35267. /**
  35268. * This flag can be used for type testing.
  35269. *
  35270. * @type {boolean}
  35271. * @readonly
  35272. * @default true
  35273. */
  35274. this.isMatrix4Uniform = true;
  35275. this.boundary = 64;
  35276. this.itemSize = 16;
  35277. }
  35278. }
  35279. /**
  35280. * A special form of Number uniform binding type.
  35281. * It's value is managed by a node object.
  35282. *
  35283. * @private
  35284. * @augments NumberUniform
  35285. */
  35286. class NumberNodeUniform extends NumberUniform {
  35287. /**
  35288. * Constructs a new node-based Number uniform.
  35289. *
  35290. * @param {NodeUniform} nodeUniform - The node uniform.
  35291. */
  35292. constructor( nodeUniform ) {
  35293. super( nodeUniform.name, nodeUniform.value );
  35294. /**
  35295. * The node uniform.
  35296. *
  35297. * @type {NodeUniform}
  35298. */
  35299. this.nodeUniform = nodeUniform;
  35300. }
  35301. /**
  35302. * Overwritten to return the value of the node uniform.
  35303. *
  35304. * @return {number} The value.
  35305. */
  35306. getValue() {
  35307. return this.nodeUniform.value;
  35308. }
  35309. /**
  35310. * Returns the node uniform data type.
  35311. *
  35312. * @return {string} The data type.
  35313. */
  35314. getType() {
  35315. return this.nodeUniform.type;
  35316. }
  35317. }
  35318. /**
  35319. * A special form of Vector2 uniform binding type.
  35320. * It's value is managed by a node object.
  35321. *
  35322. * @private
  35323. * @augments Vector2Uniform
  35324. */
  35325. class Vector2NodeUniform extends Vector2Uniform {
  35326. /**
  35327. * Constructs a new node-based Vector2 uniform.
  35328. *
  35329. * @param {NodeUniform} nodeUniform - The node uniform.
  35330. */
  35331. constructor( nodeUniform ) {
  35332. super( nodeUniform.name, nodeUniform.value );
  35333. /**
  35334. * The node uniform.
  35335. *
  35336. * @type {NodeUniform}
  35337. */
  35338. this.nodeUniform = nodeUniform;
  35339. }
  35340. /**
  35341. * Overwritten to return the value of the node uniform.
  35342. *
  35343. * @return {Vector2} The value.
  35344. */
  35345. getValue() {
  35346. return this.nodeUniform.value;
  35347. }
  35348. /**
  35349. * Returns the node uniform data type.
  35350. *
  35351. * @return {string} The data type.
  35352. */
  35353. getType() {
  35354. return this.nodeUniform.type;
  35355. }
  35356. }
  35357. /**
  35358. * A special form of Vector3 uniform binding type.
  35359. * It's value is managed by a node object.
  35360. *
  35361. * @private
  35362. * @augments Vector3Uniform
  35363. */
  35364. class Vector3NodeUniform extends Vector3Uniform {
  35365. /**
  35366. * Constructs a new node-based Vector3 uniform.
  35367. *
  35368. * @param {NodeUniform} nodeUniform - The node uniform.
  35369. */
  35370. constructor( nodeUniform ) {
  35371. super( nodeUniform.name, nodeUniform.value );
  35372. /**
  35373. * The node uniform.
  35374. *
  35375. * @type {NodeUniform}
  35376. */
  35377. this.nodeUniform = nodeUniform;
  35378. }
  35379. /**
  35380. * Overwritten to return the value of the node uniform.
  35381. *
  35382. * @return {Vector3} The value.
  35383. */
  35384. getValue() {
  35385. return this.nodeUniform.value;
  35386. }
  35387. /**
  35388. * Returns the node uniform data type.
  35389. *
  35390. * @return {string} The data type.
  35391. */
  35392. getType() {
  35393. return this.nodeUniform.type;
  35394. }
  35395. }
  35396. /**
  35397. * A special form of Vector4 uniform binding type.
  35398. * It's value is managed by a node object.
  35399. *
  35400. * @private
  35401. * @augments Vector4Uniform
  35402. */
  35403. class Vector4NodeUniform extends Vector4Uniform {
  35404. /**
  35405. * Constructs a new node-based Vector4 uniform.
  35406. *
  35407. * @param {NodeUniform} nodeUniform - The node uniform.
  35408. */
  35409. constructor( nodeUniform ) {
  35410. super( nodeUniform.name, nodeUniform.value );
  35411. /**
  35412. * The node uniform.
  35413. *
  35414. * @type {NodeUniform}
  35415. */
  35416. this.nodeUniform = nodeUniform;
  35417. }
  35418. /**
  35419. * Overwritten to return the value of the node uniform.
  35420. *
  35421. * @return {Vector4} The value.
  35422. */
  35423. getValue() {
  35424. return this.nodeUniform.value;
  35425. }
  35426. /**
  35427. * Returns the node uniform data type.
  35428. *
  35429. * @return {string} The data type.
  35430. */
  35431. getType() {
  35432. return this.nodeUniform.type;
  35433. }
  35434. }
  35435. /**
  35436. * A special form of Color uniform binding type.
  35437. * It's value is managed by a node object.
  35438. *
  35439. * @private
  35440. * @augments ColorUniform
  35441. */
  35442. class ColorNodeUniform extends ColorUniform {
  35443. /**
  35444. * Constructs a new node-based Color uniform.
  35445. *
  35446. * @param {NodeUniform} nodeUniform - The node uniform.
  35447. */
  35448. constructor( nodeUniform ) {
  35449. super( nodeUniform.name, nodeUniform.value );
  35450. /**
  35451. * The node uniform.
  35452. *
  35453. * @type {NodeUniform}
  35454. */
  35455. this.nodeUniform = nodeUniform;
  35456. }
  35457. /**
  35458. * Overwritten to return the value of the node uniform.
  35459. *
  35460. * @return {Color} The value.
  35461. */
  35462. getValue() {
  35463. return this.nodeUniform.value;
  35464. }
  35465. /**
  35466. * Returns the node uniform data type.
  35467. *
  35468. * @return {string} The data type.
  35469. */
  35470. getType() {
  35471. return this.nodeUniform.type;
  35472. }
  35473. }
  35474. /**
  35475. * A special form of Matrix2 uniform binding type.
  35476. * It's value is managed by a node object.
  35477. *
  35478. * @private
  35479. * @augments Matrix2Uniform
  35480. */
  35481. class Matrix2NodeUniform extends Matrix2Uniform {
  35482. /**
  35483. * Constructs a new node-based Matrix2 uniform.
  35484. *
  35485. * @param {NodeUniform} nodeUniform - The node uniform.
  35486. */
  35487. constructor( nodeUniform ) {
  35488. super( nodeUniform.name, nodeUniform.value );
  35489. /**
  35490. * The node uniform.
  35491. *
  35492. * @type {NodeUniform}
  35493. */
  35494. this.nodeUniform = nodeUniform;
  35495. }
  35496. /**
  35497. * Overwritten to return the value of the node uniform.
  35498. *
  35499. * @return {Matrix2} The value.
  35500. */
  35501. getValue() {
  35502. return this.nodeUniform.value;
  35503. }
  35504. /**
  35505. * Returns the node uniform data type.
  35506. *
  35507. * @return {string} The data type.
  35508. */
  35509. getType() {
  35510. return this.nodeUniform.type;
  35511. }
  35512. }
  35513. /**
  35514. * A special form of Matrix3 uniform binding type.
  35515. * It's value is managed by a node object.
  35516. *
  35517. * @private
  35518. * @augments Matrix3Uniform
  35519. */
  35520. class Matrix3NodeUniform extends Matrix3Uniform {
  35521. /**
  35522. * Constructs a new node-based Matrix3 uniform.
  35523. *
  35524. * @param {NodeUniform} nodeUniform - The node uniform.
  35525. */
  35526. constructor( nodeUniform ) {
  35527. super( nodeUniform.name, nodeUniform.value );
  35528. /**
  35529. * The node uniform.
  35530. *
  35531. * @type {NodeUniform}
  35532. */
  35533. this.nodeUniform = nodeUniform;
  35534. }
  35535. /**
  35536. * Overwritten to return the value of the node uniform.
  35537. *
  35538. * @return {Matrix3} The value.
  35539. */
  35540. getValue() {
  35541. return this.nodeUniform.value;
  35542. }
  35543. /**
  35544. * Returns the node uniform data type.
  35545. *
  35546. * @return {string} The data type.
  35547. */
  35548. getType() {
  35549. return this.nodeUniform.type;
  35550. }
  35551. }
  35552. /**
  35553. * A special form of Matrix4 uniform binding type.
  35554. * It's value is managed by a node object.
  35555. *
  35556. * @private
  35557. * @augments Matrix4Uniform
  35558. */
  35559. class Matrix4NodeUniform extends Matrix4Uniform {
  35560. /**
  35561. * Constructs a new node-based Matrix4 uniform.
  35562. *
  35563. * @param {NodeUniform} nodeUniform - The node uniform.
  35564. */
  35565. constructor( nodeUniform ) {
  35566. super( nodeUniform.name, nodeUniform.value );
  35567. /**
  35568. * The node uniform.
  35569. *
  35570. * @type {NodeUniform}
  35571. */
  35572. this.nodeUniform = nodeUniform;
  35573. }
  35574. /**
  35575. * Overwritten to return the value of the node uniform.
  35576. *
  35577. * @return {Matrix4} The value.
  35578. */
  35579. getValue() {
  35580. return this.nodeUniform.value;
  35581. }
  35582. /**
  35583. * Returns the node uniform data type.
  35584. *
  35585. * @return {string} The data type.
  35586. */
  35587. getType() {
  35588. return this.nodeUniform.type;
  35589. }
  35590. }
  35591. let _id$5 = 0;
  35592. const _bindingGroupsCache = new WeakMap();
  35593. const sharedNodeData = new WeakMap();
  35594. const typeFromArray = new Map( [
  35595. [ Int8Array, 'int' ],
  35596. [ Int16Array, 'int' ],
  35597. [ Int32Array, 'int' ],
  35598. [ Uint8Array, 'uint' ],
  35599. [ Uint16Array, 'uint' ],
  35600. [ Uint32Array, 'uint' ],
  35601. [ Float32Array, 'float' ]
  35602. ] );
  35603. const toFloat = ( value ) => {
  35604. if ( /e/g.test( value ) ) {
  35605. return String( value ).replace( /\+/g, '' );
  35606. } else {
  35607. value = Number( value );
  35608. return value + ( value % 1 ? '' : '.0' );
  35609. }
  35610. };
  35611. /**
  35612. * Base class for builders which generate a shader program based
  35613. * on a 3D object and its node material definition.
  35614. */
  35615. class NodeBuilder {
  35616. /**
  35617. * Constructs a new node builder.
  35618. *
  35619. * @param {Object3D} object - The 3D object.
  35620. * @param {Renderer} renderer - The current renderer.
  35621. * @param {NodeParser} parser - A reference to a node parser.
  35622. */
  35623. constructor( object, renderer, parser ) {
  35624. /**
  35625. * The 3D object.
  35626. *
  35627. * @type {Object3D}
  35628. */
  35629. this.object = object;
  35630. /**
  35631. * The material of the 3D object.
  35632. *
  35633. * @type {?Material}
  35634. */
  35635. this.material = ( object && object.material ) || null;
  35636. /**
  35637. * The geometry of the 3D object.
  35638. *
  35639. * @type {?BufferGeometry}
  35640. */
  35641. this.geometry = ( object && object.geometry ) || null;
  35642. /**
  35643. * The current renderer.
  35644. *
  35645. * @type {Renderer}
  35646. */
  35647. this.renderer = renderer;
  35648. /**
  35649. * A reference to a node parser.
  35650. *
  35651. * @type {NodeParser}
  35652. */
  35653. this.parser = parser;
  35654. /**
  35655. * The scene the 3D object belongs to.
  35656. *
  35657. * @type {?Scene}
  35658. * @default null
  35659. */
  35660. this.scene = null;
  35661. /**
  35662. * The camera the 3D object is rendered with.
  35663. *
  35664. * @type {?Camera}
  35665. * @default null
  35666. */
  35667. this.camera = null;
  35668. /**
  35669. * A list of all nodes the builder is processing
  35670. * for this 3D object.
  35671. *
  35672. * @type {Array<Node>}
  35673. */
  35674. this.nodes = [];
  35675. /**
  35676. * A list of all nodes the builder is processing in sequential order.
  35677. *
  35678. * This is used to determine the update order of nodes, which is important for
  35679. * {@link NodeUpdateType#UPDATE_BEFORE} and {@link NodeUpdateType#UPDATE_AFTER}.
  35680. *
  35681. * @type {Array<Node>}
  35682. */
  35683. this.sequentialNodes = [];
  35684. /**
  35685. * A list of all nodes which {@link Node#update} method should be executed.
  35686. *
  35687. * @type {Array<Node>}
  35688. */
  35689. this.updateNodes = [];
  35690. /**
  35691. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  35692. *
  35693. * @type {Array<Node>}
  35694. */
  35695. this.updateBeforeNodes = [];
  35696. /**
  35697. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  35698. *
  35699. * @type {Array<Node>}
  35700. */
  35701. this.updateAfterNodes = [];
  35702. /**
  35703. * A dictionary that assigns each node to a unique hash.
  35704. *
  35705. * @type {Object<number,Node>}
  35706. */
  35707. this.hashNodes = {};
  35708. /**
  35709. * A reference to a node material observer.
  35710. *
  35711. * @type {?NodeMaterialObserver}
  35712. * @default null
  35713. */
  35714. this.observer = null;
  35715. /**
  35716. * A reference to the current lights node.
  35717. *
  35718. * @type {?LightsNode}
  35719. * @default null
  35720. */
  35721. this.lightsNode = null;
  35722. /**
  35723. * A reference to the current environment node.
  35724. *
  35725. * @type {?Node}
  35726. * @default null
  35727. */
  35728. this.environmentNode = null;
  35729. /**
  35730. * A reference to the current fog node.
  35731. *
  35732. * @type {?Node}
  35733. * @default null
  35734. */
  35735. this.fogNode = null;
  35736. /**
  35737. * The current clipping context.
  35738. *
  35739. * @type {?ClippingContext}
  35740. */
  35741. this.clippingContext = null;
  35742. /**
  35743. * The generated vertex shader.
  35744. *
  35745. * @type {?string}
  35746. */
  35747. this.vertexShader = null;
  35748. /**
  35749. * The generated fragment shader.
  35750. *
  35751. * @type {?string}
  35752. */
  35753. this.fragmentShader = null;
  35754. /**
  35755. * The generated compute shader.
  35756. *
  35757. * @type {?string}
  35758. */
  35759. this.computeShader = null;
  35760. /**
  35761. * Nodes used in the primary flow of code generation.
  35762. *
  35763. * @type {Object<string,Array<Node>>}
  35764. */
  35765. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  35766. /**
  35767. * Nodes code from `.flowNodes`.
  35768. *
  35769. * @type {Object<string,string>}
  35770. */
  35771. this.flowCode = { vertex: '', fragment: '', compute: '' };
  35772. /**
  35773. * This dictionary holds the node uniforms of the builder.
  35774. * The uniforms are maintained in an array for each shader stage.
  35775. *
  35776. * @type {Object}
  35777. */
  35778. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  35779. /**
  35780. * This dictionary holds the output structs of the builder.
  35781. * The structs are maintained in an array for each shader stage.
  35782. *
  35783. * @type {Object}
  35784. */
  35785. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  35786. /**
  35787. * This dictionary holds the types of the builder.
  35788. *
  35789. * @type {Object}
  35790. */
  35791. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  35792. /**
  35793. * This dictionary holds the bindings for each shader stage.
  35794. *
  35795. * @type {Object}
  35796. */
  35797. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  35798. /**
  35799. * This dictionary maintains the binding indices per bind group.
  35800. *
  35801. * @type {Object}
  35802. */
  35803. this.bindingsIndexes = {};
  35804. /**
  35805. * Reference to the array of bind groups.
  35806. *
  35807. * @type {?Array<BindGroup>}
  35808. */
  35809. this.bindGroups = null;
  35810. /**
  35811. * This array holds the node attributes of this builder
  35812. * created via {@link AttributeNode}.
  35813. *
  35814. * @type {Array<NodeAttribute>}
  35815. */
  35816. this.attributes = [];
  35817. /**
  35818. * This array holds the node attributes of this builder
  35819. * created via {@link BufferAttributeNode}.
  35820. *
  35821. * @type {Array<NodeAttribute>}
  35822. */
  35823. this.bufferAttributes = [];
  35824. /**
  35825. * This array holds the node varyings of this builder.
  35826. *
  35827. * @type {Array<NodeVarying>}
  35828. */
  35829. this.varyings = [];
  35830. /**
  35831. * This dictionary holds the (native) node codes of this builder.
  35832. * The codes are maintained in an array for each shader stage.
  35833. *
  35834. * @type {Object<string,Array<NodeCode>>}
  35835. */
  35836. this.codes = {};
  35837. /**
  35838. * This dictionary holds the node variables of this builder.
  35839. * The variables are maintained in an array for each shader stage.
  35840. * This dictionary is also used to count the number of variables
  35841. * according to their type (const, vars).
  35842. *
  35843. * @type {Object<string,Array<NodeVar>|number>}
  35844. */
  35845. this.vars = {};
  35846. /**
  35847. * This dictionary holds the declarations for each shader stage.
  35848. *
  35849. * @type {Object}
  35850. */
  35851. this.declarations = {};
  35852. /**
  35853. * Current code flow.
  35854. * All code generated in this stack will be stored in `.flow`.
  35855. *
  35856. * @type {{code: string}}
  35857. */
  35858. this.flow = { code: '' };
  35859. /**
  35860. * A chain of nodes.
  35861. * Used to check recursive calls in node-graph.
  35862. *
  35863. * @type {Array<Node>}
  35864. */
  35865. this.chaining = [];
  35866. /**
  35867. * The current stack.
  35868. * This reflects the current process in the code block hierarchy,
  35869. * it is useful to know if the current process is inside a conditional for example.
  35870. *
  35871. * @type {StackNode}
  35872. */
  35873. this.stack = stack();
  35874. /**
  35875. * List of stack nodes.
  35876. * The current stack hierarchy is stored in an array.
  35877. *
  35878. * @type {Array<StackNode>}
  35879. */
  35880. this.stacks = [];
  35881. /**
  35882. * A tab value. Used for shader string generation.
  35883. *
  35884. * @type {string}
  35885. * @default '\t'
  35886. */
  35887. this.tab = '\t';
  35888. /**
  35889. * Reference to the current function node.
  35890. *
  35891. * @type {?FunctionNode}
  35892. * @default null
  35893. */
  35894. this.currentFunctionNode = null;
  35895. /**
  35896. * The builder's context.
  35897. *
  35898. * @type {Object}
  35899. */
  35900. this.context = {
  35901. material: this.material
  35902. };
  35903. /**
  35904. * The builder's cache.
  35905. *
  35906. * @type {NodeCache}
  35907. */
  35908. this.cache = new NodeCache();
  35909. /**
  35910. * Since the {@link NodeBuilder#cache} might be temporarily
  35911. * overwritten by other caches, this member retains the reference
  35912. * to the builder's own cache.
  35913. *
  35914. * @type {NodeCache}
  35915. * @default this.cache
  35916. */
  35917. this.globalCache = this.cache;
  35918. this.flowsData = new WeakMap();
  35919. /**
  35920. * The current shader stage.
  35921. *
  35922. * @type {?('vertex'|'fragment'|'compute'|'any')}
  35923. */
  35924. this.shaderStage = null;
  35925. /**
  35926. * The current build stage.
  35927. *
  35928. * @type {?('setup'|'analyze'|'generate')}
  35929. */
  35930. this.buildStage = null;
  35931. /**
  35932. * The sub-build layers.
  35933. *
  35934. * @type {Array<SubBuildNode>}
  35935. * @default []
  35936. */
  35937. this.subBuildLayers = [];
  35938. /**
  35939. * The active stack nodes.
  35940. *
  35941. * @type {Array<StackNode>}
  35942. */
  35943. this.activeStacks = [];
  35944. /**
  35945. * The current sub-build TSL function(Fn).
  35946. *
  35947. * @type {?string}
  35948. * @default null
  35949. */
  35950. this.subBuildFn = null;
  35951. /**
  35952. * The current TSL function(Fn) call node.
  35953. *
  35954. * @type {?Node}
  35955. * @default null
  35956. */
  35957. this.fnCall = null;
  35958. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  35959. }
  35960. /**
  35961. * Whether the material is using flat shading or not.
  35962. *
  35963. * @returns {boolean} Whether the material is using flat shading or not.
  35964. */
  35965. isFlatShading() {
  35966. return this.material.flatShading === true || this.geometry.hasAttribute( 'normal' ) === false;
  35967. }
  35968. /**
  35969. * Whether the material is opaque or not.
  35970. *
  35971. * @return {boolean} Whether the material is opaque or not.
  35972. */
  35973. isOpaque() {
  35974. const material = this.material;
  35975. return material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false;
  35976. }
  35977. /**
  35978. * Factory method for creating an instance of {@link RenderTarget} with the given
  35979. * dimensions and options.
  35980. *
  35981. * @param {number} width - The width of the render target.
  35982. * @param {number} height - The height of the render target.
  35983. * @param {Object} options - The options of the render target.
  35984. * @return {RenderTarget} The render target.
  35985. */
  35986. createRenderTarget( width, height, options ) {
  35987. return new RenderTarget( width, height, options );
  35988. }
  35989. /**
  35990. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  35991. * dimensions and options.
  35992. *
  35993. * @param {number} size - The size of the cube render target.
  35994. * @param {Object} options - The options of the cube render target.
  35995. * @return {CubeRenderTarget} The cube render target.
  35996. */
  35997. createCubeRenderTarget( size, options ) {
  35998. return new CubeRenderTarget( size, options );
  35999. }
  36000. /**
  36001. * Whether the given node is included in the internal array of nodes or not.
  36002. *
  36003. * @param {Node} node - The node to test.
  36004. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  36005. */
  36006. includes( node ) {
  36007. return this.nodes.includes( node );
  36008. }
  36009. /**
  36010. * Returns the output struct name which is required by
  36011. * {@link OutputStructNode}.
  36012. *
  36013. * @abstract
  36014. * @return {string} The name of the output struct.
  36015. */
  36016. getOutputStructName() {}
  36017. /**
  36018. * Returns a bind group for the given group name and binding.
  36019. *
  36020. * @private
  36021. * @param {string} groupName - The group name.
  36022. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  36023. * @return {BindGroup} The bind group
  36024. */
  36025. _getBindGroup( groupName, bindings ) {
  36026. const groupNode = bindings[ 0 ].groupNode;
  36027. let sharedGroup = groupNode.shared;
  36028. if ( sharedGroup ) {
  36029. for ( let i = 1; i < bindings.length; i ++ ) {
  36030. if ( groupNode !== bindings[ i ].groupNode ) {
  36031. sharedGroup = false;
  36032. }
  36033. }
  36034. }
  36035. //
  36036. let bindGroup;
  36037. if ( sharedGroup ) {
  36038. let cacheKeyString = '';
  36039. for ( const binding of bindings ) {
  36040. if ( binding.isNodeUniformsGroup ) {
  36041. binding.uniforms.sort( ( a, b ) => a.nodeUniform.node.id - b.nodeUniform.node.id );
  36042. for ( const uniform of binding.uniforms ) {
  36043. cacheKeyString += uniform.nodeUniform.node.id;
  36044. }
  36045. } else {
  36046. cacheKeyString += binding.nodeUniform.id;
  36047. }
  36048. }
  36049. // TODO: Remove this hack ._currentRenderContext
  36050. const currentContext = this.renderer._currentRenderContext || this.renderer; // use renderer as fallback until we have a compute context
  36051. let bindingGroupsCache = _bindingGroupsCache.get( currentContext );
  36052. if ( bindingGroupsCache === undefined ) {
  36053. bindingGroupsCache = new Map();
  36054. _bindingGroupsCache.set( currentContext, bindingGroupsCache );
  36055. }
  36056. //
  36057. const cacheKey = hashString( cacheKeyString );
  36058. bindGroup = bindingGroupsCache.get( cacheKey );
  36059. if ( bindGroup === undefined ) {
  36060. bindGroup = new BindGroup( groupName, bindings );
  36061. bindingGroupsCache.set( cacheKey, bindGroup );
  36062. }
  36063. } else {
  36064. bindGroup = new BindGroup( groupName, bindings );
  36065. }
  36066. return bindGroup;
  36067. }
  36068. /**
  36069. * Returns an array of node uniform groups for the given group name and shader stage.
  36070. *
  36071. * @param {string} groupName - The group name.
  36072. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36073. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  36074. */
  36075. getBindGroupArray( groupName, shaderStage ) {
  36076. const bindings = this.bindings[ shaderStage ];
  36077. let bindGroup = bindings[ groupName ];
  36078. if ( bindGroup === undefined ) {
  36079. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  36080. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  36081. }
  36082. bindings[ groupName ] = bindGroup = [];
  36083. }
  36084. return bindGroup;
  36085. }
  36086. /**
  36087. * Returns a list bindings of all shader stages separated by groups.
  36088. *
  36089. * @return {Array<BindGroup>} The list of bindings.
  36090. */
  36091. getBindings() {
  36092. let bindingsGroups = this.bindGroups;
  36093. if ( bindingsGroups === null ) {
  36094. const groups = {};
  36095. const bindings = this.bindings;
  36096. for ( const shaderStage of shaderStages ) {
  36097. for ( const groupName in bindings[ shaderStage ] ) {
  36098. const uniforms = bindings[ shaderStage ][ groupName ];
  36099. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  36100. for ( const uniform of uniforms ) {
  36101. if ( groupUniforms.includes( uniform ) === false ) {
  36102. groupUniforms.push( uniform );
  36103. }
  36104. }
  36105. }
  36106. }
  36107. bindingsGroups = [];
  36108. for ( const groupName in groups ) {
  36109. const group = groups[ groupName ];
  36110. const bindingsGroup = this._getBindGroup( groupName, group );
  36111. bindingsGroups.push( bindingsGroup );
  36112. }
  36113. this.bindGroups = bindingsGroups;
  36114. }
  36115. return bindingsGroups;
  36116. }
  36117. /**
  36118. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  36119. */
  36120. sortBindingGroups() {
  36121. const bindingsGroups = this.getBindings();
  36122. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  36123. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  36124. const bindingGroup = bindingsGroups[ i ];
  36125. this.bindingsIndexes[ bindingGroup.name ].group = i;
  36126. }
  36127. }
  36128. /**
  36129. * The builder maintains each node in a hash-based dictionary.
  36130. * This method sets the given node (value) with the given hash (key) into this dictionary.
  36131. *
  36132. * @param {Node} node - The node to add.
  36133. * @param {number} hash - The hash of the node.
  36134. */
  36135. setHashNode( node, hash ) {
  36136. this.hashNodes[ hash ] = node;
  36137. }
  36138. /**
  36139. * Adds a node to this builder.
  36140. *
  36141. * @param {Node} node - The node to add.
  36142. */
  36143. addNode( node ) {
  36144. if ( this.nodes.includes( node ) === false ) {
  36145. this.nodes.push( node );
  36146. this.setHashNode( node, node.getHash( this ) );
  36147. }
  36148. }
  36149. /**
  36150. * It is used to add Nodes that will be used as FRAME and RENDER events,
  36151. * and need to follow a certain sequence in the calls to work correctly.
  36152. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  36153. *
  36154. * @param {Node} node - The node to add.
  36155. */
  36156. addSequentialNode( node ) {
  36157. const updateBeforeType = node.getUpdateBeforeType();
  36158. const updateAfterType = node.getUpdateAfterType();
  36159. if ( updateBeforeType !== NodeUpdateType.NONE || updateAfterType !== NodeUpdateType.NONE ) {
  36160. if ( this.sequentialNodes.includes( node ) === false ) {
  36161. this.sequentialNodes.push( node );
  36162. }
  36163. }
  36164. }
  36165. /**
  36166. * Checks the update types of nodes
  36167. */
  36168. buildUpdateNodes() {
  36169. for ( const node of this.nodes ) {
  36170. const updateType = node.getUpdateType();
  36171. if ( updateType !== NodeUpdateType.NONE ) {
  36172. this.updateNodes.push( node );
  36173. }
  36174. }
  36175. for ( const node of this.sequentialNodes ) {
  36176. const updateBeforeType = node.getUpdateBeforeType();
  36177. const updateAfterType = node.getUpdateAfterType();
  36178. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  36179. this.updateBeforeNodes.push( node );
  36180. }
  36181. if ( updateAfterType !== NodeUpdateType.NONE ) {
  36182. this.updateAfterNodes.push( node );
  36183. }
  36184. }
  36185. }
  36186. /**
  36187. * A reference the current node which is the
  36188. * last node in the chain of nodes.
  36189. *
  36190. * @type {Node}
  36191. */
  36192. get currentNode() {
  36193. return this.chaining[ this.chaining.length - 1 ];
  36194. }
  36195. /**
  36196. * Whether the given texture is filtered or not.
  36197. *
  36198. * @param {Texture} texture - The texture to check.
  36199. * @return {boolean} Whether the given texture is filtered or not.
  36200. */
  36201. isFilteredTexture( texture ) {
  36202. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  36203. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  36204. }
  36205. /**
  36206. * Returns the maximum number of bytes available for uniform buffers.
  36207. *
  36208. * @return {number} The maximum number of bytes available for uniform buffers.
  36209. */
  36210. getUniformBufferLimit() {
  36211. return this.renderer.backend.capabilities.getUniformBufferLimit();
  36212. }
  36213. /**
  36214. * Adds the given node to the internal node chain.
  36215. * This is used to check recursive calls in node-graph.
  36216. *
  36217. * @param {Node} node - The node to add.
  36218. */
  36219. addChain( node ) {
  36220. /*
  36221. if ( this.chaining.indexOf( node ) !== - 1 ) {
  36222. warn( 'Recursive node: ', node );
  36223. }
  36224. */
  36225. this.chaining.push( node );
  36226. }
  36227. /**
  36228. * Removes the given node from the internal node chain.
  36229. *
  36230. * @param {Node} node - The node to remove.
  36231. */
  36232. removeChain( node ) {
  36233. const lastChain = this.chaining.pop();
  36234. if ( lastChain !== node ) {
  36235. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  36236. }
  36237. }
  36238. /**
  36239. * Returns the native shader method name for a given generic name. E.g.
  36240. * the method name `textureDimensions` matches the WGSL name but must be
  36241. * resolved to `textureSize` in GLSL.
  36242. *
  36243. * @abstract
  36244. * @param {string} method - The method name to resolve.
  36245. * @return {string} The resolved method name.
  36246. */
  36247. getMethod( method ) {
  36248. return method;
  36249. }
  36250. /**
  36251. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  36252. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  36253. *
  36254. * @abstract
  36255. * @param {string} condSnippet - The condition determining which expression gets resolved.
  36256. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  36257. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  36258. * @return {string} The resolved method name.
  36259. */
  36260. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  36261. return null;
  36262. }
  36263. /**
  36264. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  36265. *
  36266. * @param {number} hash - The hash of the node.
  36267. * @return {Node} The found node.
  36268. */
  36269. getNodeFromHash( hash ) {
  36270. return this.hashNodes[ hash ];
  36271. }
  36272. /**
  36273. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  36274. *
  36275. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  36276. * @param {Node} node - The node to add.
  36277. * @return {Node} The node.
  36278. */
  36279. addFlow( shaderStage, node ) {
  36280. this.flowNodes[ shaderStage ].push( node );
  36281. return node;
  36282. }
  36283. /**
  36284. * Sets builder's context.
  36285. *
  36286. * @param {Object} context - The context to set.
  36287. */
  36288. setContext( context ) {
  36289. this.context = context;
  36290. }
  36291. /**
  36292. * Returns the builder's current context.
  36293. *
  36294. * @return {Object} The builder's current context.
  36295. */
  36296. getContext() {
  36297. return this.context;
  36298. }
  36299. /**
  36300. * Adds context data to the builder's current context.
  36301. *
  36302. * @param {Object} context - The context to add.
  36303. * @return {Object} The previous context.
  36304. */
  36305. addContext( context ) {
  36306. const previousContext = this.getContext();
  36307. this.setContext( { ...this.context, ...context } );
  36308. return previousContext;
  36309. }
  36310. /**
  36311. * Gets a context used in shader construction that can be shared across different materials.
  36312. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  36313. *
  36314. * @return {Object} The builder's current context without material.
  36315. */
  36316. getSharedContext() {
  36317. const context = { ...this.context };
  36318. delete context.material;
  36319. delete context.getUV;
  36320. delete context.getOutput;
  36321. delete context.getTextureLevel;
  36322. delete context.getAO;
  36323. delete context.getShadow;
  36324. return context;
  36325. }
  36326. /**
  36327. * Sets builder's cache.
  36328. *
  36329. * @param {NodeCache} cache - The cache to set.
  36330. */
  36331. setCache( cache ) {
  36332. this.cache = cache;
  36333. }
  36334. /**
  36335. * Returns the builder's current cache.
  36336. *
  36337. * @return {NodeCache} The builder's current cache.
  36338. */
  36339. getCache() {
  36340. return this.cache;
  36341. }
  36342. /**
  36343. * Returns a cache for the given node.
  36344. *
  36345. * @param {Node} node - The node.
  36346. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  36347. * @return {NodeCache} The cache.
  36348. */
  36349. getCacheFromNode( node, parent = true ) {
  36350. const data = this.getDataFromNode( node );
  36351. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  36352. return data.cache;
  36353. }
  36354. /**
  36355. * Whether the requested feature is available or not.
  36356. *
  36357. * @abstract
  36358. * @param {string} name - The requested feature.
  36359. * @return {boolean} Whether the requested feature is supported or not.
  36360. */
  36361. isAvailable( /*name*/ ) {
  36362. return false;
  36363. }
  36364. /**
  36365. * Returns the vertexIndex input variable as a native shader string.
  36366. *
  36367. * @abstract
  36368. * @return {string} The instanceIndex shader string.
  36369. */
  36370. getVertexIndex() {
  36371. warn( 'Abstract function.' );
  36372. }
  36373. /**
  36374. * Contextually returns either the vertex stage instance index builtin
  36375. * or the linearized index of an compute invocation within a grid of workgroups.
  36376. *
  36377. * @abstract
  36378. * @return {string} The instanceIndex shader string.
  36379. */
  36380. getInstanceIndex() {
  36381. warn( 'Abstract function.' );
  36382. }
  36383. /**
  36384. * Returns the drawIndex input variable as a native shader string.
  36385. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  36386. *
  36387. * @abstract
  36388. * @return {?string} The drawIndex shader string.
  36389. */
  36390. getDrawIndex() {
  36391. warn( 'Abstract function.' );
  36392. }
  36393. /**
  36394. * Returns the frontFacing input variable as a native shader string.
  36395. *
  36396. * @abstract
  36397. * @return {string} The frontFacing shader string.
  36398. */
  36399. getFrontFacing() {
  36400. warn( 'Abstract function.' );
  36401. }
  36402. /**
  36403. * Returns the fragCoord input variable as a native shader string.
  36404. *
  36405. * @abstract
  36406. * @return {string} The fragCoord shader string.
  36407. */
  36408. getFragCoord() {
  36409. warn( 'Abstract function.' );
  36410. }
  36411. /**
  36412. * Whether to flip texture data along its vertical axis or not. WebGL needs
  36413. * this method evaluate to `true`, WebGPU to `false`.
  36414. *
  36415. * @abstract
  36416. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  36417. */
  36418. isFlipY() {
  36419. return false;
  36420. }
  36421. /**
  36422. * Calling this method increases the usage count for the given node by one.
  36423. *
  36424. * @param {Node} node - The node to increase the usage count for.
  36425. * @return {number} The updated usage count.
  36426. */
  36427. increaseUsage( node ) {
  36428. const nodeData = this.getDataFromNode( node );
  36429. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  36430. return nodeData.usageCount;
  36431. }
  36432. /**
  36433. * Generates a texture sample shader string for the given texture data.
  36434. *
  36435. * @abstract
  36436. * @param {Texture} texture - The texture.
  36437. * @param {string} textureProperty - The texture property name.
  36438. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36439. * @return {string} The generated shader string.
  36440. */
  36441. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  36442. warn( 'Abstract function.' );
  36443. }
  36444. /**
  36445. * Generates a texture LOD shader string for the given texture data.
  36446. *
  36447. * @abstract
  36448. * @param {Texture} texture - The texture.
  36449. * @param {string} textureProperty - The texture property name.
  36450. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36451. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  36452. * @param {string} levelSnippet - Snippet defining the mip level.
  36453. * @return {string} The generated shader string.
  36454. */
  36455. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  36456. warn( 'Abstract function.' );
  36457. }
  36458. /**
  36459. * Generates the array declaration string.
  36460. *
  36461. * @param {string} type - The type.
  36462. * @param {?number} [count] - The count.
  36463. * @return {string} The generated value as a shader string.
  36464. */
  36465. generateArrayDeclaration( type, count ) {
  36466. return this.getType( type ) + '[ ' + count + ' ]';
  36467. }
  36468. /**
  36469. * Generates the array shader string for the given type and value.
  36470. *
  36471. * @param {string} type - The type.
  36472. * @param {?number} [count] - The count.
  36473. * @param {?Array<Node>} [values=null] - The default values.
  36474. * @return {string} The generated value as a shader string.
  36475. */
  36476. generateArray( type, count, values = null ) {
  36477. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  36478. for ( let i = 0; i < count; i ++ ) {
  36479. const value = values ? values[ i ] : null;
  36480. if ( value !== null ) {
  36481. snippet += value.build( this, type );
  36482. } else {
  36483. snippet += this.generateConst( type );
  36484. }
  36485. if ( i < count - 1 ) snippet += ', ';
  36486. }
  36487. snippet += ' )';
  36488. return snippet;
  36489. }
  36490. /**
  36491. * Generates the struct shader string.
  36492. *
  36493. * @param {string} type - The type.
  36494. * @param {Array<Object>} [membersLayout] - The count.
  36495. * @param {?Array<Node>} [values=null] - The default values.
  36496. * @return {string} The generated value as a shader string.
  36497. */
  36498. generateStruct( type, membersLayout, values = null ) {
  36499. const snippets = [];
  36500. for ( const member of membersLayout ) {
  36501. const { name, type } = member;
  36502. if ( values && values[ name ] && values[ name ].isNode ) {
  36503. snippets.push( values[ name ].build( this, type ) );
  36504. } else {
  36505. snippets.push( this.generateConst( type ) );
  36506. }
  36507. }
  36508. return type + '( ' + snippets.join( ', ' ) + ' )';
  36509. }
  36510. /**
  36511. * Generates the shader string for the given type and value.
  36512. *
  36513. * @param {string} type - The type.
  36514. * @param {?any} [value=null] - The value.
  36515. * @return {string} The generated value as a shader string.
  36516. */
  36517. generateConst( type, value = null ) {
  36518. if ( value === null ) {
  36519. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  36520. else if ( type === 'bool' ) value = false;
  36521. else if ( type === 'color' ) value = new Color();
  36522. else if ( type === 'vec2' || type === 'uvec2' || type === 'ivec2' ) value = new Vector2();
  36523. else if ( type === 'vec3' || type === 'uvec3' || type === 'ivec3' ) value = new Vector3();
  36524. else if ( type === 'vec4' || type === 'uvec4' || type === 'ivec4' ) value = new Vector4();
  36525. }
  36526. if ( type === 'float' ) return toFloat( value );
  36527. if ( type === 'int' ) return `${ Math.round( value ) }`;
  36528. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  36529. if ( type === 'bool' ) return value ? 'true' : 'false';
  36530. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  36531. const typeLength = this.getTypeLength( type );
  36532. const componentType = this.getComponentType( type );
  36533. const generateConst = value => this.generateConst( componentType, value );
  36534. if ( typeLength === 2 ) {
  36535. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  36536. } else if ( typeLength === 3 ) {
  36537. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  36538. } else if ( typeLength === 4 && type !== 'mat2' ) {
  36539. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  36540. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  36541. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  36542. } else if ( typeLength > 4 ) {
  36543. return `${ this.getType( type ) }()`;
  36544. }
  36545. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  36546. }
  36547. /**
  36548. * It might be necessary to convert certain data types to different ones
  36549. * so this method can be used to hide the conversion.
  36550. *
  36551. * @param {string} type - The type.
  36552. * @return {string} The updated type.
  36553. */
  36554. getType( type ) {
  36555. if ( type === 'color' ) return 'vec3';
  36556. return type;
  36557. }
  36558. /**
  36559. * Whether the given attribute name is defined in the geometry or not.
  36560. *
  36561. * @param {string} name - The attribute name.
  36562. * @return {boolean} Whether the given attribute name is defined in the geometry.
  36563. */
  36564. hasGeometryAttribute( name ) {
  36565. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  36566. }
  36567. /**
  36568. * Returns a node attribute for the given name and type.
  36569. *
  36570. * @param {string} name - The attribute's name.
  36571. * @param {string} type - The attribute's type.
  36572. * @return {NodeAttribute} The node attribute.
  36573. */
  36574. getAttribute( name, type ) {
  36575. const attributes = this.attributes;
  36576. // find attribute
  36577. for ( const attribute of attributes ) {
  36578. if ( attribute.name === name ) {
  36579. return attribute;
  36580. }
  36581. }
  36582. // create a new if no exist
  36583. const attribute = new NodeAttribute( name, type );
  36584. this.registerDeclaration( attribute );
  36585. attributes.push( attribute );
  36586. return attribute;
  36587. }
  36588. /**
  36589. * Returns for the given node and shader stage the property name for the shader.
  36590. *
  36591. * @param {Node} node - The node.
  36592. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36593. * @return {string} The property name.
  36594. */
  36595. getPropertyName( node/*, shaderStage*/ ) {
  36596. return node.name;
  36597. }
  36598. /**
  36599. * Whether the given type is a vector type or not.
  36600. *
  36601. * @param {string} type - The type to check.
  36602. * @return {boolean} Whether the given type is a vector type or not.
  36603. */
  36604. isVector( type ) {
  36605. return /vec\d/.test( type );
  36606. }
  36607. /**
  36608. * Whether the given type is a matrix type or not.
  36609. *
  36610. * @param {string} type - The type to check.
  36611. * @return {boolean} Whether the given type is a matrix type or not.
  36612. */
  36613. isMatrix( type ) {
  36614. return /mat\d/.test( type );
  36615. }
  36616. /**
  36617. * Whether the given type is a reference type or not.
  36618. *
  36619. * @param {string} type - The type to check.
  36620. * @return {boolean} Whether the given type is a reference type or not.
  36621. */
  36622. isReference( type ) {
  36623. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  36624. }
  36625. /**
  36626. * Checks if the given texture requires a manual conversion to the working color space.
  36627. *
  36628. * @abstract
  36629. * @param {Texture} texture - The texture to check.
  36630. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  36631. */
  36632. needsToWorkingColorSpace( /*texture*/ ) {
  36633. return false;
  36634. }
  36635. /**
  36636. * Returns the component type of a given texture.
  36637. *
  36638. * @param {Texture} texture - The texture.
  36639. * @return {string} The component type.
  36640. */
  36641. getComponentTypeFromTexture( texture ) {
  36642. const type = texture.type;
  36643. if ( texture.isDataTexture ) {
  36644. if ( type === IntType ) return 'int';
  36645. if ( type === UnsignedIntType ) return 'uint';
  36646. }
  36647. return 'float';
  36648. }
  36649. /**
  36650. * Returns the element type for a given type.
  36651. *
  36652. * @param {string} type - The type.
  36653. * @return {string} The element type.
  36654. */
  36655. getElementType( type ) {
  36656. if ( type === 'mat2' ) return 'vec2';
  36657. if ( type === 'mat3' ) return 'vec3';
  36658. if ( type === 'mat4' ) return 'vec4';
  36659. return this.getComponentType( type );
  36660. }
  36661. /**
  36662. * Returns the component type for a given type.
  36663. *
  36664. * @param {string} type - The type.
  36665. * @return {string} The component type.
  36666. */
  36667. getComponentType( type ) {
  36668. type = this.getVectorType( type );
  36669. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  36670. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  36671. if ( componentType === null ) return null;
  36672. if ( componentType[ 1 ] === 'b' ) return 'bool';
  36673. if ( componentType[ 1 ] === 'i' ) return 'int';
  36674. if ( componentType[ 1 ] === 'u' ) return 'uint';
  36675. return 'float';
  36676. }
  36677. /**
  36678. * Returns the vector type for a given type.
  36679. *
  36680. * @param {string} type - The type.
  36681. * @return {string} The vector type.
  36682. */
  36683. getVectorType( type ) {
  36684. if ( type === 'color' ) return 'vec3';
  36685. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  36686. return type;
  36687. }
  36688. /**
  36689. * Returns the data type for the given the length and component type.
  36690. *
  36691. * @param {number} length - The length.
  36692. * @param {string} [componentType='float'] - The component type.
  36693. * @return {string} The type.
  36694. */
  36695. getTypeFromLength( length, componentType = 'float' ) {
  36696. if ( length === 1 ) return componentType;
  36697. let baseType = getTypeFromLength( length );
  36698. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  36699. // fix edge case for mat2x2 being same size as vec4
  36700. if ( /mat2/.test( componentType ) === true ) {
  36701. baseType = baseType.replace( 'vec', 'mat' );
  36702. }
  36703. return prefix + baseType;
  36704. }
  36705. /**
  36706. * Returns the type for a given typed array.
  36707. *
  36708. * @param {TypedArray} array - The typed array.
  36709. * @return {string} The type.
  36710. */
  36711. getTypeFromArray( array ) {
  36712. return typeFromArray.get( array.constructor );
  36713. }
  36714. /**
  36715. * Returns the type is an integer type.
  36716. *
  36717. * @param {string} type - The type.
  36718. * @return {boolean} Whether the type is an integer type or not.
  36719. */
  36720. isInteger( type ) {
  36721. return /int|uint|(i|u)vec/.test( type );
  36722. }
  36723. /**
  36724. * Returns the type for a given buffer attribute.
  36725. *
  36726. * @param {BufferAttribute} attribute - The buffer attribute.
  36727. * @return {string} The type.
  36728. */
  36729. getTypeFromAttribute( attribute ) {
  36730. let dataAttribute = attribute;
  36731. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36732. const array = dataAttribute.array;
  36733. const itemSize = attribute.itemSize;
  36734. const normalized = attribute.normalized;
  36735. let arrayType;
  36736. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  36737. arrayType = this.getTypeFromArray( array );
  36738. }
  36739. return this.getTypeFromLength( itemSize, arrayType );
  36740. }
  36741. /**
  36742. * Returns the length for the given data type.
  36743. *
  36744. * @param {string} type - The data type.
  36745. * @return {number} The length.
  36746. */
  36747. getTypeLength( type ) {
  36748. const vecType = this.getVectorType( type );
  36749. const vecNum = /vec([2-4])/.exec( vecType );
  36750. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  36751. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  36752. if ( /mat2/.test( type ) === true ) return 4;
  36753. if ( /mat3/.test( type ) === true ) return 9;
  36754. if ( /mat4/.test( type ) === true ) return 16;
  36755. return 0;
  36756. }
  36757. /**
  36758. * Returns the vector type for a given matrix type.
  36759. *
  36760. * @param {string} type - The matrix type.
  36761. * @return {string} The vector type.
  36762. */
  36763. getVectorFromMatrix( type ) {
  36764. return type.replace( 'mat', 'vec' );
  36765. }
  36766. /**
  36767. * For a given type this method changes the component type to the
  36768. * given value. E.g. `vec4` should be changed to the new component type
  36769. * `uint` which results in `uvec4`.
  36770. *
  36771. * @param {string} type - The type.
  36772. * @param {string} newComponentType - The new component type.
  36773. * @return {string} The new type.
  36774. */
  36775. changeComponentType( type, newComponentType ) {
  36776. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  36777. }
  36778. /**
  36779. * Returns the integer type pendant for the given type.
  36780. *
  36781. * @param {string} type - The type.
  36782. * @return {string} The integer type.
  36783. */
  36784. getIntegerType( type ) {
  36785. const componentType = this.getComponentType( type );
  36786. if ( componentType === 'int' || componentType === 'uint' ) return type;
  36787. return this.changeComponentType( type, 'int' );
  36788. }
  36789. /**
  36790. * Adds an active stack to the internal stack.
  36791. *
  36792. * @param {StackNode} stack - The stack node to add.
  36793. */
  36794. setActiveStack( stack ) {
  36795. this.activeStacks.push( stack );
  36796. }
  36797. /**
  36798. * Removes the active stack from the internal stack.
  36799. *
  36800. * @param {StackNode} stack - The stack node to remove.
  36801. */
  36802. removeActiveStack( stack ) {
  36803. if ( this.activeStacks[ this.activeStacks.length - 1 ] === stack ) {
  36804. this.activeStacks.pop();
  36805. } else {
  36806. throw new Error( 'NodeBuilder: Invalid active stack removal.' );
  36807. }
  36808. }
  36809. /**
  36810. * Returns the active stack.
  36811. *
  36812. * @return {StackNode} The active stack.
  36813. */
  36814. getActiveStack() {
  36815. return this.activeStacks[ this.activeStacks.length - 1 ];
  36816. }
  36817. /**
  36818. * Returns the base stack.
  36819. *
  36820. * @return {StackNode} The base stack.
  36821. */
  36822. getBaseStack() {
  36823. return this.activeStacks[ 0 ];
  36824. }
  36825. /**
  36826. * Adds a stack node to the internal stack.
  36827. *
  36828. * @return {StackNode} The added stack node.
  36829. */
  36830. addStack() {
  36831. this.stack = stack( this.stack );
  36832. const previousStack = getCurrentStack();
  36833. this.stacks.push( previousStack );
  36834. setCurrentStack( this.stack );
  36835. return this.stack;
  36836. }
  36837. /**
  36838. * Removes the last stack node from the internal stack.
  36839. *
  36840. * @return {StackNode} The removed stack node.
  36841. */
  36842. removeStack() {
  36843. const lastStack = this.stack;
  36844. for ( const node of lastStack.nodes ) {
  36845. const nodeData = this.getDataFromNode( node );
  36846. nodeData.stack = lastStack;
  36847. }
  36848. this.stack = lastStack.parent;
  36849. setCurrentStack( this.stacks.pop() );
  36850. return lastStack;
  36851. }
  36852. /**
  36853. * The builder maintains (cached) data for each node during the building process. This method
  36854. * can be used to get these data for a specific shader stage and cache.
  36855. *
  36856. * @param {Node} node - The node to get the data for.
  36857. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36858. * @param {?NodeCache} cache - An optional cache.
  36859. * @return {Object} The node data.
  36860. */
  36861. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  36862. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  36863. let nodeData = cache.getData( node );
  36864. if ( nodeData === undefined ) {
  36865. nodeData = {};
  36866. cache.setData( node, nodeData );
  36867. }
  36868. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  36869. //
  36870. let data = nodeData[ shaderStage ];
  36871. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  36872. const subBuild = this.getClosestSubBuild( subBuilds );
  36873. if ( subBuild ) {
  36874. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  36875. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  36876. data.subBuilds = subBuilds;
  36877. }
  36878. return data;
  36879. }
  36880. /**
  36881. * Returns the properties for the given node and shader stage.
  36882. *
  36883. * Properties are typically used within a build stage to reference a node's
  36884. * child node or nodes manually assigned to the properties in a separate build stage.
  36885. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  36886. * to the current node's properties in the setup stage and building those properties in the generate stage.
  36887. *
  36888. * @param {Node} node - The node to get the properties for.
  36889. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  36890. * @return {Object} The node properties.
  36891. */
  36892. getNodeProperties( node, shaderStage = 'any' ) {
  36893. const nodeData = this.getDataFromNode( node, shaderStage );
  36894. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  36895. }
  36896. /**
  36897. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  36898. *
  36899. * @param {BufferAttributeNode} node - The buffer attribute node.
  36900. * @param {string} type - The node type.
  36901. * @return {NodeAttribute} The node attribute.
  36902. */
  36903. getBufferAttributeFromNode( node, type ) {
  36904. const nodeData = this.getDataFromNode( node, 'vertex' );
  36905. let bufferAttribute = nodeData.bufferAttribute;
  36906. if ( bufferAttribute === undefined ) {
  36907. const index = this.uniforms.index ++;
  36908. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  36909. this.bufferAttributes.push( bufferAttribute );
  36910. nodeData.bufferAttribute = bufferAttribute;
  36911. }
  36912. return bufferAttribute;
  36913. }
  36914. /**
  36915. * Returns an instance of {@link StructType} for the given struct name and shader stage
  36916. * or null if not found.
  36917. *
  36918. * @param {string} name - The name of the struct.
  36919. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36920. * @return {?StructType} The struct type or null if not found.
  36921. */
  36922. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  36923. return this.types[ shaderStage ][ name ] || null;
  36924. }
  36925. /**
  36926. * Returns an instance of {@link StructType} for the given output struct node.
  36927. *
  36928. * @param {OutputStructNode} node - The output struct node.
  36929. * @param {Array<Object>} membersLayout - The output struct types.
  36930. * @param {?string} [name=null] - The name of the struct.
  36931. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36932. * @return {StructType} The struct type attribute.
  36933. */
  36934. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  36935. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36936. let structType = nodeData.structType;
  36937. if ( structType === undefined ) {
  36938. const index = this.structs.index ++;
  36939. if ( name === null ) name = 'StructType' + index;
  36940. structType = new StructType( name, membersLayout );
  36941. this.structs[ shaderStage ].push( structType );
  36942. this.types[ shaderStage ][ name ] = node;
  36943. nodeData.structType = structType;
  36944. }
  36945. return structType;
  36946. }
  36947. /**
  36948. * Returns an instance of {@link StructType} for the given output struct node.
  36949. *
  36950. * @param {OutputStructNode} node - The output struct node.
  36951. * @param {Array<Object>} membersLayout - The output struct types.
  36952. * @return {StructType} The struct type attribute.
  36953. */
  36954. getOutputStructTypeFromNode( node, membersLayout ) {
  36955. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  36956. structType.output = true;
  36957. return structType;
  36958. }
  36959. /**
  36960. * Returns an instance of {@link NodeUniform} for the given uniform node.
  36961. *
  36962. * @param {UniformNode} node - The uniform node.
  36963. * @param {string} type - The uniform type.
  36964. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36965. * @param {?string} name - The name of the uniform.
  36966. * @return {NodeUniform} The node uniform.
  36967. */
  36968. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  36969. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36970. let nodeUniform = nodeData.uniform;
  36971. if ( nodeUniform === undefined ) {
  36972. const index = this.uniforms.index ++;
  36973. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  36974. this.uniforms[ shaderStage ].push( nodeUniform );
  36975. this.registerDeclaration( nodeUniform );
  36976. nodeData.uniform = nodeUniform;
  36977. }
  36978. return nodeUniform;
  36979. }
  36980. /**
  36981. * Returns an instance of {@link NodeVar} for the given variable node.
  36982. *
  36983. * @param {VarNode} node - The variable node.
  36984. * @param {?string} name - The variable's name.
  36985. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  36986. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36987. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  36988. *
  36989. * @return {NodeVar} The node variable.
  36990. */
  36991. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  36992. const nodeData = this.getDataFromNode( node, shaderStage );
  36993. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  36994. let nodeVar = nodeData[ subBuildVariable ];
  36995. if ( nodeVar === undefined ) {
  36996. const idNS = readOnly ? '_const' : '_var';
  36997. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  36998. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  36999. if ( name === null ) {
  37000. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  37001. this.vars[ idNS ] ++;
  37002. }
  37003. //
  37004. if ( subBuildVariable !== 'variable' ) {
  37005. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  37006. }
  37007. //
  37008. const count = node.getArrayCount( this );
  37009. nodeVar = new NodeVar( name, type, readOnly, count );
  37010. if ( ! readOnly ) {
  37011. vars.push( nodeVar );
  37012. }
  37013. this.registerDeclaration( nodeVar );
  37014. nodeData[ subBuildVariable ] = nodeVar;
  37015. }
  37016. return nodeVar;
  37017. }
  37018. /**
  37019. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  37020. *
  37021. * @param {Node} node - The varying node.
  37022. * @return {boolean} Returns true if deterministic.
  37023. */
  37024. isDeterministic( node ) {
  37025. if ( node.isMathNode ) {
  37026. return this.isDeterministic( node.aNode ) &&
  37027. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  37028. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  37029. } else if ( node.isOperatorNode ) {
  37030. return this.isDeterministic( node.aNode ) &&
  37031. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  37032. } else if ( node.isArrayNode ) {
  37033. if ( node.values !== null ) {
  37034. for ( const n of node.values ) {
  37035. if ( ! this.isDeterministic( n ) ) {
  37036. return false;
  37037. }
  37038. }
  37039. }
  37040. return true;
  37041. } else if ( node.isConstNode ) {
  37042. return true;
  37043. }
  37044. return false;
  37045. }
  37046. /**
  37047. * Returns an instance of {@link NodeVarying} for the given varying node.
  37048. *
  37049. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  37050. * @param {?string} name - The varying's name.
  37051. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  37052. * @param {?string} interpolationType - The interpolation type of the varying.
  37053. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  37054. * @return {NodeVar} The node varying.
  37055. */
  37056. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  37057. const nodeData = this.getDataFromNode( node, 'any' );
  37058. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  37059. let nodeVarying = nodeData[ subBuildVarying ];
  37060. if ( nodeVarying === undefined ) {
  37061. const varyings = this.varyings;
  37062. const index = varyings.length;
  37063. if ( name === null ) name = 'nodeVarying' + index;
  37064. //
  37065. if ( subBuildVarying !== 'varying' ) {
  37066. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  37067. }
  37068. //
  37069. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  37070. varyings.push( nodeVarying );
  37071. this.registerDeclaration( nodeVarying );
  37072. nodeData[ subBuildVarying ] = nodeVarying;
  37073. }
  37074. return nodeVarying;
  37075. }
  37076. /**
  37077. * Registers a node declaration in the current shader stage.
  37078. *
  37079. * @param {Object} node - The node to be registered.
  37080. */
  37081. registerDeclaration( node ) {
  37082. const shaderStage = this.shaderStage;
  37083. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  37084. const property = this.getPropertyName( node );
  37085. let index = 1;
  37086. let name = property;
  37087. // Automatically renames the property if the name is already in use.
  37088. while ( declarations[ name ] !== undefined ) {
  37089. name = property + '_' + index ++;
  37090. }
  37091. if ( index > 1 ) {
  37092. node.name = name;
  37093. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  37094. }
  37095. declarations[ name ] = node;
  37096. }
  37097. /**
  37098. * Returns an instance of {@link NodeCode} for the given code node.
  37099. *
  37100. * @param {CodeNode} node - The code node.
  37101. * @param {string} type - The node type.
  37102. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  37103. * @return {NodeCode} The node code.
  37104. */
  37105. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  37106. const nodeData = this.getDataFromNode( node );
  37107. let nodeCode = nodeData.code;
  37108. if ( nodeCode === undefined ) {
  37109. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  37110. const index = codes.length;
  37111. nodeCode = new NodeCode( 'nodeCode' + index, type );
  37112. codes.push( nodeCode );
  37113. nodeData.code = nodeCode;
  37114. }
  37115. return nodeCode;
  37116. }
  37117. /**
  37118. * Adds a code flow based on the code-block hierarchy.
  37119. * This is used so that code-blocks like If,Else create their variables locally if the Node
  37120. * is only used inside one of these conditionals in the current shader stage.
  37121. *
  37122. * @param {Node} node - The node to add.
  37123. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  37124. */
  37125. addFlowCodeHierarchy( node, nodeBlock ) {
  37126. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  37127. let needsFlowCode = true;
  37128. let nodeBlockHierarchy = nodeBlock;
  37129. while ( nodeBlockHierarchy ) {
  37130. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  37131. needsFlowCode = false;
  37132. break;
  37133. }
  37134. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  37135. }
  37136. if ( needsFlowCode ) {
  37137. for ( const flowCode of flowCodes ) {
  37138. this.addLineFlowCode( flowCode );
  37139. }
  37140. }
  37141. }
  37142. /**
  37143. * Add a inline-code to the current flow code-block.
  37144. *
  37145. * @param {Node} node - The node to add.
  37146. * @param {string} code - The code to add.
  37147. * @param {Node} nodeBlock - Current ConditionalNode
  37148. */
  37149. addLineFlowCodeBlock( node, code, nodeBlock ) {
  37150. const nodeData = this.getDataFromNode( node );
  37151. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  37152. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  37153. flowCodes.push( code );
  37154. codeBlock.set( nodeBlock, true );
  37155. }
  37156. /**
  37157. * Add a inline-code to the current flow.
  37158. *
  37159. * @param {string} code - The code to add.
  37160. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  37161. * @return {NodeBuilder} A reference to this node builder.
  37162. */
  37163. addLineFlowCode( code, node = null ) {
  37164. if ( code === '' ) return this;
  37165. if ( node !== null && this.context.nodeBlock ) {
  37166. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  37167. }
  37168. code = this.tab + code;
  37169. if ( ! /;\s*$/.test( code ) ) {
  37170. code = code + ';\n';
  37171. }
  37172. this.flow.code += code;
  37173. return this;
  37174. }
  37175. /**
  37176. * Adds a code to the current code flow.
  37177. *
  37178. * @param {string} code - Shader code.
  37179. * @return {NodeBuilder} A reference to this node builder.
  37180. */
  37181. addFlowCode( code ) {
  37182. this.flow.code += code;
  37183. return this;
  37184. }
  37185. /**
  37186. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  37187. * Typically used in codes with If,Else.
  37188. *
  37189. * @return {NodeBuilder} A reference to this node builder.
  37190. */
  37191. addFlowTab() {
  37192. this.tab += '\t';
  37193. return this;
  37194. }
  37195. /**
  37196. * Removes a tab.
  37197. *
  37198. * @return {NodeBuilder} A reference to this node builder.
  37199. */
  37200. removeFlowTab() {
  37201. this.tab = this.tab.slice( 0, -1 );
  37202. return this;
  37203. }
  37204. /**
  37205. * Gets the current flow data based on a Node.
  37206. *
  37207. * @param {Node} node - Node that the flow was started.
  37208. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37209. * @return {Object} The flow data.
  37210. */
  37211. getFlowData( node/*, shaderStage*/ ) {
  37212. return this.flowsData.get( node );
  37213. }
  37214. /**
  37215. * Executes the node flow based on a root node to generate the final shader code.
  37216. *
  37217. * @param {Node} node - The node to execute.
  37218. * @return {Object} The code flow.
  37219. */
  37220. flowNode( node ) {
  37221. const output = node.getNodeType( this );
  37222. const flowData = this.flowChildNode( node, output );
  37223. this.flowsData.set( node, flowData );
  37224. return flowData;
  37225. }
  37226. /**
  37227. * Includes a node in the current function node.
  37228. *
  37229. * @param {Node} node - The node to include.
  37230. * @returns {void}
  37231. */
  37232. addInclude( node ) {
  37233. if ( this.currentFunctionNode !== null ) {
  37234. this.currentFunctionNode.includes.push( node );
  37235. }
  37236. }
  37237. /**
  37238. * Returns the native shader operator name for a given generic name.
  37239. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  37240. *
  37241. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  37242. * @return {FunctionNode} The build function node.
  37243. */
  37244. buildFunctionNode( shaderNode ) {
  37245. const fn = new FunctionNode();
  37246. const previous = this.currentFunctionNode;
  37247. this.currentFunctionNode = fn;
  37248. fn.code = this.buildFunctionCode( shaderNode );
  37249. this.currentFunctionNode = previous;
  37250. return fn;
  37251. }
  37252. /**
  37253. * Generates a code flow based on a TSL function: Fn().
  37254. *
  37255. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  37256. * @return {Object}
  37257. */
  37258. flowShaderNode( shaderNode ) {
  37259. const layout = shaderNode.layout;
  37260. const inputs = {
  37261. [ Symbol.iterator ]() {
  37262. let index = 0;
  37263. const values = Object.values( this );
  37264. return {
  37265. next: () => ( {
  37266. value: values[ index ],
  37267. done: index ++ >= values.length
  37268. } )
  37269. };
  37270. }
  37271. };
  37272. for ( const input of layout.inputs ) {
  37273. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  37274. }
  37275. //
  37276. shaderNode.layout = null;
  37277. const callNode = shaderNode.call( inputs );
  37278. const flowData = this.flowStagesNode( callNode, layout.type );
  37279. shaderNode.layout = layout;
  37280. return flowData;
  37281. }
  37282. /**
  37283. * Executes the node in a specific build stage.
  37284. *
  37285. * This function can be used to arbitrarily execute the specified build stage
  37286. * outside of the standard build process. For instance, if a node's type depends
  37287. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  37288. * can be used to execute the setup build stage and access its generated nodes
  37289. * before the standard build process begins.
  37290. *
  37291. * @param {Node} node - The node to execute.
  37292. * @param {string} buildStage - The build stage to execute the node in.
  37293. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  37294. * @return {?(Node|string)} The result of the node build.
  37295. */
  37296. flowBuildStage( node, buildStage, output = null ) {
  37297. const previousBuildStage = this.getBuildStage();
  37298. this.setBuildStage( buildStage );
  37299. const result = node.build( this, output );
  37300. this.setBuildStage( previousBuildStage );
  37301. return result;
  37302. }
  37303. /**
  37304. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  37305. *
  37306. * @param {Node} node - The node to execute.
  37307. * @param {?string} output - Expected output type. For example 'vec3'.
  37308. * @return {Object}
  37309. */
  37310. flowStagesNode( node, output = null ) {
  37311. const previousFlow = this.flow;
  37312. const previousVars = this.vars;
  37313. const previousDeclarations = this.declarations;
  37314. const previousCache = this.cache;
  37315. const previousBuildStage = this.buildStage;
  37316. const previousStack = this.stack;
  37317. const flow = {
  37318. code: ''
  37319. };
  37320. this.flow = flow;
  37321. this.vars = {};
  37322. this.declarations = {};
  37323. this.cache = new NodeCache();
  37324. this.stack = stack();
  37325. for ( const buildStage of defaultBuildStages ) {
  37326. this.setBuildStage( buildStage );
  37327. flow.result = node.build( this, output );
  37328. }
  37329. flow.vars = this.getVars( this.shaderStage );
  37330. this.flow = previousFlow;
  37331. this.vars = previousVars;
  37332. this.declarations = previousDeclarations;
  37333. this.cache = previousCache;
  37334. this.stack = previousStack;
  37335. this.setBuildStage( previousBuildStage );
  37336. return flow;
  37337. }
  37338. /**
  37339. * Returns the native shader operator name for a given generic name.
  37340. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  37341. *
  37342. * @abstract
  37343. * @param {string} op - The operator name to resolve.
  37344. * @return {?string} The resolved operator name.
  37345. */
  37346. getFunctionOperator( /* op */ ) {
  37347. return null;
  37348. }
  37349. /**
  37350. * Builds the given shader node.
  37351. *
  37352. * @abstract
  37353. * @param {ShaderNodeInternal} shaderNode - The shader node.
  37354. * @return {string} The function code.
  37355. */
  37356. buildFunctionCode( /* shaderNode */ ) {
  37357. warn( 'Abstract function.' );
  37358. }
  37359. /**
  37360. * Generates a code flow based on a child Node.
  37361. *
  37362. * @param {Node} node - The node to execute.
  37363. * @param {?string} output - Expected output type. For example 'vec3'.
  37364. * @return {Object} The code flow.
  37365. */
  37366. flowChildNode( node, output = null ) {
  37367. const previousFlow = this.flow;
  37368. const flow = {
  37369. code: ''
  37370. };
  37371. this.flow = flow;
  37372. flow.result = node.build( this, output );
  37373. this.flow = previousFlow;
  37374. return flow;
  37375. }
  37376. /**
  37377. * Executes a flow of code in a different stage.
  37378. *
  37379. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  37380. * return the value in fragment-stage even if it is being executed in an input fragment.
  37381. *
  37382. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37383. * @param {Node} node - The node to execute.
  37384. * @param {?string} output - Expected output type. For example 'vec3'.
  37385. * @param {?string} propertyName - The property name to assign the result.
  37386. * @return {?(Object|Node)} The code flow or node.build() result.
  37387. */
  37388. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  37389. const previousTab = this.tab;
  37390. const previousCache = this.cache;
  37391. const previousShaderStage = this.shaderStage;
  37392. const previousContext = this.context;
  37393. this.setShaderStage( shaderStage );
  37394. const context = { ...this.context };
  37395. delete context.nodeBlock;
  37396. this.cache = this.globalCache;
  37397. this.tab = '\t';
  37398. this.context = context;
  37399. let result = null;
  37400. if ( this.buildStage === 'generate' ) {
  37401. const flowData = this.flowChildNode( node, output );
  37402. if ( propertyName !== null ) {
  37403. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  37404. }
  37405. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  37406. result = flowData;
  37407. } else {
  37408. result = node.build( this );
  37409. }
  37410. this.setShaderStage( previousShaderStage );
  37411. this.cache = previousCache;
  37412. this.tab = previousTab;
  37413. this.context = previousContext;
  37414. return result;
  37415. }
  37416. /**
  37417. * Returns an array holding all node attributes of this node builder.
  37418. *
  37419. * @return {Array<NodeAttribute>} The node attributes of this builder.
  37420. */
  37421. getAttributesArray() {
  37422. return this.attributes.concat( this.bufferAttributes );
  37423. }
  37424. /**
  37425. * Returns the attribute definitions as a shader string for the given shader stage.
  37426. *
  37427. * @abstract
  37428. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37429. * @return {string} The attribute code section.
  37430. */
  37431. getAttributes( /*shaderStage*/ ) {
  37432. warn( 'Abstract function.' );
  37433. }
  37434. /**
  37435. * Returns the varying definitions as a shader string for the given shader stage.
  37436. *
  37437. * @abstract
  37438. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37439. * @return {string} The varying code section.
  37440. */
  37441. getVaryings( /*shaderStage*/ ) {
  37442. warn( 'Abstract function.' );
  37443. }
  37444. /**
  37445. * Returns a single variable definition as a shader string for the given variable type and name.
  37446. *
  37447. * @param {string} type - The variable's type.
  37448. * @param {string} name - The variable's name.
  37449. * @param {?number} [count=null] - The array length.
  37450. * @return {string} The shader string.
  37451. */
  37452. getVar( type, name, count = null ) {
  37453. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  37454. }
  37455. /**
  37456. * Returns the variable definitions as a shader string for the given shader stage.
  37457. *
  37458. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37459. * @return {string} The variable code section.
  37460. */
  37461. getVars( shaderStage ) {
  37462. let snippet = '';
  37463. const vars = this.vars[ shaderStage ];
  37464. if ( vars !== undefined ) {
  37465. for ( const variable of vars ) {
  37466. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  37467. }
  37468. }
  37469. return snippet;
  37470. }
  37471. /**
  37472. * Returns the uniform definitions as a shader string for the given shader stage.
  37473. *
  37474. * @abstract
  37475. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37476. * @return {string} The uniform code section.
  37477. */
  37478. getUniforms( /*shaderStage*/ ) {
  37479. warn( 'Abstract function.' );
  37480. }
  37481. /**
  37482. * Returns the native code definitions as a shader string for the given shader stage.
  37483. *
  37484. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37485. * @return {string} The native code section.
  37486. */
  37487. getCodes( shaderStage ) {
  37488. const codes = this.codes[ shaderStage ];
  37489. let code = '';
  37490. if ( codes !== undefined ) {
  37491. for ( const nodeCode of codes ) {
  37492. code += nodeCode.code + '\n';
  37493. }
  37494. }
  37495. return code;
  37496. }
  37497. /**
  37498. * Returns the hash of this node builder.
  37499. *
  37500. * @return {string} The hash.
  37501. */
  37502. getHash() {
  37503. return this.vertexShader + this.fragmentShader + this.computeShader;
  37504. }
  37505. /**
  37506. * Sets the current shader stage.
  37507. *
  37508. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  37509. */
  37510. setShaderStage( shaderStage ) {
  37511. this.shaderStage = shaderStage;
  37512. }
  37513. /**
  37514. * Returns the current shader stage.
  37515. *
  37516. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  37517. */
  37518. getShaderStage() {
  37519. return this.shaderStage;
  37520. }
  37521. /**
  37522. * Sets the current build stage.
  37523. *
  37524. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  37525. */
  37526. setBuildStage( buildStage ) {
  37527. this.buildStage = buildStage;
  37528. }
  37529. /**
  37530. * Returns the current build stage.
  37531. *
  37532. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  37533. */
  37534. getBuildStage() {
  37535. return this.buildStage;
  37536. }
  37537. /**
  37538. * Controls the code build of the shader stages.
  37539. *
  37540. * @abstract
  37541. */
  37542. buildCode() {
  37543. warn( 'Abstract function.' );
  37544. }
  37545. /**
  37546. * Returns the current sub-build layer.
  37547. *
  37548. * @return {SubBuildNode} The current sub-build layers.
  37549. */
  37550. get subBuild() {
  37551. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  37552. }
  37553. /**
  37554. * Adds a sub-build layer to the node builder.
  37555. *
  37556. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  37557. */
  37558. addSubBuild( subBuild ) {
  37559. this.subBuildLayers.push( subBuild );
  37560. }
  37561. /**
  37562. * Removes the last sub-build layer from the node builder.
  37563. *
  37564. * @return {SubBuildNode} The removed sub-build layer.
  37565. */
  37566. removeSubBuild() {
  37567. return this.subBuildLayers.pop();
  37568. }
  37569. /**
  37570. * Returns the closest sub-build layer for the given data.
  37571. *
  37572. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  37573. * @return {?string} The closest sub-build name or null if none found.
  37574. */
  37575. getClosestSubBuild( data ) {
  37576. let subBuilds;
  37577. if ( data && data.isNode ) {
  37578. if ( data.isShaderCallNodeInternal ) {
  37579. subBuilds = data.shaderNode.subBuilds;
  37580. } else if ( data.isStackNode ) {
  37581. subBuilds = [ data.subBuild ];
  37582. } else {
  37583. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  37584. }
  37585. } else if ( data instanceof Set ) {
  37586. subBuilds = [ ...data ];
  37587. } else {
  37588. subBuilds = data;
  37589. }
  37590. if ( ! subBuilds ) return null;
  37591. const subBuildLayers = this.subBuildLayers;
  37592. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  37593. const subBuild = subBuilds[ i ];
  37594. if ( subBuildLayers.includes( subBuild ) ) {
  37595. return subBuild;
  37596. }
  37597. }
  37598. return null;
  37599. }
  37600. /**
  37601. * Returns the output node of a sub-build layer.
  37602. *
  37603. * @param {Node} node - The node to get the output from.
  37604. * @return {string} The output node name.
  37605. */
  37606. getSubBuildOutput( node ) {
  37607. return this.getSubBuildProperty( 'outputNode', node );
  37608. }
  37609. /**
  37610. * Returns the sub-build property name for the given property and node.
  37611. *
  37612. * @param {string} [property=''] - The property name.
  37613. * @param {?Node} [node=null] - The node to get the sub-build from.
  37614. * @return {string} The sub-build property name.
  37615. */
  37616. getSubBuildProperty( property = '', node = null ) {
  37617. let subBuild;
  37618. if ( node !== null ) {
  37619. subBuild = this.getClosestSubBuild( node );
  37620. } else {
  37621. subBuild = this.subBuildFn;
  37622. }
  37623. let result;
  37624. if ( subBuild ) {
  37625. result = property ? ( subBuild + '_' + property ) : subBuild;
  37626. } else {
  37627. result = property;
  37628. }
  37629. return result;
  37630. }
  37631. /**
  37632. * Prebuild the node builder.
  37633. */
  37634. prebuild() {
  37635. const { object, renderer, material } = this;
  37636. // < renderer.contextNode >
  37637. if ( renderer.contextNode.isContextNode === true ) {
  37638. this.context = { ...this.context, ...renderer.contextNode.getFlowContextData() };
  37639. } else {
  37640. error( 'NodeBuilder: "renderer.contextNode" must be an instance of `context()`.' );
  37641. }
  37642. // < material.contextNode >
  37643. if ( material && material.contextNode ) {
  37644. if ( material.contextNode.isContextNode === true ) {
  37645. this.context = { ...this.context, ...material.contextNode.getFlowContextData() };
  37646. } else {
  37647. error( 'NodeBuilder: "material.contextNode" must be an instance of `context()`.' );
  37648. }
  37649. }
  37650. // < nodeMaterial >
  37651. if ( material !== null ) {
  37652. let nodeMaterial = renderer.library.fromMaterial( material );
  37653. if ( nodeMaterial === null ) {
  37654. error( `NodeBuilder: Material "${ material.type }" is not compatible.` );
  37655. nodeMaterial = new NodeMaterial();
  37656. }
  37657. nodeMaterial.build( this );
  37658. } else {
  37659. this.addFlow( 'compute', object );
  37660. }
  37661. }
  37662. /**
  37663. * Central build method which controls the build for the given object.
  37664. *
  37665. * @return {NodeBuilder} A reference to this node builder.
  37666. */
  37667. build() {
  37668. this.prebuild();
  37669. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  37670. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  37671. // generate() -> stage 3: generate shader
  37672. for ( const buildStage of defaultBuildStages ) {
  37673. this.setBuildStage( buildStage );
  37674. if ( this.context.position && this.context.position.isNode ) {
  37675. this.flowNodeFromShaderStage( 'vertex', this.context.position );
  37676. }
  37677. for ( const shaderStage of shaderStages ) {
  37678. this.setShaderStage( shaderStage );
  37679. const flowNodes = this.flowNodes[ shaderStage ];
  37680. for ( const node of flowNodes ) {
  37681. if ( buildStage === 'generate' ) {
  37682. this.flowNode( node );
  37683. } else {
  37684. node.build( this );
  37685. }
  37686. }
  37687. }
  37688. }
  37689. this.setBuildStage( null );
  37690. this.setShaderStage( null );
  37691. // stage 4: build code for a specific output
  37692. this.buildCode();
  37693. this.buildUpdateNodes();
  37694. return this;
  37695. }
  37696. /**
  37697. * Async version of build() that yields to main thread between shader stages.
  37698. * Use this in compileAsync() to prevent blocking the main thread.
  37699. *
  37700. * @return {Promise<NodeBuilder>} A promise that resolves to this node builder.
  37701. */
  37702. async buildAsync() {
  37703. this.prebuild();
  37704. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  37705. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  37706. // generate() -> stage 3: generate shader
  37707. for ( const buildStage of defaultBuildStages ) {
  37708. this.setBuildStage( buildStage );
  37709. if ( this.context.position && this.context.position.isNode ) {
  37710. this.flowNodeFromShaderStage( 'vertex', this.context.position );
  37711. }
  37712. for ( const shaderStage of shaderStages ) {
  37713. this.setShaderStage( shaderStage );
  37714. const flowNodes = this.flowNodes[ shaderStage ];
  37715. for ( const node of flowNodes ) {
  37716. if ( buildStage === 'generate' ) {
  37717. this.flowNode( node );
  37718. } else {
  37719. node.build( this );
  37720. }
  37721. }
  37722. // Yield to main thread after each shader stage to prevent blocking
  37723. await yieldToMain();
  37724. }
  37725. }
  37726. this.setBuildStage( null );
  37727. this.setShaderStage( null );
  37728. // stage 4: build code for a specific output
  37729. this.buildCode();
  37730. this.buildUpdateNodes();
  37731. return this;
  37732. }
  37733. /**
  37734. * Returns shared data object for the given node.
  37735. *
  37736. * @param {Node} node - The node to get shared data from.
  37737. * @return {Object} The shared data.
  37738. */
  37739. getSharedDataFromNode( node ) {
  37740. let data = sharedNodeData.get( node );
  37741. if ( data === undefined ) {
  37742. data = {};
  37743. }
  37744. return data;
  37745. }
  37746. /**
  37747. * Returns a uniform representation which is later used for UBO generation and rendering.
  37748. *
  37749. * @param {NodeUniform} uniformNode - The uniform node.
  37750. * @param {string} type - The requested type.
  37751. * @return {Uniform} The uniform.
  37752. */
  37753. getNodeUniform( uniformNode, type ) {
  37754. const nodeData = this.getSharedDataFromNode( uniformNode );
  37755. let node = nodeData.cache;
  37756. if ( node === undefined ) {
  37757. if ( type === 'float' || type === 'int' || type === 'uint' ) node = new NumberNodeUniform( uniformNode );
  37758. else if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) node = new Vector2NodeUniform( uniformNode );
  37759. else if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) node = new Vector3NodeUniform( uniformNode );
  37760. else if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) node = new Vector4NodeUniform( uniformNode );
  37761. else if ( type === 'color' ) node = new ColorNodeUniform( uniformNode );
  37762. else if ( type === 'mat2' ) node = new Matrix2NodeUniform( uniformNode );
  37763. else if ( type === 'mat3' ) node = new Matrix3NodeUniform( uniformNode );
  37764. else if ( type === 'mat4' ) node = new Matrix4NodeUniform( uniformNode );
  37765. else {
  37766. throw new Error( `Uniform "${ type }" not implemented.` );
  37767. }
  37768. nodeData.cache = node;
  37769. }
  37770. return node;
  37771. }
  37772. /**
  37773. * Formats the given shader snippet from a given type into another one. E.g.
  37774. * this method might be used to convert a simple float string `"1.0"` into a
  37775. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  37776. *
  37777. * @param {string} snippet - The shader snippet.
  37778. * @param {string} fromType - The source type.
  37779. * @param {string} toType - The target type.
  37780. * @return {string} The updated shader string.
  37781. */
  37782. format( snippet, fromType, toType ) {
  37783. fromType = this.getVectorType( fromType );
  37784. toType = this.getVectorType( toType );
  37785. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  37786. return snippet;
  37787. }
  37788. const fromTypeLength = this.getTypeLength( fromType );
  37789. const toTypeLength = this.getTypeLength( toType );
  37790. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  37791. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  37792. }
  37793. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  37794. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  37795. }
  37796. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  37797. // @TODO: ignore for now
  37798. return snippet;
  37799. }
  37800. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  37801. // @TODO: ignore for now
  37802. return snippet;
  37803. }
  37804. if ( fromTypeLength === toTypeLength ) {
  37805. return `${ this.getType( toType ) }( ${ snippet } )`;
  37806. }
  37807. if ( fromTypeLength > toTypeLength ) {
  37808. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  37809. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  37810. }
  37811. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  37812. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  37813. }
  37814. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  37815. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  37816. }
  37817. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  37818. // convert a number value to vector type, e.g:
  37819. // vec3( 1u ) -> vec3( float( 1u ) )
  37820. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  37821. }
  37822. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  37823. }
  37824. /**
  37825. * Returns a signature with the engine's current revision.
  37826. *
  37827. * @return {string} The signature.
  37828. */
  37829. getSignature() {
  37830. return `// Three.js r${ REVISION } - Node System\n`;
  37831. }
  37832. /**
  37833. * Returns `true` if data from the previous frame are required. Relevant
  37834. * when computing motion vectors with {@link VelocityNode}.
  37835. *
  37836. * @return {boolean} Whether data from the previous frame are required or not.
  37837. */
  37838. needsPreviousData() {
  37839. const mrt = this.renderer.getMRT();
  37840. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( this.object ).useVelocity === true;
  37841. }
  37842. }
  37843. /**
  37844. * Management class for updating nodes. The module tracks metrics like
  37845. * the elapsed time, delta time, the render and frame ID to correctly
  37846. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  37847. * and {@link Node#updateAfter} depending on the node's configuration.
  37848. */
  37849. class NodeFrame {
  37850. /**
  37851. * Constructs a new node fame.
  37852. */
  37853. constructor() {
  37854. /**
  37855. * The elapsed time in seconds.
  37856. *
  37857. * @type {number}
  37858. * @default 0
  37859. */
  37860. this.time = 0;
  37861. /**
  37862. * The delta time in seconds.
  37863. *
  37864. * @type {number}
  37865. * @default 0
  37866. */
  37867. this.deltaTime = 0;
  37868. /**
  37869. * The frame ID.
  37870. *
  37871. * @type {number}
  37872. * @default 0
  37873. */
  37874. this.frameId = 0;
  37875. /**
  37876. * The render ID.
  37877. *
  37878. * @type {number}
  37879. * @default 0
  37880. */
  37881. this.renderId = 0;
  37882. /**
  37883. * Used to control the {@link Node#update} call.
  37884. *
  37885. * @type {WeakMap<Node, Object>}
  37886. */
  37887. this.updateMap = new WeakMap();
  37888. /**
  37889. * Used to control the {@link Node#updateBefore} call.
  37890. *
  37891. * @type {WeakMap<Node, Object>}
  37892. */
  37893. this.updateBeforeMap = new WeakMap();
  37894. /**
  37895. * Used to control the {@link Node#updateAfter} call.
  37896. *
  37897. * @type {WeakMap<Node, Object>}
  37898. */
  37899. this.updateAfterMap = new WeakMap();
  37900. /**
  37901. * A reference to the current renderer.
  37902. *
  37903. * @type {?Renderer}
  37904. * @default null
  37905. */
  37906. this.renderer = null;
  37907. /**
  37908. * A reference to the current material.
  37909. *
  37910. * @type {?Material}
  37911. * @default null
  37912. */
  37913. this.material = null;
  37914. /**
  37915. * A reference to the current camera.
  37916. *
  37917. * @type {?Camera}
  37918. * @default null
  37919. */
  37920. this.camera = null;
  37921. /**
  37922. * A reference to the current 3D object.
  37923. *
  37924. * @type {?Object3D}
  37925. * @default null
  37926. */
  37927. this.object = null;
  37928. /**
  37929. * A reference to the current scene.
  37930. *
  37931. * @type {?Scene}
  37932. * @default null
  37933. */
  37934. this.scene = null;
  37935. }
  37936. /**
  37937. * Returns a dictionary for a given node and update map which
  37938. * is used to correctly call node update methods per frame or render.
  37939. *
  37940. * @private
  37941. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  37942. * @param {Node} nodeRef - The reference to the current node.
  37943. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  37944. */
  37945. _getMaps( referenceMap, nodeRef ) {
  37946. let maps = referenceMap.get( nodeRef );
  37947. if ( maps === undefined ) {
  37948. maps = {
  37949. renderId: 0,
  37950. frameId: 0,
  37951. };
  37952. referenceMap.set( nodeRef, maps );
  37953. }
  37954. return maps;
  37955. }
  37956. /**
  37957. * This method executes the {@link Node#updateBefore} for the given node.
  37958. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  37959. * is only executed once per frame, render or object depending on the update
  37960. * type.
  37961. *
  37962. * @param {Node} node - The node that should be updated.
  37963. */
  37964. updateBeforeNode( node ) {
  37965. const updateType = node.getUpdateBeforeType();
  37966. const reference = node.updateReference( this );
  37967. if ( updateType === NodeUpdateType.FRAME ) {
  37968. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37969. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  37970. const previousFrameId = nodeUpdateBeforeMap.frameId;
  37971. nodeUpdateBeforeMap.frameId = this.frameId;
  37972. if ( node.updateBefore( this ) === false ) {
  37973. nodeUpdateBeforeMap.frameId = previousFrameId;
  37974. }
  37975. }
  37976. } else if ( updateType === NodeUpdateType.RENDER ) {
  37977. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37978. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  37979. const previousRenderId = nodeUpdateBeforeMap.renderId;
  37980. nodeUpdateBeforeMap.renderId = this.renderId;
  37981. if ( node.updateBefore( this ) === false ) {
  37982. nodeUpdateBeforeMap.renderId = previousRenderId;
  37983. }
  37984. }
  37985. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37986. node.updateBefore( this );
  37987. }
  37988. }
  37989. /**
  37990. * This method executes the {@link Node#updateAfter} for the given node.
  37991. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  37992. * is only executed once per frame, render or object depending on the update
  37993. * type.
  37994. *
  37995. * @param {Node} node - The node that should be updated.
  37996. */
  37997. updateAfterNode( node ) {
  37998. const updateType = node.getUpdateAfterType();
  37999. const reference = node.updateReference( this );
  38000. if ( updateType === NodeUpdateType.FRAME ) {
  38001. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  38002. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  38003. if ( node.updateAfter( this ) !== false ) {
  38004. nodeUpdateAfterMap.frameId = this.frameId;
  38005. }
  38006. }
  38007. } else if ( updateType === NodeUpdateType.RENDER ) {
  38008. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  38009. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  38010. if ( node.updateAfter( this ) !== false ) {
  38011. nodeUpdateAfterMap.renderId = this.renderId;
  38012. }
  38013. }
  38014. } else if ( updateType === NodeUpdateType.OBJECT ) {
  38015. node.updateAfter( this );
  38016. }
  38017. }
  38018. /**
  38019. * This method executes the {@link Node#update} for the given node.
  38020. * It makes sure {@link Node#updateType} is honored meaning the update
  38021. * is only executed once per frame, render or object depending on the update
  38022. * type.
  38023. *
  38024. * @param {Node} node - The node that should be updated.
  38025. */
  38026. updateNode( node ) {
  38027. const updateType = node.getUpdateType();
  38028. const reference = node.updateReference( this );
  38029. if ( updateType === NodeUpdateType.FRAME ) {
  38030. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  38031. if ( nodeUpdateMap.frameId !== this.frameId ) {
  38032. if ( node.update( this ) !== false ) {
  38033. nodeUpdateMap.frameId = this.frameId;
  38034. }
  38035. }
  38036. } else if ( updateType === NodeUpdateType.RENDER ) {
  38037. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  38038. if ( nodeUpdateMap.renderId !== this.renderId ) {
  38039. if ( node.update( this ) !== false ) {
  38040. nodeUpdateMap.renderId = this.renderId;
  38041. }
  38042. }
  38043. } else if ( updateType === NodeUpdateType.OBJECT ) {
  38044. node.update( this );
  38045. }
  38046. }
  38047. /**
  38048. * Updates the internal state of the node frame. This method is
  38049. * called by the renderer in its internal animation loop.
  38050. */
  38051. update() {
  38052. this.frameId ++;
  38053. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  38054. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  38055. this.lastTime = performance.now();
  38056. this.time += this.deltaTime;
  38057. }
  38058. }
  38059. /**
  38060. * Describes the input of a {@link NodeFunction}.
  38061. */
  38062. class NodeFunctionInput {
  38063. /**
  38064. * Constructs a new node function input.
  38065. *
  38066. * @param {string} type - The input type.
  38067. * @param {string} name - The input name.
  38068. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  38069. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  38070. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  38071. */
  38072. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  38073. /**
  38074. * The input type.
  38075. *
  38076. * @type {string}
  38077. */
  38078. this.type = type;
  38079. /**
  38080. * The input name.
  38081. *
  38082. * @type {string}
  38083. */
  38084. this.name = name;
  38085. /**
  38086. * If the input is an Array, count will be the length.
  38087. *
  38088. * @type {?number}
  38089. * @default null
  38090. */
  38091. this.count = count;
  38092. /**
  38093. *The parameter qualifier (only relevant for GLSL).
  38094. *
  38095. * @type {('in'|'out'|'inout')}
  38096. * @default ''
  38097. */
  38098. this.qualifier = qualifier;
  38099. /**
  38100. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  38101. *
  38102. * @type {boolean}
  38103. * @default false
  38104. */
  38105. this.isConst = isConst;
  38106. }
  38107. }
  38108. NodeFunctionInput.isNodeFunctionInput = true;
  38109. /**
  38110. * Module for representing ambient lights as nodes.
  38111. *
  38112. * @augments AnalyticLightNode
  38113. */
  38114. class AmbientLightNode extends AnalyticLightNode {
  38115. static get type() {
  38116. return 'AmbientLightNode';
  38117. }
  38118. /**
  38119. * Constructs a new ambient light node.
  38120. *
  38121. * @param {?AmbientLight} [light=null] - The ambient light source.
  38122. */
  38123. constructor( light = null ) {
  38124. super( light );
  38125. }
  38126. setup( { context } ) {
  38127. context.irradiance.addAssign( this.colorNode );
  38128. }
  38129. }
  38130. /**
  38131. * Module for representing directional lights as nodes.
  38132. *
  38133. * @augments AnalyticLightNode
  38134. */
  38135. class DirectionalLightNode extends AnalyticLightNode {
  38136. static get type() {
  38137. return 'DirectionalLightNode';
  38138. }
  38139. /**
  38140. * Constructs a new directional light node.
  38141. *
  38142. * @param {?DirectionalLight} [light=null] - The directional light source.
  38143. */
  38144. constructor( light = null ) {
  38145. super( light );
  38146. }
  38147. setupDirect() {
  38148. const lightColor = this.colorNode;
  38149. const lightDirection = lightTargetDirection( this.light );
  38150. return { lightDirection, lightColor };
  38151. }
  38152. }
  38153. /**
  38154. * Module for representing hemisphere lights as nodes.
  38155. *
  38156. * @augments AnalyticLightNode
  38157. */
  38158. class HemisphereLightNode extends AnalyticLightNode {
  38159. static get type() {
  38160. return 'HemisphereLightNode';
  38161. }
  38162. /**
  38163. * Constructs a new hemisphere light node.
  38164. *
  38165. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  38166. */
  38167. constructor( light = null ) {
  38168. super( light );
  38169. /**
  38170. * Uniform node representing the light's position.
  38171. *
  38172. * @type {UniformNode<vec3>}
  38173. */
  38174. this.lightPositionNode = lightPosition( light );
  38175. /**
  38176. * A node representing the light's direction.
  38177. *
  38178. * @type {Node<vec3>}
  38179. */
  38180. this.lightDirectionNode = this.lightPositionNode.normalize();
  38181. /**
  38182. * Uniform node representing the light's ground color.
  38183. *
  38184. * @type {UniformNode<vec3>}
  38185. */
  38186. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  38187. }
  38188. /**
  38189. * Overwritten to updated hemisphere light specific uniforms.
  38190. *
  38191. * @param {NodeFrame} frame - A reference to the current node frame.
  38192. */
  38193. update( frame ) {
  38194. const { light } = this;
  38195. super.update( frame );
  38196. this.lightPositionNode.object3d = light;
  38197. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  38198. }
  38199. setup( builder ) {
  38200. const { colorNode, groundColorNode, lightDirectionNode } = this;
  38201. const dotNL = normalWorld.dot( lightDirectionNode );
  38202. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  38203. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  38204. builder.context.irradiance.addAssign( irradiance );
  38205. }
  38206. }
  38207. /**
  38208. * Module for representing spot lights as nodes.
  38209. *
  38210. * @augments AnalyticLightNode
  38211. */
  38212. class SpotLightNode extends AnalyticLightNode {
  38213. static get type() {
  38214. return 'SpotLightNode';
  38215. }
  38216. /**
  38217. * Constructs a new spot light node.
  38218. *
  38219. * @param {?SpotLight} [light=null] - The spot light source.
  38220. */
  38221. constructor( light = null ) {
  38222. super( light );
  38223. /**
  38224. * Uniform node representing the cone cosine.
  38225. *
  38226. * @type {UniformNode<float>}
  38227. */
  38228. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  38229. /**
  38230. * Uniform node representing the penumbra cosine.
  38231. *
  38232. * @type {UniformNode<float>}
  38233. */
  38234. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  38235. /**
  38236. * Uniform node representing the cutoff distance.
  38237. *
  38238. * @type {UniformNode<float>}
  38239. */
  38240. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  38241. /**
  38242. * Uniform node representing the decay exponent.
  38243. *
  38244. * @type {UniformNode<float>}
  38245. */
  38246. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  38247. /**
  38248. * Uniform node representing the light color.
  38249. *
  38250. * @type {UniformNode<Color>}
  38251. */
  38252. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  38253. }
  38254. /**
  38255. * Overwritten to updated spot light specific uniforms.
  38256. *
  38257. * @param {NodeFrame} frame - A reference to the current node frame.
  38258. */
  38259. update( frame ) {
  38260. super.update( frame );
  38261. const { light } = this;
  38262. this.coneCosNode.value = Math.cos( light.angle );
  38263. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  38264. this.cutoffDistanceNode.value = light.distance;
  38265. this.decayExponentNode.value = light.decay;
  38266. }
  38267. /**
  38268. * Computes the spot attenuation for the given angle.
  38269. *
  38270. * @param {NodeBuilder} builder - The node builder.
  38271. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  38272. * @return {Node<float>} The spot attenuation.
  38273. */
  38274. getSpotAttenuation( builder, angleCosine ) {
  38275. const { coneCosNode, penumbraCosNode } = this;
  38276. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  38277. }
  38278. getLightCoord( builder ) {
  38279. const properties = builder.getNodeProperties( this );
  38280. let projectionUV = properties.projectionUV;
  38281. if ( projectionUV === undefined ) {
  38282. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  38283. properties.projectionUV = projectionUV;
  38284. }
  38285. return projectionUV;
  38286. }
  38287. setupDirect( builder ) {
  38288. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  38289. const lightVector = this.getLightVector( builder );
  38290. const lightDirection = lightVector.normalize();
  38291. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  38292. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  38293. const lightDistance = lightVector.length();
  38294. const lightAttenuation = getDistanceAttenuation( {
  38295. lightDistance,
  38296. cutoffDistance: cutoffDistanceNode,
  38297. decayExponent: decayExponentNode
  38298. } );
  38299. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  38300. let projected, lightCoord;
  38301. if ( light.colorNode ) {
  38302. lightCoord = this.getLightCoord( builder );
  38303. projected = light.colorNode( lightCoord );
  38304. } else if ( light.map ) {
  38305. lightCoord = this.getLightCoord( builder );
  38306. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  38307. }
  38308. if ( projected ) {
  38309. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  38310. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  38311. }
  38312. return { lightColor, lightDirection };
  38313. }
  38314. }
  38315. /**
  38316. * An IES version of the default spot light node.
  38317. *
  38318. * @augments SpotLightNode
  38319. */
  38320. class IESSpotLightNode extends SpotLightNode {
  38321. static get type() {
  38322. return 'IESSpotLightNode';
  38323. }
  38324. /**
  38325. * Overwrites the default implementation to compute an IES conform spot attenuation.
  38326. *
  38327. * @param {NodeBuilder} builder - The node builder.
  38328. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  38329. * @return {Node<float>} The spot attenuation.
  38330. */
  38331. getSpotAttenuation( builder, angleCosine ) {
  38332. const iesMap = this.light.iesMap;
  38333. let spotAttenuation = null;
  38334. if ( iesMap && iesMap.isTexture === true ) {
  38335. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  38336. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  38337. } else {
  38338. spotAttenuation = super.getSpotAttenuation( angleCosine );
  38339. }
  38340. return spotAttenuation;
  38341. }
  38342. }
  38343. /**
  38344. * Module for representing light probes as nodes.
  38345. *
  38346. * @augments AnalyticLightNode
  38347. */
  38348. class LightProbeNode extends AnalyticLightNode {
  38349. static get type() {
  38350. return 'LightProbeNode';
  38351. }
  38352. /**
  38353. * Constructs a new light probe node.
  38354. *
  38355. * @param {?LightProbe} [light=null] - The light probe.
  38356. */
  38357. constructor( light = null ) {
  38358. super( light );
  38359. const array = [];
  38360. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  38361. /**
  38362. * Light probe represented as a uniform of spherical harmonics.
  38363. *
  38364. * @type {UniformArrayNode}
  38365. */
  38366. this.lightProbe = uniformArray( array );
  38367. }
  38368. /**
  38369. * Overwritten to updated light probe specific uniforms.
  38370. *
  38371. * @param {NodeFrame} frame - A reference to the current node frame.
  38372. */
  38373. update( frame ) {
  38374. const { light } = this;
  38375. super.update( frame );
  38376. //
  38377. for ( let i = 0; i < 9; i ++ ) {
  38378. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  38379. }
  38380. }
  38381. setup( builder ) {
  38382. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  38383. builder.context.irradiance.addAssign( irradiance );
  38384. }
  38385. }
  38386. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  38387. const d = p.abs().sub( b );
  38388. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  38389. } );
  38390. /**
  38391. * An implementation of a projector light node.
  38392. *
  38393. * @augments SpotLightNode
  38394. */
  38395. class ProjectorLightNode extends SpotLightNode {
  38396. static get type() {
  38397. return 'ProjectorLightNode';
  38398. }
  38399. update( frame ) {
  38400. super.update( frame );
  38401. const light = this.light;
  38402. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  38403. if ( light.aspect === null ) {
  38404. let aspect = 1;
  38405. if ( light.map !== null ) {
  38406. aspect = light.map.width / light.map.height;
  38407. }
  38408. light.shadow.aspect = aspect;
  38409. } else {
  38410. light.shadow.aspect = light.aspect;
  38411. }
  38412. }
  38413. /**
  38414. * Overwrites the default implementation to compute projection attenuation.
  38415. *
  38416. * @param {NodeBuilder} builder - The node builder.
  38417. * @return {Node<float>} The spot attenuation.
  38418. */
  38419. getSpotAttenuation( builder ) {
  38420. const attenuation = float( 0 );
  38421. const penumbraCos = this.penumbraCosNode;
  38422. // compute the fragment's position in the light's clip space
  38423. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  38424. // the sign of w determines whether the current fragment is in front or behind the light.
  38425. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  38426. If( spotLightCoord.w.greaterThan( 0 ), () => {
  38427. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  38428. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  38429. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  38430. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  38431. } );
  38432. return attenuation;
  38433. }
  38434. }
  38435. const _matrix41 = /*@__PURE__*/ new Matrix4();
  38436. const _matrix42 = /*@__PURE__*/ new Matrix4();
  38437. let _ltcLib = null;
  38438. /**
  38439. * Module for representing rect area lights as nodes.
  38440. *
  38441. * @augments AnalyticLightNode
  38442. */
  38443. class RectAreaLightNode extends AnalyticLightNode {
  38444. static get type() {
  38445. return 'RectAreaLightNode';
  38446. }
  38447. /**
  38448. * Constructs a new rect area light node.
  38449. *
  38450. * @param {?RectAreaLight} [light=null] - The rect area light source.
  38451. */
  38452. constructor( light = null ) {
  38453. super( light );
  38454. /**
  38455. * Uniform node representing the half height of the are light.
  38456. *
  38457. * @type {UniformNode<vec3>}
  38458. */
  38459. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  38460. /**
  38461. * Uniform node representing the half width of the are light.
  38462. *
  38463. * @type {UniformNode<vec3>}
  38464. */
  38465. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  38466. /**
  38467. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  38468. * relies on `viewMatrix` which might vary per render call.
  38469. *
  38470. * @type {string}
  38471. * @default 'render'
  38472. */
  38473. this.updateType = NodeUpdateType.RENDER;
  38474. }
  38475. /**
  38476. * Overwritten to updated rect area light specific uniforms.
  38477. *
  38478. * @param {NodeFrame} frame - A reference to the current node frame.
  38479. */
  38480. update( frame ) {
  38481. super.update( frame );
  38482. const { light } = this;
  38483. const viewMatrix = frame.camera.matrixWorldInverse;
  38484. _matrix42.identity();
  38485. _matrix41.copy( light.matrixWorld );
  38486. _matrix41.premultiply( viewMatrix );
  38487. _matrix42.extractRotation( _matrix41 );
  38488. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  38489. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  38490. this.halfWidth.value.applyMatrix4( _matrix42 );
  38491. this.halfHeight.value.applyMatrix4( _matrix42 );
  38492. }
  38493. setupDirectRectArea( builder ) {
  38494. let ltc_1, ltc_2;
  38495. if ( builder.isAvailable( 'float32Filterable' ) ) {
  38496. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  38497. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  38498. } else {
  38499. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  38500. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  38501. }
  38502. const { colorNode, light } = this;
  38503. const lightPosition = lightViewPosition( light );
  38504. return {
  38505. lightColor: colorNode,
  38506. lightPosition,
  38507. halfWidth: this.halfWidth,
  38508. halfHeight: this.halfHeight,
  38509. ltc_1,
  38510. ltc_2
  38511. };
  38512. }
  38513. /**
  38514. * Used to configure the internal BRDF approximation texture data.
  38515. *
  38516. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  38517. */
  38518. static setLTC( ltc ) {
  38519. _ltcLib = ltc;
  38520. }
  38521. }
  38522. /**
  38523. * Base class for node parsers. A derived parser must be implemented
  38524. * for each supported native shader language.
  38525. */
  38526. class NodeParser {
  38527. /**
  38528. * The method parses the given native code an returns a node function.
  38529. *
  38530. * @abstract
  38531. * @param {string} source - The native shader code.
  38532. * @return {NodeFunction} A node function.
  38533. */
  38534. parseFunction( /*source*/ ) {
  38535. warn( 'Abstract function.' );
  38536. }
  38537. }
  38538. /**
  38539. * Base class for node functions. A derived module must be implemented
  38540. * for each supported native shader language. Similar to other `Node*` modules,
  38541. * this class is only relevant during the building process and not used
  38542. * in user-level code.
  38543. */
  38544. class NodeFunction {
  38545. /**
  38546. * Constructs a new node function.
  38547. *
  38548. * @param {string} type - The node type. This type is the return type of the node function.
  38549. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  38550. * @param {string} [name=''] - The function's name.
  38551. * @param {string} [precision=''] - The precision qualifier.
  38552. */
  38553. constructor( type, inputs, name = '', precision = '' ) {
  38554. /**
  38555. * The node type. This type is the return type of the node function.
  38556. *
  38557. * @type {string}
  38558. */
  38559. this.type = type;
  38560. /**
  38561. * The function's inputs.
  38562. *
  38563. * @type {Array<NodeFunctionInput>}
  38564. */
  38565. this.inputs = inputs;
  38566. /**
  38567. * The name of the uniform.
  38568. *
  38569. * @type {string}
  38570. * @default ''
  38571. */
  38572. this.name = name;
  38573. /**
  38574. * The precision qualifier.
  38575. *
  38576. * @type {string}
  38577. * @default ''
  38578. */
  38579. this.precision = precision;
  38580. }
  38581. /**
  38582. * This method returns the native code of the node function.
  38583. *
  38584. * @abstract
  38585. * @param {string} name - The function's name.
  38586. * @return {string} A shader code.
  38587. */
  38588. getCode( /*name = this.name*/ ) {
  38589. warn( 'Abstract function.' );
  38590. }
  38591. }
  38592. NodeFunction.isNodeFunction = true;
  38593. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  38594. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  38595. const pragmaMain = '#pragma main';
  38596. const parse$1 = ( source ) => {
  38597. source = source.trim();
  38598. const pragmaMainIndex = source.indexOf( pragmaMain );
  38599. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  38600. const declaration = mainCode.match( declarationRegexp$1 );
  38601. if ( declaration !== null && declaration.length === 5 ) {
  38602. // tokenizer
  38603. const inputsCode = declaration[ 4 ];
  38604. const propsMatches = [];
  38605. let nameMatch = null;
  38606. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  38607. propsMatches.push( nameMatch );
  38608. }
  38609. // parser
  38610. const inputs = [];
  38611. let i = 0;
  38612. while ( i < propsMatches.length ) {
  38613. const isConst = propsMatches[ i ][ 0 ] === 'const';
  38614. if ( isConst === true ) {
  38615. i ++;
  38616. }
  38617. let qualifier = propsMatches[ i ][ 0 ];
  38618. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  38619. i ++;
  38620. } else {
  38621. qualifier = '';
  38622. }
  38623. const type = propsMatches[ i ++ ][ 0 ];
  38624. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  38625. if ( Number.isNaN( count ) === false ) i ++;
  38626. else count = null;
  38627. const name = propsMatches[ i ++ ][ 0 ];
  38628. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  38629. }
  38630. //
  38631. const blockCode = mainCode.substring( declaration[ 0 ].length );
  38632. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  38633. const type = declaration[ 2 ];
  38634. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  38635. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  38636. return {
  38637. type,
  38638. inputs,
  38639. name,
  38640. precision,
  38641. inputsCode,
  38642. blockCode,
  38643. headerCode
  38644. };
  38645. } else {
  38646. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  38647. }
  38648. };
  38649. /**
  38650. * This class represents a GLSL node function.
  38651. *
  38652. * @augments NodeFunction
  38653. */
  38654. class GLSLNodeFunction extends NodeFunction {
  38655. /**
  38656. * Constructs a new GLSL node function.
  38657. *
  38658. * @param {string} source - The GLSL source.
  38659. */
  38660. constructor( source ) {
  38661. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  38662. super( type, inputs, name, precision );
  38663. this.inputsCode = inputsCode;
  38664. this.blockCode = blockCode;
  38665. this.headerCode = headerCode;
  38666. }
  38667. /**
  38668. * This method returns the GLSL code of the node function.
  38669. *
  38670. * @param {string} [name=this.name] - The function's name.
  38671. * @return {string} The shader code.
  38672. */
  38673. getCode( name = this.name ) {
  38674. let code;
  38675. const blockCode = this.blockCode;
  38676. if ( blockCode !== '' ) {
  38677. const { type, inputsCode, headerCode, precision } = this;
  38678. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  38679. if ( precision !== '' ) {
  38680. declarationCode = `${ precision } ${ declarationCode }`;
  38681. }
  38682. code = headerCode + declarationCode + blockCode;
  38683. } else {
  38684. // interface function
  38685. code = '';
  38686. }
  38687. return code;
  38688. }
  38689. }
  38690. /**
  38691. * A GLSL node parser.
  38692. *
  38693. * @augments NodeParser
  38694. */
  38695. class GLSLNodeParser extends NodeParser {
  38696. /**
  38697. * The method parses the given GLSL code an returns a node function.
  38698. *
  38699. * @param {string} source - The GLSL code.
  38700. * @return {GLSLNodeFunction} A node function.
  38701. */
  38702. parseFunction( source ) {
  38703. return new GLSLNodeFunction( source );
  38704. }
  38705. }
  38706. const _chainKeys$1 = [];
  38707. const _cacheKeyValues = [];
  38708. /**
  38709. * This renderer module manages node-related objects and is the
  38710. * primary interface between the renderer and the node system.
  38711. *
  38712. * @private
  38713. * @augments DataMap
  38714. */
  38715. class NodeManager extends DataMap {
  38716. /**
  38717. * Constructs a new nodes management component.
  38718. *
  38719. * @param {Renderer} renderer - The renderer.
  38720. * @param {Backend} backend - The renderer's backend.
  38721. */
  38722. constructor( renderer, backend ) {
  38723. super();
  38724. /**
  38725. * The renderer.
  38726. *
  38727. * @type {Renderer}
  38728. */
  38729. this.renderer = renderer;
  38730. /**
  38731. * The renderer's backend.
  38732. *
  38733. * @type {Backend}
  38734. */
  38735. this.backend = backend;
  38736. /**
  38737. * The node frame.
  38738. *
  38739. * @type {Renderer}
  38740. */
  38741. this.nodeFrame = new NodeFrame();
  38742. /**
  38743. * A cache for managing node builder states.
  38744. *
  38745. * @type {Map<number,NodeBuilderState>}
  38746. */
  38747. this.nodeBuilderCache = new Map();
  38748. /**
  38749. * A cache for managing data cache key data.
  38750. *
  38751. * @type {ChainMap}
  38752. */
  38753. this.callHashCache = new ChainMap();
  38754. /**
  38755. * A cache for managing node uniforms group data.
  38756. *
  38757. * @type {ChainMap}
  38758. */
  38759. this.groupsData = new ChainMap();
  38760. /**
  38761. * Queue for pending async builds to limit concurrent compilation.
  38762. *
  38763. * @private
  38764. * @type {Array<Function>}
  38765. */
  38766. this._buildQueue = [];
  38767. /**
  38768. * Whether an async build is currently in progress.
  38769. *
  38770. * @private
  38771. * @type {boolean}
  38772. */
  38773. this._buildInProgress = false;
  38774. /**
  38775. * A cache for managing node objects of
  38776. * scene properties like fog or environments.
  38777. *
  38778. * @type {Object<string,WeakMap>}
  38779. */
  38780. this.cacheLib = {};
  38781. }
  38782. /**
  38783. * Returns `true` if the given node uniforms group must be updated or not.
  38784. *
  38785. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  38786. * @return {boolean} Whether the node uniforms group requires an update or not.
  38787. */
  38788. updateGroup( nodeUniformsGroup ) {
  38789. const groupNode = nodeUniformsGroup.groupNode;
  38790. _chainKeys$1[ 0 ] = groupNode;
  38791. _chainKeys$1[ 1 ] = nodeUniformsGroup;
  38792. let groupData = this.groupsData.get( _chainKeys$1 );
  38793. if ( groupData === undefined ) this.groupsData.set( _chainKeys$1, groupData = {} );
  38794. _chainKeys$1[ 0 ] = null;
  38795. _chainKeys$1[ 1 ] = null;
  38796. if ( groupData.version !== groupNode.version ) {
  38797. groupData.version = groupNode.version;
  38798. return true;
  38799. }
  38800. return false;
  38801. }
  38802. /**
  38803. * Returns the cache key for the given render object.
  38804. *
  38805. * @param {RenderObject} renderObject - The render object.
  38806. * @return {number} The cache key.
  38807. */
  38808. getForRenderCacheKey( renderObject ) {
  38809. return renderObject.initialCacheKey;
  38810. }
  38811. /**
  38812. * Creates a node builder configured for the given render object and material.
  38813. *
  38814. * @private
  38815. * @param {RenderObject} renderObject - The render object.
  38816. * @param {Material} material - The material to use.
  38817. * @return {NodeBuilder} The configured node builder.
  38818. */
  38819. _createNodeBuilder( renderObject, material ) {
  38820. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  38821. nodeBuilder.scene = renderObject.scene;
  38822. nodeBuilder.material = material;
  38823. nodeBuilder.camera = renderObject.camera;
  38824. nodeBuilder.context.material = material;
  38825. nodeBuilder.lightsNode = renderObject.lightsNode;
  38826. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  38827. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  38828. nodeBuilder.clippingContext = renderObject.clippingContext;
  38829. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  38830. nodeBuilder.enableMultiview();
  38831. }
  38832. return nodeBuilder;
  38833. }
  38834. /**
  38835. * Returns a node builder state for the given render object.
  38836. *
  38837. * @param {RenderObject} renderObject - The render object.
  38838. * @param {boolean} [useAsync=false] - Whether to use async build with yielding.
  38839. * @return {NodeBuilderState|Promise<NodeBuilderState>} The node builder state (or Promise if async).
  38840. */
  38841. getForRender( renderObject, useAsync = false ) {
  38842. const renderObjectData = this.get( renderObject );
  38843. let nodeBuilderState = renderObjectData.nodeBuilderState;
  38844. if ( nodeBuilderState === undefined ) {
  38845. const { nodeBuilderCache } = this;
  38846. const cacheKey = this.getForRenderCacheKey( renderObject );
  38847. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  38848. if ( nodeBuilderState === undefined ) {
  38849. const buildNodeBuilder = async () => {
  38850. let nodeBuilder = this._createNodeBuilder( renderObject, renderObject.material );
  38851. try {
  38852. if ( useAsync ) {
  38853. await nodeBuilder.buildAsync();
  38854. } else {
  38855. nodeBuilder.build();
  38856. }
  38857. } catch ( e ) {
  38858. nodeBuilder = this._createNodeBuilder( renderObject, new NodeMaterial() );
  38859. if ( useAsync ) {
  38860. await nodeBuilder.buildAsync();
  38861. } else {
  38862. nodeBuilder.build();
  38863. }
  38864. error( 'TSL: ' + e );
  38865. }
  38866. return nodeBuilder;
  38867. };
  38868. if ( useAsync ) {
  38869. return buildNodeBuilder().then( ( nodeBuilder ) => {
  38870. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38871. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  38872. nodeBuilderState.usedTimes ++;
  38873. renderObjectData.nodeBuilderState = nodeBuilderState;
  38874. return nodeBuilderState;
  38875. } );
  38876. } else {
  38877. // Synchronous path - call buildNodeBuilder but don't await
  38878. let nodeBuilder = this._createNodeBuilder( renderObject, renderObject.material );
  38879. try {
  38880. nodeBuilder.build();
  38881. } catch ( e ) {
  38882. nodeBuilder = this._createNodeBuilder( renderObject, new NodeMaterial() );
  38883. nodeBuilder.build();
  38884. let stackTrace = e.stackTrace;
  38885. if ( ! stackTrace && e.stack ) {
  38886. // Capture stack trace for JavaScript errors
  38887. stackTrace = new StackTrace( e.stack );
  38888. }
  38889. error( 'TSL: ' + e, stackTrace );
  38890. }
  38891. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38892. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  38893. }
  38894. }
  38895. nodeBuilderState.usedTimes ++;
  38896. renderObjectData.nodeBuilderState = nodeBuilderState;
  38897. }
  38898. return nodeBuilderState;
  38899. }
  38900. /**
  38901. * Async version of getForRender() that yields to main thread during build.
  38902. * Use this in compileAsync() to prevent blocking the main thread.
  38903. *
  38904. * @param {RenderObject} renderObject - The render object.
  38905. * @return {Promise<NodeBuilderState>} A promise that resolves to the node builder state.
  38906. */
  38907. getForRenderAsync( renderObject ) {
  38908. const result = this.getForRender( renderObject, true );
  38909. // Ensure we always return a Promise (cache hit returns nodeBuilderState directly)
  38910. if ( result.then ) {
  38911. return result;
  38912. }
  38913. return Promise.resolve( result );
  38914. }
  38915. /**
  38916. * Returns nodeBuilderState if ready, null if pending async build.
  38917. * Queues async build on first call for cache miss.
  38918. * Use this in render() path to enable non-blocking compilation.
  38919. *
  38920. * @param {RenderObject} renderObject - The render object.
  38921. * @return {?NodeBuilderState} The node builder state, or null if still building.
  38922. */
  38923. getForRenderDeferred( renderObject ) {
  38924. const renderObjectData = this.get( renderObject );
  38925. // Already built for this renderObject
  38926. if ( renderObjectData.nodeBuilderState !== undefined ) {
  38927. return renderObjectData.nodeBuilderState;
  38928. }
  38929. // Check cache with stable key
  38930. const cacheKey = this.getForRenderCacheKey( renderObject );
  38931. const nodeBuilderState = this.nodeBuilderCache.get( cacheKey );
  38932. if ( nodeBuilderState !== undefined ) {
  38933. // Cache hit - use it
  38934. nodeBuilderState.usedTimes ++;
  38935. renderObjectData.nodeBuilderState = nodeBuilderState;
  38936. return nodeBuilderState;
  38937. }
  38938. // Cache miss - check if async build already queued
  38939. if ( renderObjectData.pendingBuild !== true ) {
  38940. // Mark as pending and add to build queue
  38941. renderObjectData.pendingBuild = true;
  38942. this._buildQueue.push( () => {
  38943. return this.getForRenderAsync( renderObject ).then( () => {
  38944. renderObjectData.pendingBuild = false;
  38945. } );
  38946. } );
  38947. // Start processing queue if not already running
  38948. this._processBuildQueue();
  38949. }
  38950. return null; // Not ready
  38951. }
  38952. /**
  38953. * Processes the build queue one item at a time.
  38954. * This ensures builds don't all run simultaneously and freeze the main thread.
  38955. *
  38956. * @private
  38957. */
  38958. _processBuildQueue() {
  38959. if ( this._buildInProgress || this._buildQueue.length === 0 ) {
  38960. return;
  38961. }
  38962. this._buildInProgress = true;
  38963. const buildFn = this._buildQueue.shift();
  38964. buildFn().then( () => {
  38965. this._buildInProgress = false;
  38966. // Process next item in queue
  38967. this._processBuildQueue();
  38968. } );
  38969. }
  38970. /**
  38971. * Deletes the given object from the internal data map
  38972. *
  38973. * @param {any} object - The object to delete.
  38974. * @return {?Object} The deleted dictionary.
  38975. */
  38976. delete( object ) {
  38977. if ( object.isRenderObject ) {
  38978. const nodeBuilderState = this.get( object ).nodeBuilderState;
  38979. if ( nodeBuilderState !== undefined ) {
  38980. nodeBuilderState.usedTimes --;
  38981. if ( nodeBuilderState.usedTimes === 0 ) {
  38982. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  38983. }
  38984. }
  38985. }
  38986. return super.delete( object );
  38987. }
  38988. /**
  38989. * Returns a node builder state for the given compute node.
  38990. *
  38991. * @param {Node} computeNode - The compute node.
  38992. * @return {NodeBuilderState} The node builder state.
  38993. */
  38994. getForCompute( computeNode ) {
  38995. const computeData = this.get( computeNode );
  38996. let nodeBuilderState = computeData.nodeBuilderState;
  38997. if ( nodeBuilderState === undefined ) {
  38998. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  38999. nodeBuilder.build();
  39000. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  39001. computeData.nodeBuilderState = nodeBuilderState;
  39002. }
  39003. return nodeBuilderState;
  39004. }
  39005. /**
  39006. * Creates a node builder state for the given node builder.
  39007. *
  39008. * @private
  39009. * @param {NodeBuilder} nodeBuilder - The node builder.
  39010. * @return {NodeBuilderState} The node builder state.
  39011. */
  39012. _createNodeBuilderState( nodeBuilder ) {
  39013. return new NodeBuilderState(
  39014. nodeBuilder.vertexShader,
  39015. nodeBuilder.fragmentShader,
  39016. nodeBuilder.computeShader,
  39017. nodeBuilder.getAttributesArray(),
  39018. nodeBuilder.getBindings(),
  39019. nodeBuilder.updateNodes,
  39020. nodeBuilder.updateBeforeNodes,
  39021. nodeBuilder.updateAfterNodes,
  39022. nodeBuilder.observer,
  39023. nodeBuilder.transforms
  39024. );
  39025. }
  39026. /**
  39027. * Returns an environment node for the current configured
  39028. * scene environment.
  39029. *
  39030. * @param {Scene} scene - The scene.
  39031. * @return {Node} A node representing the current scene environment.
  39032. */
  39033. getEnvironmentNode( scene ) {
  39034. this.updateEnvironment( scene );
  39035. let environmentNode = null;
  39036. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  39037. environmentNode = scene.environmentNode;
  39038. } else {
  39039. const sceneData = this.get( scene );
  39040. if ( sceneData.environmentNode ) {
  39041. environmentNode = sceneData.environmentNode;
  39042. }
  39043. }
  39044. return environmentNode;
  39045. }
  39046. /**
  39047. * Returns a background node for the current configured
  39048. * scene background.
  39049. *
  39050. * @param {Scene} scene - The scene.
  39051. * @return {Node} A node representing the current scene background.
  39052. */
  39053. getBackgroundNode( scene ) {
  39054. this.updateBackground( scene );
  39055. let backgroundNode = null;
  39056. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  39057. backgroundNode = scene.backgroundNode;
  39058. } else {
  39059. const sceneData = this.get( scene );
  39060. if ( sceneData.backgroundNode ) {
  39061. backgroundNode = sceneData.backgroundNode;
  39062. }
  39063. }
  39064. return backgroundNode;
  39065. }
  39066. /**
  39067. * Returns a fog node for the current configured scene fog.
  39068. *
  39069. * @param {Scene} scene - The scene.
  39070. * @return {Node} A node representing the current scene fog.
  39071. */
  39072. getFogNode( scene ) {
  39073. this.updateFog( scene );
  39074. return scene.fogNode || this.get( scene ).fogNode || null;
  39075. }
  39076. /**
  39077. * Returns a cache key for the given scene and lights node.
  39078. * This key is used by `RenderObject` as a part of the dynamic
  39079. * cache key (a key that must be checked every time the render
  39080. * objects is drawn).
  39081. *
  39082. * @param {Scene} scene - The scene.
  39083. * @param {LightsNode} lightsNode - The lights node.
  39084. * @return {number} The cache key.
  39085. */
  39086. getCacheKey( scene, lightsNode ) {
  39087. _chainKeys$1[ 0 ] = scene;
  39088. _chainKeys$1[ 1 ] = lightsNode;
  39089. const callId = this.renderer.info.calls;
  39090. const cacheKeyData = this.callHashCache.get( _chainKeys$1 ) || {};
  39091. if ( cacheKeyData.callId !== callId ) {
  39092. const environmentNode = this.getEnvironmentNode( scene );
  39093. const fogNode = this.getFogNode( scene );
  39094. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  39095. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  39096. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  39097. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  39098. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  39099. _cacheKeyValues.push( this.renderer.shadowMap.type );
  39100. cacheKeyData.callId = callId;
  39101. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  39102. this.callHashCache.set( _chainKeys$1, cacheKeyData );
  39103. _cacheKeyValues.length = 0;
  39104. }
  39105. _chainKeys$1[ 0 ] = null;
  39106. _chainKeys$1[ 1 ] = null;
  39107. return cacheKeyData.cacheKey;
  39108. }
  39109. /**
  39110. * A boolean that indicates whether tone mapping should be enabled
  39111. * or not.
  39112. *
  39113. * @type {boolean}
  39114. */
  39115. get isToneMappingState() {
  39116. return this.renderer.getRenderTarget() ? false : true;
  39117. }
  39118. /**
  39119. * If a scene background is configured, this method makes sure to
  39120. * represent the background with a corresponding node-based implementation.
  39121. *
  39122. * @param {Scene} scene - The scene.
  39123. */
  39124. updateBackground( scene ) {
  39125. const sceneData = this.get( scene );
  39126. const background = scene.background;
  39127. if ( background ) {
  39128. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  39129. if ( sceneData.background !== background || forceUpdate ) {
  39130. const backgroundNode = this.getCacheNode( 'background', background, () => {
  39131. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  39132. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  39133. return pmremTexture( background );
  39134. } else {
  39135. let envMap;
  39136. if ( background.isCubeTexture === true ) {
  39137. envMap = cubeTexture( background );
  39138. } else {
  39139. envMap = texture( background );
  39140. }
  39141. return cubeMapNode( envMap );
  39142. }
  39143. } else if ( background.isTexture === true ) {
  39144. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  39145. } else if ( background.isColor !== true ) {
  39146. error( 'WebGPUNodes: Unsupported background configuration.', background );
  39147. }
  39148. }, forceUpdate );
  39149. sceneData.backgroundNode = backgroundNode;
  39150. sceneData.background = background;
  39151. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  39152. }
  39153. } else if ( sceneData.backgroundNode ) {
  39154. delete sceneData.backgroundNode;
  39155. delete sceneData.background;
  39156. }
  39157. }
  39158. /**
  39159. * This method is part of the caching of nodes which are used to represents the
  39160. * scene's background, fog or environment.
  39161. *
  39162. * @param {string} type - The type of object to cache.
  39163. * @param {Object} object - The object.
  39164. * @param {Function} callback - A callback that produces a node representation for the given object.
  39165. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  39166. * @return {Node} The node representation.
  39167. */
  39168. getCacheNode( type, object, callback, forceUpdate = false ) {
  39169. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  39170. let node = nodeCache.get( object );
  39171. if ( node === undefined || forceUpdate ) {
  39172. node = callback();
  39173. nodeCache.set( object, node );
  39174. }
  39175. return node;
  39176. }
  39177. /**
  39178. * If a scene fog is configured, this method makes sure to
  39179. * represent the fog with a corresponding node-based implementation.
  39180. *
  39181. * @param {Scene} scene - The scene.
  39182. */
  39183. updateFog( scene ) {
  39184. const sceneData = this.get( scene );
  39185. const sceneFog = scene.fog;
  39186. if ( sceneFog ) {
  39187. if ( sceneData.fog !== sceneFog ) {
  39188. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  39189. if ( sceneFog.isFogExp2 ) {
  39190. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  39191. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  39192. return fog( color, densityFogFactor( density ) );
  39193. } else if ( sceneFog.isFog ) {
  39194. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  39195. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  39196. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  39197. return fog( color, rangeFogFactor( near, far ) );
  39198. } else {
  39199. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  39200. }
  39201. } );
  39202. sceneData.fogNode = fogNode;
  39203. sceneData.fog = sceneFog;
  39204. }
  39205. } else {
  39206. delete sceneData.fogNode;
  39207. delete sceneData.fog;
  39208. }
  39209. }
  39210. /**
  39211. * If a scene environment is configured, this method makes sure to
  39212. * represent the environment with a corresponding node-based implementation.
  39213. *
  39214. * @param {Scene} scene - The scene.
  39215. */
  39216. updateEnvironment( scene ) {
  39217. const sceneData = this.get( scene );
  39218. const environment = scene.environment;
  39219. if ( environment ) {
  39220. if ( sceneData.environment !== environment ) {
  39221. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  39222. if ( environment.isCubeTexture === true ) {
  39223. return cubeTexture( environment );
  39224. } else if ( environment.isTexture === true ) {
  39225. return texture( environment );
  39226. } else {
  39227. error( 'Nodes: Unsupported environment configuration.', environment );
  39228. }
  39229. } );
  39230. sceneData.environmentNode = environmentNode;
  39231. sceneData.environment = environment;
  39232. }
  39233. } else if ( sceneData.environmentNode ) {
  39234. delete sceneData.environmentNode;
  39235. delete sceneData.environment;
  39236. }
  39237. }
  39238. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  39239. const nodeFrame = this.nodeFrame;
  39240. nodeFrame.renderer = renderer;
  39241. nodeFrame.scene = scene;
  39242. nodeFrame.object = object;
  39243. nodeFrame.camera = camera;
  39244. nodeFrame.material = material;
  39245. return nodeFrame;
  39246. }
  39247. getNodeFrameForRender( renderObject ) {
  39248. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  39249. }
  39250. /**
  39251. * Returns the current output cache key.
  39252. *
  39253. * @return {string} The output cache key.
  39254. */
  39255. getOutputCacheKey() {
  39256. const renderer = this.renderer;
  39257. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  39258. }
  39259. /**
  39260. * Returns a node that represents the output configuration (tone mapping and
  39261. * color space) for the current target.
  39262. *
  39263. * @param {Texture} outputTarget - The output target.
  39264. * @return {Node} The output node.
  39265. */
  39266. getOutputNode( outputTarget ) {
  39267. const renderer = this.renderer;
  39268. const output = outputTarget.isArrayTexture ?
  39269. texture( outputTarget, screenUV ).depth( builtin( 'gl_ViewID_OVR' ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  39270. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  39271. return output;
  39272. }
  39273. /**
  39274. * Triggers the call of `updateBefore()` methods
  39275. * for all nodes of the given render object.
  39276. *
  39277. * @param {RenderObject} renderObject - The render object.
  39278. */
  39279. updateBefore( renderObject ) {
  39280. const nodeBuilder = renderObject.getNodeBuilderState();
  39281. for ( const node of nodeBuilder.updateBeforeNodes ) {
  39282. // update frame state for each node
  39283. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  39284. }
  39285. }
  39286. /**
  39287. * Triggers the call of `updateAfter()` methods
  39288. * for all nodes of the given render object.
  39289. *
  39290. * @param {RenderObject} renderObject - The render object.
  39291. */
  39292. updateAfter( renderObject ) {
  39293. const nodeBuilder = renderObject.getNodeBuilderState();
  39294. for ( const node of nodeBuilder.updateAfterNodes ) {
  39295. // update frame state for each node
  39296. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  39297. }
  39298. }
  39299. /**
  39300. * Triggers the call of `update()` methods
  39301. * for all nodes of the given compute node.
  39302. *
  39303. * @param {Node} computeNode - The compute node.
  39304. */
  39305. updateForCompute( computeNode ) {
  39306. const nodeFrame = this.getNodeFrame();
  39307. const nodeBuilder = this.getForCompute( computeNode );
  39308. for ( const node of nodeBuilder.updateNodes ) {
  39309. nodeFrame.updateNode( node );
  39310. }
  39311. }
  39312. /**
  39313. * Triggers the call of `update()` methods
  39314. * for all nodes of the given render object.
  39315. *
  39316. * @param {RenderObject} renderObject - The render object.
  39317. */
  39318. updateForRender( renderObject ) {
  39319. const nodeFrame = this.getNodeFrameForRender( renderObject );
  39320. const nodeBuilder = renderObject.getNodeBuilderState();
  39321. for ( const node of nodeBuilder.updateNodes ) {
  39322. nodeFrame.updateNode( node );
  39323. }
  39324. }
  39325. /**
  39326. * Returns `true` if the given render object requires a refresh.
  39327. *
  39328. * @param {RenderObject} renderObject - The render object.
  39329. * @return {boolean} Whether the given render object requires a refresh or not.
  39330. */
  39331. needsRefresh( renderObject ) {
  39332. const nodeFrame = this.getNodeFrameForRender( renderObject );
  39333. const monitor = renderObject.getMonitor();
  39334. return monitor.needsRefresh( renderObject, nodeFrame );
  39335. }
  39336. /**
  39337. * Frees the internal resources.
  39338. */
  39339. dispose() {
  39340. super.dispose();
  39341. this.nodeFrame = new NodeFrame();
  39342. this.nodeBuilderCache = new Map();
  39343. this.cacheLib = {};
  39344. }
  39345. }
  39346. const _plane = /*@__PURE__*/ new Plane();
  39347. /**
  39348. * Represents the state that is used to perform clipping via clipping planes.
  39349. * There is a default clipping context for each render context. When the
  39350. * scene holds instances of `ClippingGroup`, there will be a context for each
  39351. * group.
  39352. *
  39353. * @private
  39354. */
  39355. class ClippingContext {
  39356. /**
  39357. * Constructs a new clipping context.
  39358. *
  39359. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  39360. */
  39361. constructor( parentContext = null ) {
  39362. /**
  39363. * The clipping context's version.
  39364. *
  39365. * @type {number}
  39366. * @readonly
  39367. */
  39368. this.version = 0;
  39369. /**
  39370. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  39371. *
  39372. * @type {?boolean}
  39373. * @default null
  39374. */
  39375. this.clipIntersection = null;
  39376. /**
  39377. * The clipping context's cache key.
  39378. *
  39379. * @type {string}
  39380. */
  39381. this.cacheKey = '';
  39382. /**
  39383. * Whether the shadow pass is active or not.
  39384. *
  39385. * @type {boolean}
  39386. * @default false
  39387. */
  39388. this.shadowPass = false;
  39389. /**
  39390. * The view normal matrix.
  39391. *
  39392. * @type {Matrix3}
  39393. */
  39394. this.viewNormalMatrix = new Matrix3();
  39395. /**
  39396. * Internal cache for maintaining clipping contexts.
  39397. *
  39398. * @type {WeakMap<ClippingGroup,ClippingContext>}
  39399. */
  39400. this.clippingGroupContexts = new WeakMap();
  39401. /**
  39402. * The intersection planes.
  39403. *
  39404. * @type {Array<Vector4>}
  39405. */
  39406. this.intersectionPlanes = [];
  39407. /**
  39408. * The intersection planes.
  39409. *
  39410. * @type {Array<Vector4>}
  39411. */
  39412. this.unionPlanes = [];
  39413. /**
  39414. * The version of the clipping context's parent context.
  39415. *
  39416. * @type {?number}
  39417. * @readonly
  39418. */
  39419. this.parentVersion = null;
  39420. if ( parentContext !== null ) {
  39421. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  39422. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  39423. this.shadowPass = parentContext.shadowPass;
  39424. this.viewMatrix = parentContext.viewMatrix;
  39425. }
  39426. }
  39427. /**
  39428. * Projects the given source clipping planes and writes the result into the
  39429. * destination array.
  39430. *
  39431. * @param {Array<Plane>} source - The source clipping planes.
  39432. * @param {Array<Vector4>} destination - The destination.
  39433. * @param {number} offset - The offset.
  39434. */
  39435. projectPlanes( source, destination, offset ) {
  39436. const l = source.length;
  39437. for ( let i = 0; i < l; i ++ ) {
  39438. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  39439. const v = destination[ offset + i ];
  39440. const normal = _plane.normal;
  39441. v.x = - normal.x;
  39442. v.y = - normal.y;
  39443. v.z = - normal.z;
  39444. v.w = _plane.constant;
  39445. }
  39446. }
  39447. /**
  39448. * Updates the root clipping context of a scene.
  39449. *
  39450. * @param {Scene} scene - The scene.
  39451. * @param {Camera} camera - The camera that is used to render the scene.
  39452. */
  39453. updateGlobal( scene, camera ) {
  39454. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  39455. this.viewMatrix = camera.matrixWorldInverse;
  39456. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  39457. }
  39458. /**
  39459. * Updates the clipping context.
  39460. *
  39461. * @param {ClippingContext} parentContext - The parent context.
  39462. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  39463. */
  39464. update( parentContext, clippingGroup ) {
  39465. let update = false;
  39466. if ( parentContext.version !== this.parentVersion ) {
  39467. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  39468. this.unionPlanes = Array.from( parentContext.unionPlanes );
  39469. this.parentVersion = parentContext.version;
  39470. }
  39471. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  39472. this.clipIntersection = clippingGroup.clipIntersection;
  39473. if ( this.clipIntersection ) {
  39474. this.unionPlanes.length = parentContext.unionPlanes.length;
  39475. } else {
  39476. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  39477. }
  39478. }
  39479. const srcClippingPlanes = clippingGroup.clippingPlanes;
  39480. const l = srcClippingPlanes.length;
  39481. let dstClippingPlanes;
  39482. let offset;
  39483. if ( this.clipIntersection ) {
  39484. dstClippingPlanes = this.intersectionPlanes;
  39485. offset = parentContext.intersectionPlanes.length;
  39486. } else {
  39487. dstClippingPlanes = this.unionPlanes;
  39488. offset = parentContext.unionPlanes.length;
  39489. }
  39490. if ( dstClippingPlanes.length !== offset + l ) {
  39491. dstClippingPlanes.length = offset + l;
  39492. for ( let i = 0; i < l; i ++ ) {
  39493. dstClippingPlanes[ offset + i ] = new Vector4();
  39494. }
  39495. update = true;
  39496. }
  39497. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  39498. if ( update ) {
  39499. this.version ++;
  39500. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  39501. }
  39502. }
  39503. /**
  39504. * Returns a clipping context for the given clipping group.
  39505. *
  39506. * @param {ClippingGroup} clippingGroup - The clipping group.
  39507. * @return {ClippingContext} The clipping context.
  39508. */
  39509. getGroupContext( clippingGroup ) {
  39510. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  39511. let context = this.clippingGroupContexts.get( clippingGroup );
  39512. if ( context === undefined ) {
  39513. context = new ClippingContext( this );
  39514. this.clippingGroupContexts.set( clippingGroup, context );
  39515. }
  39516. context.update( this, clippingGroup );
  39517. return context;
  39518. }
  39519. /**
  39520. * The count of union clipping planes.
  39521. *
  39522. * @type {number}
  39523. * @readonly
  39524. */
  39525. get unionClippingCount() {
  39526. return this.unionPlanes.length;
  39527. }
  39528. }
  39529. /**
  39530. * This module is used to represent render bundles inside the renderer
  39531. * for further processing.
  39532. *
  39533. * @private
  39534. */
  39535. class RenderBundle {
  39536. /**
  39537. * Constructs a new bundle group.
  39538. *
  39539. * @param {BundleGroup} bundleGroup - The bundle group.
  39540. * @param {Camera} camera - The camera the bundle group is rendered with.
  39541. */
  39542. constructor( bundleGroup, camera ) {
  39543. this.bundleGroup = bundleGroup;
  39544. this.camera = camera;
  39545. }
  39546. }
  39547. const _chainKeys = [];
  39548. /**
  39549. * This renderer module manages render bundles.
  39550. *
  39551. * @private
  39552. */
  39553. class RenderBundles {
  39554. /**
  39555. * Constructs a new render bundle management component.
  39556. */
  39557. constructor() {
  39558. /**
  39559. * A chain map for maintaining the render bundles.
  39560. *
  39561. * @type {ChainMap}
  39562. */
  39563. this.bundles = new ChainMap();
  39564. }
  39565. /**
  39566. * Returns a render bundle for the given bundle group and camera.
  39567. *
  39568. * @param {BundleGroup} bundleGroup - The bundle group.
  39569. * @param {Camera} camera - The camera the bundle group is rendered with.
  39570. * @return {RenderBundle} The render bundle.
  39571. */
  39572. get( bundleGroup, camera ) {
  39573. const bundles = this.bundles;
  39574. _chainKeys[ 0 ] = bundleGroup;
  39575. _chainKeys[ 1 ] = camera;
  39576. let bundle = bundles.get( _chainKeys );
  39577. if ( bundle === undefined ) {
  39578. bundle = new RenderBundle( bundleGroup, camera );
  39579. bundles.set( _chainKeys, bundle );
  39580. }
  39581. _chainKeys[ 0 ] = null;
  39582. _chainKeys[ 1 ] = null;
  39583. return bundle;
  39584. }
  39585. /**
  39586. * Frees all internal resources.
  39587. */
  39588. dispose() {
  39589. this.bundles = new ChainMap();
  39590. }
  39591. }
  39592. /**
  39593. * The purpose of a node library is to assign node implementations
  39594. * to existing library features. In `WebGPURenderer` lights, materials
  39595. * which are not based on `NodeMaterial` as well as tone mapping techniques
  39596. * are implemented with node-based modules.
  39597. *
  39598. * @private
  39599. */
  39600. class NodeLibrary {
  39601. /**
  39602. * Constructs a new node library.
  39603. */
  39604. constructor() {
  39605. /**
  39606. * A weak map that maps lights to light nodes.
  39607. *
  39608. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  39609. */
  39610. this.lightNodes = new WeakMap();
  39611. /**
  39612. * A map that maps materials to node materials.
  39613. *
  39614. * @type {Map<string,NodeMaterial.constructor>}
  39615. */
  39616. this.materialNodes = new Map();
  39617. /**
  39618. * A map that maps tone mapping techniques (constants)
  39619. * to tone mapping node functions.
  39620. *
  39621. * @type {Map<number,Function>}
  39622. */
  39623. this.toneMappingNodes = new Map();
  39624. }
  39625. /**
  39626. * Returns a matching node material instance for the given material object.
  39627. *
  39628. * This method also assigns/copies the properties of the given material object
  39629. * to the node material. This is done to make sure the current material
  39630. * configuration carries over to the node version.
  39631. *
  39632. * @param {Material} material - A material.
  39633. * @return {NodeMaterial} The corresponding node material.
  39634. */
  39635. fromMaterial( material ) {
  39636. if ( material.isNodeMaterial ) return material;
  39637. let nodeMaterial = null;
  39638. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  39639. if ( nodeMaterialClass !== null ) {
  39640. nodeMaterial = new nodeMaterialClass();
  39641. for ( const key in material ) {
  39642. nodeMaterial[ key ] = material[ key ];
  39643. }
  39644. }
  39645. return nodeMaterial;
  39646. }
  39647. /**
  39648. * Adds a tone mapping node function for a tone mapping technique (constant).
  39649. *
  39650. * @param {Function} toneMappingNode - The tone mapping node function.
  39651. * @param {number} toneMapping - The tone mapping.
  39652. */
  39653. addToneMapping( toneMappingNode, toneMapping ) {
  39654. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  39655. }
  39656. /**
  39657. * Returns a tone mapping node function for a tone mapping technique (constant).
  39658. *
  39659. * @param {number} toneMapping - The tone mapping.
  39660. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  39661. */
  39662. getToneMappingFunction( toneMapping ) {
  39663. return this.toneMappingNodes.get( toneMapping ) || null;
  39664. }
  39665. /**
  39666. * Returns a node material class definition for a material type.
  39667. *
  39668. * @param {string} materialType - The material type.
  39669. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  39670. */
  39671. getMaterialNodeClass( materialType ) {
  39672. return this.materialNodes.get( materialType ) || null;
  39673. }
  39674. /**
  39675. * Adds a node material class definition for a given material type.
  39676. *
  39677. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  39678. * @param {string} materialClassType - The material type.
  39679. */
  39680. addMaterial( materialNodeClass, materialClassType ) {
  39681. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  39682. }
  39683. /**
  39684. * Returns a light node class definition for a light class definition.
  39685. *
  39686. * @param {Light.constructor} light - The light class definition.
  39687. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  39688. */
  39689. getLightNodeClass( light ) {
  39690. return this.lightNodes.get( light ) || null;
  39691. }
  39692. /**
  39693. * Adds a light node class definition for a given light class definition.
  39694. *
  39695. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  39696. * @param {Light.constructor} lightClass - The light class definition.
  39697. */
  39698. addLight( lightNodeClass, lightClass ) {
  39699. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  39700. }
  39701. /**
  39702. * Adds a node class definition for the given type to the provided type library.
  39703. *
  39704. * @param {Node.constructor} nodeClass - The node class definition.
  39705. * @param {number|string} type - The object type.
  39706. * @param {Map<number|string,Node.constructor>} library - The type library.
  39707. */
  39708. addType( nodeClass, type, library ) {
  39709. if ( library.has( type ) ) {
  39710. warn( `Redefinition of node ${ type }` );
  39711. return;
  39712. }
  39713. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39714. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  39715. library.set( type, nodeClass );
  39716. }
  39717. /**
  39718. * Adds a node class definition for the given class definition to the provided type library.
  39719. *
  39720. * @param {Node.constructor} nodeClass - The node class definition.
  39721. * @param {Node.constructor} baseClass - The class definition.
  39722. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  39723. */
  39724. addClass( nodeClass, baseClass, library ) {
  39725. if ( library.has( baseClass ) ) {
  39726. warn( `Redefinition of node ${ baseClass.name }` );
  39727. return;
  39728. }
  39729. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39730. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  39731. library.set( baseClass, nodeClass );
  39732. }
  39733. }
  39734. const _defaultLights = /*@__PURE__*/ new LightsNode();
  39735. const _weakMap = /*@__PURE__*/ new WeakMap();
  39736. /**
  39737. * This renderer module manages the lights nodes which are unique
  39738. * per scene and camera combination.
  39739. *
  39740. * The lights node itself is later configured in the render list
  39741. * with the actual lights from the scene.
  39742. *
  39743. * @private
  39744. */
  39745. class Lighting {
  39746. /**
  39747. * Creates a new lights node for the given array of lights.
  39748. *
  39749. * @param {Array<Light>} lights - The render object.
  39750. * @return {LightsNode} The lights node.
  39751. */
  39752. createNode( lights = [] ) {
  39753. return new LightsNode().setLights( lights );
  39754. }
  39755. /**
  39756. * Returns a lights node for the given scene and camera.
  39757. *
  39758. * @param {Scene} scene - The scene.
  39759. * @param {Camera} camera - The camera.
  39760. * @return {LightsNode} The lights node.
  39761. */
  39762. getNode( scene ) {
  39763. // ignore post-processing
  39764. if ( scene.isQuadMesh ) return _defaultLights;
  39765. let node = _weakMap.get( scene );
  39766. if ( node === undefined ) {
  39767. node = this.createNode();
  39768. _weakMap.set( scene, node );
  39769. }
  39770. return node;
  39771. }
  39772. }
  39773. /**
  39774. * A special type of render target that is used when rendering
  39775. * with the WebXR Device API.
  39776. *
  39777. * @private
  39778. * @augments RenderTarget
  39779. */
  39780. class XRRenderTarget extends RenderTarget {
  39781. /**
  39782. * Constructs a new XR render target.
  39783. *
  39784. * @param {number} [width=1] - The width of the render target.
  39785. * @param {number} [height=1] - The height of the render target.
  39786. * @param {Object} [options={}] - The configuration options.
  39787. */
  39788. constructor( width = 1, height = 1, options = {} ) {
  39789. super( width, height, options );
  39790. /**
  39791. * This flag can be used for type testing.
  39792. *
  39793. * @type {boolean}
  39794. * @readonly
  39795. * @default true
  39796. */
  39797. this.isXRRenderTarget = true;
  39798. /**
  39799. * Whether the attachments of the render target
  39800. * are defined by external textures. This flag is
  39801. * set to `true` when using the WebXR Layers API.
  39802. *
  39803. * @private
  39804. * @type {boolean}
  39805. * @default false
  39806. */
  39807. this._hasExternalTextures = false;
  39808. /**
  39809. * Whether a depth buffer should automatically be allocated
  39810. * for this XR render target or not.
  39811. *
  39812. * Allocating a depth buffer is the default behavior of XR render
  39813. * targets. However, when using the WebXR Layers API, this flag
  39814. * must be set to `false` when the `ignoreDepthValues` property of
  39815. * the projection layers evaluates to `false`.
  39816. *
  39817. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  39818. *
  39819. * @private
  39820. * @type {boolean}
  39821. * @default true
  39822. */
  39823. this._autoAllocateDepthBuffer = true;
  39824. /**
  39825. * Whether this render target is associated with a XRWebGLLayer.
  39826. *
  39827. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  39828. * this means that you don't have access to its bound color,
  39829. * stencil and depth buffers. We need to handle this framebuffer
  39830. * differently since its textures are always bound.
  39831. *
  39832. * @private
  39833. * @type {boolean}
  39834. * @default false
  39835. * */
  39836. this._isOpaqueFramebuffer = false;
  39837. }
  39838. copy( source ) {
  39839. super.copy( source );
  39840. this._hasExternalTextures = source._hasExternalTextures;
  39841. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  39842. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  39843. return this;
  39844. }
  39845. }
  39846. const _cameraLPos = /*@__PURE__*/ new Vector3();
  39847. const _cameraRPos = /*@__PURE__*/ new Vector3();
  39848. const _contextNodeLib = /*@__PURE__*/ new WeakMap();
  39849. /**
  39850. * The XR manager is built on top of the WebXR Device API to
  39851. * manage XR sessions with `WebGPURenderer`.
  39852. *
  39853. * XR is currently only supported with a WebGL 2 backend.
  39854. *
  39855. * @augments EventDispatcher
  39856. */
  39857. class XRManager extends EventDispatcher {
  39858. /**
  39859. * Constructs a new XR manager.
  39860. *
  39861. * @param {Renderer} renderer - The renderer.
  39862. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  39863. */
  39864. constructor( renderer, multiview = false ) {
  39865. super();
  39866. /**
  39867. * This flag globally enables XR rendering.
  39868. *
  39869. * @type {boolean}
  39870. * @default false
  39871. */
  39872. this.enabled = false;
  39873. /**
  39874. * Whether the XR device is currently presenting or not.
  39875. *
  39876. * @type {boolean}
  39877. * @default false
  39878. * @readonly
  39879. */
  39880. this.isPresenting = false;
  39881. /**
  39882. * Whether the XR camera should automatically be updated or not.
  39883. *
  39884. * @type {boolean}
  39885. * @default true
  39886. */
  39887. this.cameraAutoUpdate = true;
  39888. /**
  39889. * The renderer.
  39890. *
  39891. * @private
  39892. * @type {Renderer}
  39893. */
  39894. this._renderer = renderer;
  39895. // camera
  39896. /**
  39897. * Represents the camera for the left eye.
  39898. *
  39899. * @private
  39900. * @type {PerspectiveCamera}
  39901. */
  39902. this._cameraL = new PerspectiveCamera();
  39903. this._cameraL.viewport = new Vector4();
  39904. /**
  39905. * Represents the camera for the right eye.
  39906. *
  39907. * @private
  39908. * @type {PerspectiveCamera}
  39909. */
  39910. this._cameraR = new PerspectiveCamera();
  39911. this._cameraR.viewport = new Vector4();
  39912. /**
  39913. * A list of cameras used for rendering the XR views.
  39914. *
  39915. * @private
  39916. * @type {Array<Camera>}
  39917. */
  39918. this._cameras = [ this._cameraL, this._cameraR ];
  39919. /**
  39920. * The main XR camera.
  39921. *
  39922. * @private
  39923. * @type {ArrayCamera}
  39924. */
  39925. this._cameraXR = new ArrayCamera();
  39926. /**
  39927. * The current near value of the XR camera.
  39928. *
  39929. * @private
  39930. * @type {?number}
  39931. * @default null
  39932. */
  39933. this._currentDepthNear = null;
  39934. /**
  39935. * The current far value of the XR camera.
  39936. *
  39937. * @private
  39938. * @type {?number}
  39939. * @default null
  39940. */
  39941. this._currentDepthFar = null;
  39942. /**
  39943. * A list of WebXR controllers requested by the application.
  39944. *
  39945. * @private
  39946. * @type {Array<WebXRController>}
  39947. */
  39948. this._controllers = [];
  39949. /**
  39950. * A list of XR input source. Each input source belongs to
  39951. * an instance of WebXRController.
  39952. *
  39953. * @private
  39954. * @type {Array<XRInputSource?>}
  39955. */
  39956. this._controllerInputSources = [];
  39957. /**
  39958. * The XR render target that represents the rendering destination
  39959. * during an active XR session.
  39960. *
  39961. * @private
  39962. * @type {?RenderTarget}
  39963. * @default null
  39964. */
  39965. this._xrRenderTarget = null;
  39966. /**
  39967. * An array holding all the non-projection layers
  39968. *
  39969. * @private
  39970. * @type {Array<Object>}
  39971. * @default []
  39972. */
  39973. this._layers = [];
  39974. /**
  39975. * Whether the XR session uses layers.
  39976. *
  39977. * @private
  39978. * @type {boolean}
  39979. * @default false
  39980. */
  39981. this._sessionUsesLayers = false;
  39982. /**
  39983. * Whether the device supports binding gl objects.
  39984. *
  39985. * @private
  39986. * @type {boolean}
  39987. * @readonly
  39988. */
  39989. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  39990. /**
  39991. * Helper function to create native WebXR Layer.
  39992. *
  39993. * @private
  39994. * @type {Function}
  39995. */
  39996. this._createXRLayer = createXRLayer.bind( this );
  39997. /**
  39998. * The current WebGL context.
  39999. *
  40000. * @private
  40001. * @type {?WebGL2RenderingContext}
  40002. * @default null
  40003. */
  40004. this._gl = null;
  40005. /**
  40006. * The current animation context.
  40007. *
  40008. * @private
  40009. * @type {?Window}
  40010. * @default null
  40011. */
  40012. this._currentAnimationContext = null;
  40013. /**
  40014. * The current animation loop.
  40015. *
  40016. * @private
  40017. * @type {?Function}
  40018. * @default null
  40019. */
  40020. this._currentAnimationLoop = null;
  40021. /**
  40022. * The current pixel ratio.
  40023. *
  40024. * @private
  40025. * @type {?number}
  40026. * @default null
  40027. */
  40028. this._currentPixelRatio = null;
  40029. /**
  40030. * The current size of the renderer's canvas
  40031. * in logical pixel unit.
  40032. *
  40033. * @private
  40034. * @type {Vector2}
  40035. */
  40036. this._currentSize = new Vector2();
  40037. /**
  40038. * The default event listener for handling events inside a XR session.
  40039. *
  40040. * @private
  40041. * @type {Function}
  40042. */
  40043. this._onSessionEvent = onSessionEvent.bind( this );
  40044. /**
  40045. * The event listener for handling the end of a XR session.
  40046. *
  40047. * @private
  40048. * @type {Function}
  40049. */
  40050. this._onSessionEnd = onSessionEnd.bind( this );
  40051. /**
  40052. * The event listener for handling the `inputsourceschange` event.
  40053. *
  40054. * @private
  40055. * @type {Function}
  40056. */
  40057. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  40058. /**
  40059. * The animation loop which is used as a replacement for the default
  40060. * animation loop of the application. It is only used when a XR session
  40061. * is active.
  40062. *
  40063. * @private
  40064. * @type {Function}
  40065. */
  40066. this._onAnimationFrame = onAnimationFrame.bind( this );
  40067. /**
  40068. * The current XR reference space.
  40069. *
  40070. * @private
  40071. * @type {?XRReferenceSpace}
  40072. * @default null
  40073. */
  40074. this._referenceSpace = null;
  40075. /**
  40076. * The current XR reference space type.
  40077. *
  40078. * @private
  40079. * @type {XRReferenceSpaceType}
  40080. * @default 'local-floor'
  40081. */
  40082. this._referenceSpaceType = 'local-floor';
  40083. /**
  40084. * A custom reference space defined by the application.
  40085. *
  40086. * @private
  40087. * @type {?XRReferenceSpace}
  40088. * @default null
  40089. */
  40090. this._customReferenceSpace = null;
  40091. /**
  40092. * The framebuffer scale factor.
  40093. *
  40094. * @private
  40095. * @type {number}
  40096. * @default 1
  40097. */
  40098. this._framebufferScaleFactor = 1;
  40099. /**
  40100. * The foveation factor.
  40101. *
  40102. * @private
  40103. * @type {number}
  40104. * @default 1
  40105. */
  40106. this._foveation = 1.0;
  40107. /**
  40108. * A reference to the current XR session.
  40109. *
  40110. * @private
  40111. * @type {?XRSession}
  40112. * @default null
  40113. */
  40114. this._session = null;
  40115. /**
  40116. * A reference to the current XR base layer.
  40117. *
  40118. * @private
  40119. * @type {?XRWebGLLayer}
  40120. * @default null
  40121. */
  40122. this._glBaseLayer = null;
  40123. /**
  40124. * A reference to the current XR binding.
  40125. *
  40126. * @private
  40127. * @type {?XRWebGLBinding}
  40128. * @default null
  40129. */
  40130. this._glBinding = null;
  40131. /**
  40132. * A reference to the current XR projection layer.
  40133. *
  40134. * @private
  40135. * @type {?XRProjectionLayer}
  40136. * @default null
  40137. */
  40138. this._glProjLayer = null;
  40139. /**
  40140. * A reference to the current XR frame.
  40141. *
  40142. * @private
  40143. * @type {?XRFrame}
  40144. * @default null
  40145. */
  40146. this._xrFrame = null;
  40147. /**
  40148. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  40149. *
  40150. * Note: this does not represent XRSession explicitly requesting
  40151. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  40152. *
  40153. * @private
  40154. * @type {boolean}
  40155. * @readonly
  40156. */
  40157. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  40158. /**
  40159. * Whether the usage of multiview has been requested by the application or not.
  40160. *
  40161. * @private
  40162. * @type {boolean}
  40163. * @default false
  40164. * @readonly
  40165. */
  40166. this._useMultiviewIfPossible = multiview;
  40167. /**
  40168. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  40169. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  40170. *
  40171. * @private
  40172. * @type {boolean}
  40173. * @readonly
  40174. */
  40175. this._useMultiview = false;
  40176. }
  40177. /**
  40178. * Returns an instance of `THREE.Group` that represents the transformation
  40179. * of a XR controller in target ray space. The requested controller is defined
  40180. * by the given index.
  40181. *
  40182. * @param {number} index - The index of the XR controller.
  40183. * @return {Group} A group that represents the controller's transformation.
  40184. */
  40185. getController( index ) {
  40186. const controller = this._getController( index );
  40187. return controller.getTargetRaySpace();
  40188. }
  40189. /**
  40190. * Returns an instance of `THREE.Group` that represents the transformation
  40191. * of a XR controller in grip space. The requested controller is defined
  40192. * by the given index.
  40193. *
  40194. * @param {number} index - The index of the XR controller.
  40195. * @return {Group} A group that represents the controller's transformation.
  40196. */
  40197. getControllerGrip( index ) {
  40198. const controller = this._getController( index );
  40199. return controller.getGripSpace();
  40200. }
  40201. /**
  40202. * Returns an instance of `THREE.Group` that represents the transformation
  40203. * of a XR controller in hand space. The requested controller is defined
  40204. * by the given index.
  40205. *
  40206. * @param {number} index - The index of the XR controller.
  40207. * @return {Group} A group that represents the controller's transformation.
  40208. */
  40209. getHand( index ) {
  40210. const controller = this._getController( index );
  40211. return controller.getHandSpace();
  40212. }
  40213. /**
  40214. * Returns the foveation value.
  40215. *
  40216. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  40217. */
  40218. getFoveation() {
  40219. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  40220. return undefined;
  40221. }
  40222. return this._foveation;
  40223. }
  40224. /**
  40225. * Sets the foveation value.
  40226. *
  40227. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  40228. * and `1` means maximum foveation (the edges render at lower resolution).
  40229. */
  40230. setFoveation( foveation ) {
  40231. this._foveation = foveation;
  40232. if ( this._glProjLayer !== null ) {
  40233. this._glProjLayer.fixedFoveation = foveation;
  40234. }
  40235. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  40236. this._glBaseLayer.fixedFoveation = foveation;
  40237. }
  40238. }
  40239. /**
  40240. * Returns the framebuffer scale factor.
  40241. *
  40242. * @return {number} The framebuffer scale factor.
  40243. */
  40244. getFramebufferScaleFactor() {
  40245. return this._framebufferScaleFactor;
  40246. }
  40247. /**
  40248. * Sets the framebuffer scale factor.
  40249. *
  40250. * This method can not be used during a XR session.
  40251. *
  40252. * @param {number} factor - The framebuffer scale factor.
  40253. */
  40254. setFramebufferScaleFactor( factor ) {
  40255. this._framebufferScaleFactor = factor;
  40256. if ( this.isPresenting === true ) {
  40257. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  40258. }
  40259. }
  40260. /**
  40261. * Returns the reference space type.
  40262. *
  40263. * @return {XRReferenceSpaceType} The reference space type.
  40264. */
  40265. getReferenceSpaceType() {
  40266. return this._referenceSpaceType;
  40267. }
  40268. /**
  40269. * Sets the reference space type.
  40270. *
  40271. * This method can not be used during a XR session.
  40272. *
  40273. * @param {XRReferenceSpaceType} type - The reference space type.
  40274. */
  40275. setReferenceSpaceType( type ) {
  40276. this._referenceSpaceType = type;
  40277. if ( this.isPresenting === true ) {
  40278. warn( 'XRManager: Cannot change reference space type while presenting.' );
  40279. }
  40280. }
  40281. /**
  40282. * Returns the XR reference space.
  40283. *
  40284. * @return {XRReferenceSpace} The XR reference space.
  40285. */
  40286. getReferenceSpace() {
  40287. return this._customReferenceSpace || this._referenceSpace;
  40288. }
  40289. /**
  40290. * Sets a custom XR reference space.
  40291. *
  40292. * @param {XRReferenceSpace} space - The XR reference space.
  40293. */
  40294. setReferenceSpace( space ) {
  40295. this._customReferenceSpace = space;
  40296. }
  40297. /**
  40298. * Returns the XR camera.
  40299. *
  40300. * @return {ArrayCamera} The XR camera.
  40301. */
  40302. getCamera() {
  40303. return this._cameraXR;
  40304. }
  40305. /**
  40306. * Returns the environment blend mode from the current XR session.
  40307. *
  40308. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  40309. */
  40310. getEnvironmentBlendMode() {
  40311. if ( this._session !== null ) {
  40312. return this._session.environmentBlendMode;
  40313. }
  40314. }
  40315. /**
  40316. * Returns the current XR binding.
  40317. *
  40318. * Creates a new binding if needed and the browser is
  40319. * capable of doing so.
  40320. *
  40321. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  40322. */
  40323. getBinding() {
  40324. if ( this._glBinding === null && this._supportsGlBinding ) {
  40325. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  40326. }
  40327. return this._glBinding;
  40328. }
  40329. /**
  40330. * Returns the current XR frame.
  40331. *
  40332. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  40333. */
  40334. getFrame() {
  40335. return this._xrFrame;
  40336. }
  40337. /**
  40338. * Returns `true` if the engine renders to a multiview target.
  40339. *
  40340. * @return {boolean} Whether the engine renders to a multiview render target or not.
  40341. */
  40342. useMultiview() {
  40343. return this._useMultiview;
  40344. }
  40345. /**
  40346. * This method can be used in XR applications to create a quadratic layer that presents a separate
  40347. * rendered scene.
  40348. *
  40349. * @param {number} width - The width of the layer plane in world units.
  40350. * @param {number} height - The height of the layer plane in world units.
  40351. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  40352. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  40353. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  40354. * @param {number} pixelheight - The height of the layer's render target in pixels.
  40355. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  40356. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  40357. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  40358. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  40359. */
  40360. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  40361. const geometry = new PlaneGeometry( width, height );
  40362. const renderTarget = new XRRenderTarget(
  40363. pixelwidth,
  40364. pixelheight,
  40365. {
  40366. format: RGBAFormat,
  40367. type: UnsignedByteType,
  40368. depthTexture: new DepthTexture(
  40369. pixelwidth,
  40370. pixelheight,
  40371. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  40372. undefined,
  40373. undefined,
  40374. undefined,
  40375. undefined,
  40376. undefined,
  40377. undefined,
  40378. attributes.stencil ? DepthStencilFormat : DepthFormat
  40379. ),
  40380. stencilBuffer: attributes.stencil,
  40381. resolveDepthBuffer: false,
  40382. resolveStencilBuffer: false
  40383. } );
  40384. renderTarget._autoAllocateDepthBuffer = true;
  40385. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  40386. material.map = renderTarget.texture;
  40387. material.map.offset.y = 1;
  40388. material.map.repeat.y = -1;
  40389. const plane = new Mesh( geometry, material );
  40390. plane.position.copy( translation );
  40391. plane.quaternion.copy( quaternion );
  40392. const layer = {
  40393. type: 'quad',
  40394. width: width,
  40395. height: height,
  40396. translation: translation,
  40397. quaternion: quaternion,
  40398. pixelwidth: pixelwidth,
  40399. pixelheight: pixelheight,
  40400. plane: plane,
  40401. material: material,
  40402. rendercall: rendercall,
  40403. renderTarget: renderTarget };
  40404. this._layers.push( layer );
  40405. if ( this._session !== null ) {
  40406. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  40407. layer.plane.material.blending = CustomBlending;
  40408. layer.plane.material.blendEquation = AddEquation;
  40409. layer.plane.material.blendSrc = ZeroFactor;
  40410. layer.plane.material.blendDst = ZeroFactor;
  40411. layer.xrlayer = this._createXRLayer( layer );
  40412. const xrlayers = this._session.renderState.layers;
  40413. xrlayers.unshift( layer.xrlayer );
  40414. this._session.updateRenderState( { layers: xrlayers } );
  40415. } else {
  40416. renderTarget.isXRRenderTarget = false;
  40417. }
  40418. return plane;
  40419. }
  40420. /**
  40421. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  40422. * rendered scene.
  40423. *
  40424. * @param {number} radius - The radius of the cylinder in world units.
  40425. * @param {number} centralAngle - The central angle of the cylinder in radians.
  40426. * @param {number} aspectratio - The aspect ratio.
  40427. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  40428. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  40429. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  40430. * @param {number} pixelheight - The height of the layer's render target in pixels.
  40431. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  40432. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  40433. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  40434. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  40435. */
  40436. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  40437. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  40438. const renderTarget = new XRRenderTarget(
  40439. pixelwidth,
  40440. pixelheight,
  40441. {
  40442. format: RGBAFormat,
  40443. type: UnsignedByteType,
  40444. depthTexture: new DepthTexture(
  40445. pixelwidth,
  40446. pixelheight,
  40447. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  40448. undefined,
  40449. undefined,
  40450. undefined,
  40451. undefined,
  40452. undefined,
  40453. undefined,
  40454. attributes.stencil ? DepthStencilFormat : DepthFormat
  40455. ),
  40456. stencilBuffer: attributes.stencil,
  40457. resolveDepthBuffer: false,
  40458. resolveStencilBuffer: false
  40459. } );
  40460. renderTarget._autoAllocateDepthBuffer = true;
  40461. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  40462. material.map = renderTarget.texture;
  40463. material.map.offset.y = 1;
  40464. material.map.repeat.y = -1;
  40465. const plane = new Mesh( geometry, material );
  40466. plane.position.copy( translation );
  40467. plane.quaternion.copy( quaternion );
  40468. const layer = {
  40469. type: 'cylinder',
  40470. radius: radius,
  40471. centralAngle: centralAngle,
  40472. aspectratio: aspectratio,
  40473. translation: translation,
  40474. quaternion: quaternion,
  40475. pixelwidth: pixelwidth,
  40476. pixelheight: pixelheight,
  40477. plane: plane,
  40478. material: material,
  40479. rendercall: rendercall,
  40480. renderTarget: renderTarget };
  40481. this._layers.push( layer );
  40482. if ( this._session !== null ) {
  40483. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  40484. layer.plane.material.blending = CustomBlending;
  40485. layer.plane.material.blendEquation = AddEquation;
  40486. layer.plane.material.blendSrc = ZeroFactor;
  40487. layer.plane.material.blendDst = ZeroFactor;
  40488. layer.xrlayer = this._createXRLayer( layer );
  40489. const xrlayers = this._session.renderState.layers;
  40490. xrlayers.unshift( layer.xrlayer );
  40491. this._session.updateRenderState( { layers: xrlayers } );
  40492. } else {
  40493. renderTarget.isXRRenderTarget = false;
  40494. }
  40495. return plane;
  40496. }
  40497. /**
  40498. * Renders the XR layers that have been previously added to the scene.
  40499. *
  40500. * This method is usually called in your animation loop before rendering
  40501. * the actual scene via `renderer.render( scene, camera );`.
  40502. */
  40503. renderLayers( ) {
  40504. const translationObject = new Vector3();
  40505. const quaternionObject = new Quaternion();
  40506. const renderer = this._renderer;
  40507. const wasPresenting = this.isPresenting;
  40508. this.isPresenting = false;
  40509. const rendererSize = new Vector2();
  40510. renderer.getSize( rendererSize );
  40511. const currentRenderTarget = renderer.getRenderTarget();
  40512. for ( const layer of this._layers ) {
  40513. layer.renderTarget.isXRRenderTarget = this._session !== null;
  40514. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  40515. const currentContextNode = renderer.contextNode;
  40516. let contextNode;
  40517. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  40518. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  40519. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  40520. renderer.backend.setXRRenderTargetTextures(
  40521. layer.renderTarget,
  40522. glSubImage.colorTexture,
  40523. undefined );
  40524. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  40525. contextNode = _contextNodeLib.get( currentContextNode );
  40526. if ( contextNode === undefined ) {
  40527. // Apply ToneMapping and OutputColorSpace directly in the material shader
  40528. contextNode = currentContextNode.context( {
  40529. getOutput: ( outputNode ) => {
  40530. return renderOutput( outputNode, renderer.toneMapping, renderer.outputColorSpace );
  40531. }
  40532. } );
  40533. _contextNodeLib.set( currentContextNode, contextNode );
  40534. }
  40535. } else {
  40536. contextNode = currentContextNode;
  40537. }
  40538. renderer.contextNode = contextNode;
  40539. renderer.setRenderTarget( layer.renderTarget );
  40540. layer.rendercall();
  40541. renderer.contextNode = currentContextNode;
  40542. }
  40543. renderer.setRenderTarget( currentRenderTarget );
  40544. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  40545. this.isPresenting = wasPresenting;
  40546. }
  40547. /**
  40548. * Returns the current XR session.
  40549. *
  40550. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  40551. */
  40552. getSession() {
  40553. return this._session;
  40554. }
  40555. /**
  40556. * After a XR session has been requested usually with one of the `*Button` modules, it
  40557. * is injected into the renderer with this method. This method triggers the start of
  40558. * the actual XR rendering.
  40559. *
  40560. * @async
  40561. * @param {XRSession} session - The XR session to set.
  40562. * @return {Promise} A Promise that resolves when the session has been set.
  40563. */
  40564. async setSession( session ) {
  40565. const renderer = this._renderer;
  40566. const backend = renderer.backend;
  40567. this._gl = renderer.getContext();
  40568. const gl = this._gl;
  40569. const attributes = gl.getContextAttributes();
  40570. this._session = session;
  40571. if ( session !== null ) {
  40572. 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.' );
  40573. session.addEventListener( 'select', this._onSessionEvent );
  40574. session.addEventListener( 'selectstart', this._onSessionEvent );
  40575. session.addEventListener( 'selectend', this._onSessionEvent );
  40576. session.addEventListener( 'squeeze', this._onSessionEvent );
  40577. session.addEventListener( 'squeezestart', this._onSessionEvent );
  40578. session.addEventListener( 'squeezeend', this._onSessionEvent );
  40579. session.addEventListener( 'end', this._onSessionEnd );
  40580. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40581. await backend.makeXRCompatible();
  40582. this._currentPixelRatio = renderer.getPixelRatio();
  40583. renderer.getSize( this._currentSize );
  40584. this._currentAnimationContext = renderer._animation.getContext();
  40585. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  40586. renderer._animation.stop();
  40587. //
  40588. if ( this._supportsLayers === true ) {
  40589. // default path using XRProjectionLayer
  40590. let depthFormat = null;
  40591. let depthType = null;
  40592. let glDepthFormat = null;
  40593. if ( renderer.depth ) {
  40594. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  40595. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  40596. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  40597. }
  40598. const projectionlayerInit = {
  40599. colorFormat: gl.RGBA8,
  40600. depthFormat: glDepthFormat,
  40601. scaleFactor: this._framebufferScaleFactor,
  40602. clearOnAccess: false
  40603. };
  40604. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  40605. projectionlayerInit.textureType = 'texture-array';
  40606. this._useMultiview = true;
  40607. }
  40608. this._glBinding = this.getBinding();
  40609. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  40610. const layersArray = [ glProjLayer ];
  40611. this._glProjLayer = glProjLayer;
  40612. renderer.setPixelRatio( 1 );
  40613. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  40614. const depth = this._useMultiview ? 2 : 1;
  40615. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  40616. this._xrRenderTarget = new XRRenderTarget(
  40617. glProjLayer.textureWidth,
  40618. glProjLayer.textureHeight,
  40619. {
  40620. format: RGBAFormat,
  40621. type: UnsignedByteType,
  40622. colorSpace: renderer.outputColorSpace,
  40623. depthTexture: depthTexture,
  40624. stencilBuffer: renderer.stencil,
  40625. samples: attributes.antialias ? 4 : 0,
  40626. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  40627. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  40628. depth: this._useMultiview ? 2 : 1,
  40629. multiview: this._useMultiview
  40630. } );
  40631. this._xrRenderTarget._hasExternalTextures = true;
  40632. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  40633. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  40634. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40635. if ( this._sessionUsesLayers ) {
  40636. // switch layers to native
  40637. for ( const layer of this._layers ) {
  40638. // change material so it "punches" out a hole to show the XR Layer.
  40639. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  40640. layer.plane.material.blending = CustomBlending;
  40641. layer.plane.material.blendEquation = AddEquation;
  40642. layer.plane.material.blendSrc = ZeroFactor;
  40643. layer.plane.material.blendDst = ZeroFactor;
  40644. layer.xrlayer = this._createXRLayer( layer );
  40645. layersArray.unshift( layer.xrlayer );
  40646. }
  40647. }
  40648. session.updateRenderState( { layers: layersArray } );
  40649. } else {
  40650. // fallback to XRWebGLLayer
  40651. const layerInit = {
  40652. antialias: renderer.currentSamples > 0,
  40653. alpha: true,
  40654. depth: renderer.depth,
  40655. stencil: renderer.stencil,
  40656. framebufferScaleFactor: this.getFramebufferScaleFactor()
  40657. };
  40658. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  40659. this._glBaseLayer = glBaseLayer;
  40660. session.updateRenderState( { baseLayer: glBaseLayer } );
  40661. renderer.setPixelRatio( 1 );
  40662. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  40663. this._xrRenderTarget = new XRRenderTarget(
  40664. glBaseLayer.framebufferWidth,
  40665. glBaseLayer.framebufferHeight,
  40666. {
  40667. format: RGBAFormat,
  40668. type: UnsignedByteType,
  40669. colorSpace: renderer.outputColorSpace,
  40670. stencilBuffer: renderer.stencil,
  40671. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40672. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40673. }
  40674. );
  40675. this._xrRenderTarget._isOpaqueFramebuffer = true;
  40676. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40677. }
  40678. //
  40679. this.setFoveation( this.getFoveation() );
  40680. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  40681. renderer._animation.setContext( session );
  40682. renderer._animation.start();
  40683. this.isPresenting = true;
  40684. this.dispatchEvent( { type: 'sessionstart' } );
  40685. }
  40686. }
  40687. /**
  40688. * This method is called by the renderer per frame and updates the XR camera
  40689. * and it sub cameras based on the given camera. The given camera is the "user"
  40690. * camera created on application level and used for non-XR rendering.
  40691. *
  40692. * @param {PerspectiveCamera} camera - The camera.
  40693. */
  40694. updateCamera( camera ) {
  40695. const session = this._session;
  40696. if ( session === null ) return;
  40697. const depthNear = camera.near;
  40698. const depthFar = camera.far;
  40699. const cameraXR = this._cameraXR;
  40700. const cameraL = this._cameraL;
  40701. const cameraR = this._cameraR;
  40702. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  40703. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  40704. cameraXR.isMultiViewCamera = this._useMultiview;
  40705. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  40706. // Note that the new renderState won't apply until the next frame. See #18320
  40707. session.updateRenderState( {
  40708. depthNear: cameraXR.near,
  40709. depthFar: cameraXR.far
  40710. } );
  40711. this._currentDepthNear = cameraXR.near;
  40712. this._currentDepthFar = cameraXR.far;
  40713. }
  40714. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  40715. cameraXR.layers.mask = camera.layers.mask | 0b110;
  40716. cameraL.layers.mask = cameraXR.layers.mask & -5;
  40717. cameraR.layers.mask = cameraXR.layers.mask & -3;
  40718. const parent = camera.parent;
  40719. const cameras = cameraXR.cameras;
  40720. updateCamera( cameraXR, parent );
  40721. for ( let i = 0; i < cameras.length; i ++ ) {
  40722. updateCamera( cameras[ i ], parent );
  40723. }
  40724. // update projection matrix for proper view frustum culling
  40725. if ( cameras.length === 2 ) {
  40726. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  40727. } else {
  40728. // assume single camera setup (AR)
  40729. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  40730. }
  40731. // update user camera and its children
  40732. updateUserCamera( camera, cameraXR, parent );
  40733. }
  40734. /**
  40735. * Returns a WebXR controller for the given controller index.
  40736. *
  40737. * @private
  40738. * @param {number} index - The controller index.
  40739. * @return {WebXRController} The XR controller.
  40740. */
  40741. _getController( index ) {
  40742. let controller = this._controllers[ index ];
  40743. if ( controller === undefined ) {
  40744. controller = new WebXRController();
  40745. this._controllers[ index ] = controller;
  40746. }
  40747. return controller;
  40748. }
  40749. }
  40750. /**
  40751. * Assumes 2 cameras that are parallel and share an X-axis, and that
  40752. * the cameras' projection and world matrices have already been set.
  40753. * And that near and far planes are identical for both cameras.
  40754. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  40755. *
  40756. * @param {ArrayCamera} camera - The camera to update.
  40757. * @param {PerspectiveCamera} cameraL - The left camera.
  40758. * @param {PerspectiveCamera} cameraR - The right camera.
  40759. */
  40760. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  40761. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  40762. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  40763. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  40764. const projL = cameraL.projectionMatrix.elements;
  40765. const projR = cameraR.projectionMatrix.elements;
  40766. // VR systems will have identical far and near planes, and
  40767. // most likely identical top and bottom frustum extents.
  40768. // Use the left camera for these values.
  40769. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  40770. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  40771. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  40772. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  40773. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  40774. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  40775. const left = near * leftFov;
  40776. const right = near * rightFov;
  40777. // Calculate the new camera's position offset from the
  40778. // left camera. xOffset should be roughly half `ipd`.
  40779. const zOffset = ipd / ( - leftFov + rightFov );
  40780. const xOffset = zOffset * - leftFov;
  40781. // TODO: Better way to apply this offset?
  40782. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  40783. camera.translateX( xOffset );
  40784. camera.translateZ( zOffset );
  40785. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  40786. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40787. // Check if the projection uses an infinite far plane.
  40788. if ( projL[ 10 ] === -1 ) {
  40789. // Use the projection matrix from the left eye.
  40790. // The camera offset is sufficient to include the view volumes
  40791. // of both eyes (assuming symmetric projections).
  40792. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  40793. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  40794. } else {
  40795. // Find the union of the frustum values of the cameras and scale
  40796. // the values so that the near plane's position does not change in world space,
  40797. // although must now be relative to the new union camera.
  40798. const near2 = near + zOffset;
  40799. const far2 = far + zOffset;
  40800. const left2 = left - xOffset;
  40801. const right2 = right + ( ipd - xOffset );
  40802. const top2 = topFov * far / far2 * near2;
  40803. const bottom2 = bottomFov * far / far2 * near2;
  40804. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  40805. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40806. }
  40807. }
  40808. /**
  40809. * Updates the world matrices for the given camera based on the parent 3D object.
  40810. *
  40811. * @inner
  40812. * @param {Camera} camera - The camera to update.
  40813. * @param {Object3D} parent - The parent 3D object.
  40814. */
  40815. function updateCamera( camera, parent ) {
  40816. if ( parent === null ) {
  40817. camera.matrixWorld.copy( camera.matrix );
  40818. } else {
  40819. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  40820. }
  40821. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40822. }
  40823. /**
  40824. * Updates the given camera with the transformation of the XR camera and parent object.
  40825. *
  40826. * @inner
  40827. * @param {Camera} camera - The camera to update.
  40828. * @param {ArrayCamera} cameraXR - The XR camera.
  40829. * @param {Object3D} parent - The parent 3D object.
  40830. */
  40831. function updateUserCamera( camera, cameraXR, parent ) {
  40832. if ( parent === null ) {
  40833. camera.matrix.copy( cameraXR.matrixWorld );
  40834. } else {
  40835. camera.matrix.copy( parent.matrixWorld );
  40836. camera.matrix.invert();
  40837. camera.matrix.multiply( cameraXR.matrixWorld );
  40838. }
  40839. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40840. camera.updateMatrixWorld( true );
  40841. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  40842. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  40843. if ( camera.isPerspectiveCamera ) {
  40844. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  40845. camera.zoom = 1;
  40846. }
  40847. }
  40848. function onSessionEvent( event ) {
  40849. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  40850. if ( controllerIndex === -1 ) {
  40851. return;
  40852. }
  40853. const controller = this._controllers[ controllerIndex ];
  40854. if ( controller !== undefined ) {
  40855. const referenceSpace = this.getReferenceSpace();
  40856. controller.update( event.inputSource, event.frame, referenceSpace );
  40857. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  40858. }
  40859. }
  40860. function onSessionEnd() {
  40861. const session = this._session;
  40862. const renderer = this._renderer;
  40863. session.removeEventListener( 'select', this._onSessionEvent );
  40864. session.removeEventListener( 'selectstart', this._onSessionEvent );
  40865. session.removeEventListener( 'selectend', this._onSessionEvent );
  40866. session.removeEventListener( 'squeeze', this._onSessionEvent );
  40867. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  40868. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  40869. session.removeEventListener( 'end', this._onSessionEnd );
  40870. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40871. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40872. const inputSource = this._controllerInputSources[ i ];
  40873. if ( inputSource === null ) continue;
  40874. this._controllerInputSources[ i ] = null;
  40875. this._controllers[ i ].disconnect( inputSource );
  40876. }
  40877. this._currentDepthNear = null;
  40878. this._currentDepthFar = null;
  40879. // restore framebuffer/rendering state
  40880. renderer._resetXRState();
  40881. this._session = null;
  40882. this._xrRenderTarget = null;
  40883. this._glBinding = null;
  40884. this._glBaseLayer = null;
  40885. this._glProjLayer = null;
  40886. // switch layers back to emulated
  40887. if ( this._sessionUsesLayers === true ) {
  40888. for ( const layer of this._layers ) {
  40889. // Recreate layer render target to reset state
  40890. layer.renderTarget = new XRRenderTarget(
  40891. layer.pixelwidth,
  40892. layer.pixelheight,
  40893. {
  40894. format: RGBAFormat,
  40895. type: UnsignedByteType,
  40896. depthTexture: new DepthTexture(
  40897. layer.pixelwidth,
  40898. layer.pixelheight,
  40899. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  40900. undefined,
  40901. undefined,
  40902. undefined,
  40903. undefined,
  40904. undefined,
  40905. undefined,
  40906. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  40907. ),
  40908. stencilBuffer: layer.stencilBuffer,
  40909. resolveDepthBuffer: false,
  40910. resolveStencilBuffer: false
  40911. } );
  40912. layer.renderTarget.isXRRenderTarget = false;
  40913. layer.plane.material = layer.material;
  40914. layer.material.map = layer.renderTarget.texture;
  40915. layer.material.map.offset.y = 1;
  40916. layer.material.map.repeat.y = -1;
  40917. delete layer.xrlayer;
  40918. }
  40919. }
  40920. //
  40921. this.isPresenting = false;
  40922. this._useMultiview = false;
  40923. renderer._animation.stop();
  40924. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  40925. renderer._animation.setContext( this._currentAnimationContext );
  40926. renderer._animation.start();
  40927. renderer.setPixelRatio( this._currentPixelRatio );
  40928. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  40929. this.dispatchEvent( { type: 'sessionend' } );
  40930. }
  40931. function onInputSourcesChange( event ) {
  40932. const controllers = this._controllers;
  40933. const controllerInputSources = this._controllerInputSources;
  40934. // Notify disconnected
  40935. for ( let i = 0; i < event.removed.length; i ++ ) {
  40936. const inputSource = event.removed[ i ];
  40937. const index = controllerInputSources.indexOf( inputSource );
  40938. if ( index >= 0 ) {
  40939. controllerInputSources[ index ] = null;
  40940. controllers[ index ].disconnect( inputSource );
  40941. }
  40942. }
  40943. // Notify connected
  40944. for ( let i = 0; i < event.added.length; i ++ ) {
  40945. const inputSource = event.added[ i ];
  40946. let controllerIndex = controllerInputSources.indexOf( inputSource );
  40947. if ( controllerIndex === -1 ) {
  40948. // Assign input source a controller that currently has no input source
  40949. for ( let i = 0; i < controllers.length; i ++ ) {
  40950. if ( i >= controllerInputSources.length ) {
  40951. controllerInputSources.push( inputSource );
  40952. controllerIndex = i;
  40953. break;
  40954. } else if ( controllerInputSources[ i ] === null ) {
  40955. controllerInputSources[ i ] = inputSource;
  40956. controllerIndex = i;
  40957. break;
  40958. }
  40959. }
  40960. // If all controllers do currently receive input we ignore new ones
  40961. if ( controllerIndex === -1 ) break;
  40962. }
  40963. const controller = controllers[ controllerIndex ];
  40964. if ( controller ) {
  40965. controller.connect( inputSource );
  40966. }
  40967. }
  40968. }
  40969. // Creation method for native WebXR layers
  40970. function createXRLayer( layer ) {
  40971. if ( layer.type === 'quad' ) {
  40972. return this._glBinding.createQuadLayer( {
  40973. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40974. width: layer.width / 2,
  40975. height: layer.height / 2,
  40976. space: this._referenceSpace,
  40977. viewPixelWidth: layer.pixelwidth,
  40978. viewPixelHeight: layer.pixelheight,
  40979. clearOnAccess: false
  40980. } );
  40981. } else {
  40982. return this._glBinding.createCylinderLayer( {
  40983. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40984. radius: layer.radius,
  40985. centralAngle: layer.centralAngle,
  40986. aspectRatio: layer.aspectRatio,
  40987. space: this._referenceSpace,
  40988. viewPixelWidth: layer.pixelwidth,
  40989. viewPixelHeight: layer.pixelheight,
  40990. clearOnAccess: false
  40991. } );
  40992. }
  40993. }
  40994. // Animation Loop
  40995. function onAnimationFrame( time, frame ) {
  40996. if ( frame === undefined ) return;
  40997. const cameraXR = this._cameraXR;
  40998. const renderer = this._renderer;
  40999. const backend = renderer.backend;
  41000. const glBaseLayer = this._glBaseLayer;
  41001. const referenceSpace = this.getReferenceSpace();
  41002. const pose = frame.getViewerPose( referenceSpace );
  41003. this._xrFrame = frame;
  41004. if ( pose !== null ) {
  41005. const views = pose.views;
  41006. if ( this._glBaseLayer !== null ) {
  41007. backend.setXRTarget( glBaseLayer.framebuffer );
  41008. }
  41009. let cameraXRNeedsUpdate = false;
  41010. // check if it's necessary to rebuild cameraXR's camera list
  41011. if ( views.length !== cameraXR.cameras.length ) {
  41012. cameraXR.cameras.length = 0;
  41013. cameraXRNeedsUpdate = true;
  41014. }
  41015. for ( let i = 0; i < views.length; i ++ ) {
  41016. const view = views[ i ];
  41017. let viewport;
  41018. if ( this._supportsLayers === true ) {
  41019. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  41020. viewport = glSubImage.viewport;
  41021. // For side-by-side projection, we only produce a single texture for both eyes.
  41022. if ( i === 0 ) {
  41023. backend.setXRRenderTargetTextures(
  41024. this._xrRenderTarget,
  41025. glSubImage.colorTexture,
  41026. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  41027. );
  41028. }
  41029. } else {
  41030. viewport = glBaseLayer.getViewport( view );
  41031. }
  41032. let camera = this._cameras[ i ];
  41033. if ( camera === undefined ) {
  41034. camera = new PerspectiveCamera();
  41035. camera.layers.enable( i );
  41036. camera.viewport = new Vector4();
  41037. this._cameras[ i ] = camera;
  41038. }
  41039. camera.matrix.fromArray( view.transform.matrix );
  41040. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  41041. camera.projectionMatrix.fromArray( view.projectionMatrix );
  41042. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  41043. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  41044. if ( i === 0 ) {
  41045. cameraXR.matrix.copy( camera.matrix );
  41046. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  41047. }
  41048. if ( cameraXRNeedsUpdate === true ) {
  41049. cameraXR.cameras.push( camera );
  41050. }
  41051. }
  41052. renderer.setOutputRenderTarget( this._xrRenderTarget );
  41053. }
  41054. //
  41055. for ( let i = 0; i < this._controllers.length; i ++ ) {
  41056. const inputSource = this._controllerInputSources[ i ];
  41057. const controller = this._controllers[ i ];
  41058. if ( inputSource !== null && controller !== undefined ) {
  41059. controller.update( inputSource, frame, referenceSpace );
  41060. }
  41061. }
  41062. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  41063. if ( frame.detectedPlanes ) {
  41064. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  41065. }
  41066. this._xrFrame = null;
  41067. }
  41068. /**
  41069. * CanvasTarget is a class that represents the final output destination of the renderer.
  41070. *
  41071. * @augments EventDispatcher
  41072. */
  41073. class CanvasTarget extends EventDispatcher {
  41074. /**
  41075. * Constructs a new CanvasTarget.
  41076. *
  41077. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  41078. */
  41079. constructor( domElement ) {
  41080. super();
  41081. /**
  41082. * A reference to the canvas element the renderer is drawing to.
  41083. * This value of this property will automatically be created by
  41084. * the renderer.
  41085. *
  41086. * @type {HTMLCanvasElement|OffscreenCanvas}
  41087. */
  41088. this.domElement = domElement;
  41089. /**
  41090. * The renderer's pixel ratio.
  41091. *
  41092. * @private
  41093. * @type {number}
  41094. * @default 1
  41095. */
  41096. this._pixelRatio = 1;
  41097. /**
  41098. * The width of the renderer's default framebuffer in logical pixel unit.
  41099. *
  41100. * @private
  41101. * @type {number}
  41102. */
  41103. this._width = this.domElement.width;
  41104. /**
  41105. * The height of the renderer's default framebuffer in logical pixel unit.
  41106. *
  41107. * @private
  41108. * @type {number}
  41109. */
  41110. this._height = this.domElement.height;
  41111. /**
  41112. * The viewport of the renderer in logical pixel unit.
  41113. *
  41114. * @private
  41115. * @type {Vector4}
  41116. */
  41117. this._viewport = new Vector4( 0, 0, this._width, this._height );
  41118. /**
  41119. * The scissor rectangle of the renderer in logical pixel unit.
  41120. *
  41121. * @private
  41122. * @type {Vector4}
  41123. */
  41124. this._scissor = new Vector4( 0, 0, this._width, this._height );
  41125. /**
  41126. * Whether the scissor test should be enabled or not.
  41127. *
  41128. * @private
  41129. * @type {boolean}
  41130. */
  41131. this._scissorTest = false;
  41132. /**
  41133. * The color texture of the default framebuffer.
  41134. *
  41135. * @type {FramebufferTexture}
  41136. */
  41137. this.colorTexture = new FramebufferTexture();
  41138. /**
  41139. * The depth texture of the default framebuffer.
  41140. *
  41141. * @type {DepthTexture}
  41142. */
  41143. this.depthTexture = new DepthTexture();
  41144. }
  41145. /**
  41146. * Returns the pixel ratio.
  41147. *
  41148. * @return {number} The pixel ratio.
  41149. */
  41150. getPixelRatio() {
  41151. return this._pixelRatio;
  41152. }
  41153. /**
  41154. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  41155. *
  41156. * @param {Vector2} target - The method writes the result in this target object.
  41157. * @return {Vector2} The drawing buffer size.
  41158. */
  41159. getDrawingBufferSize( target ) {
  41160. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  41161. }
  41162. /**
  41163. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  41164. *
  41165. * @param {Vector2} target - The method writes the result in this target object.
  41166. * @return {Vector2} The renderer's size in logical pixels.
  41167. */
  41168. getSize( target ) {
  41169. return target.set( this._width, this._height );
  41170. }
  41171. /**
  41172. * Sets the given pixel ratio and resizes the canvas if necessary.
  41173. *
  41174. * @param {number} [value=1] - The pixel ratio.
  41175. */
  41176. setPixelRatio( value = 1 ) {
  41177. if ( this._pixelRatio === value ) return;
  41178. this._pixelRatio = value;
  41179. this.setSize( this._width, this._height, false );
  41180. }
  41181. /**
  41182. * This method allows to define the drawing buffer size by specifying
  41183. * width, height and pixel ratio all at once. The size of the drawing
  41184. * buffer is computed with this formula:
  41185. * ```js
  41186. * size.x = width * pixelRatio;
  41187. * size.y = height * pixelRatio;
  41188. * ```
  41189. *
  41190. * @param {number} width - The width in logical pixels.
  41191. * @param {number} height - The height in logical pixels.
  41192. * @param {number} pixelRatio - The pixel ratio.
  41193. */
  41194. setDrawingBufferSize( width, height, pixelRatio ) {
  41195. // Renderer can't be resized while presenting in XR.
  41196. if ( this.xr && this.xr.isPresenting ) return;
  41197. this._width = width;
  41198. this._height = height;
  41199. this._pixelRatio = pixelRatio;
  41200. this.domElement.width = Math.floor( width * pixelRatio );
  41201. this.domElement.height = Math.floor( height * pixelRatio );
  41202. this.setViewport( 0, 0, width, height );
  41203. this._dispatchResize();
  41204. }
  41205. /**
  41206. * Sets the size of the renderer.
  41207. *
  41208. * @param {number} width - The width in logical pixels.
  41209. * @param {number} height - The height in logical pixels.
  41210. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  41211. */
  41212. setSize( width, height, updateStyle = true ) {
  41213. // Renderer can't be resized while presenting in XR.
  41214. if ( this.xr && this.xr.isPresenting ) return;
  41215. this._width = width;
  41216. this._height = height;
  41217. this.domElement.width = Math.floor( width * this._pixelRatio );
  41218. this.domElement.height = Math.floor( height * this._pixelRatio );
  41219. if ( updateStyle === true ) {
  41220. this.domElement.style.width = width + 'px';
  41221. this.domElement.style.height = height + 'px';
  41222. }
  41223. this.setViewport( 0, 0, width, height );
  41224. this._dispatchResize();
  41225. }
  41226. /**
  41227. * Returns the scissor rectangle.
  41228. *
  41229. * @param {Vector4} target - The method writes the result in this target object.
  41230. * @return {Vector4} The scissor rectangle.
  41231. */
  41232. getScissor( target ) {
  41233. const scissor = this._scissor;
  41234. target.x = scissor.x;
  41235. target.y = scissor.y;
  41236. target.width = scissor.width;
  41237. target.height = scissor.height;
  41238. return target;
  41239. }
  41240. /**
  41241. * Defines the scissor rectangle.
  41242. *
  41243. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  41244. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  41245. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  41246. * @param {number} width - The width of the scissor box in logical pixel unit.
  41247. * @param {number} height - The height of the scissor box in logical pixel unit.
  41248. */
  41249. setScissor( x, y, width, height ) {
  41250. const scissor = this._scissor;
  41251. if ( x.isVector4 ) {
  41252. scissor.copy( x );
  41253. } else {
  41254. scissor.set( x, y, width, height );
  41255. }
  41256. }
  41257. /**
  41258. * Returns the scissor test value.
  41259. *
  41260. * @return {boolean} Whether the scissor test should be enabled or not.
  41261. */
  41262. getScissorTest() {
  41263. return this._scissorTest;
  41264. }
  41265. /**
  41266. * Defines the scissor test.
  41267. *
  41268. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41269. */
  41270. setScissorTest( boolean ) {
  41271. this._scissorTest = boolean;
  41272. }
  41273. /**
  41274. * Returns the viewport definition.
  41275. *
  41276. * @param {Vector4} target - The method writes the result in this target object.
  41277. * @return {Vector4} The viewport definition.
  41278. */
  41279. getViewport( target ) {
  41280. return target.copy( this._viewport );
  41281. }
  41282. /**
  41283. * Defines the viewport.
  41284. *
  41285. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  41286. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  41287. * @param {number} width - The width of the viewport in logical pixel unit.
  41288. * @param {number} height - The height of the viewport in logical pixel unit.
  41289. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  41290. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  41291. */
  41292. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  41293. const viewport = this._viewport;
  41294. if ( x.isVector4 ) {
  41295. viewport.copy( x );
  41296. } else {
  41297. viewport.set( x, y, width, height );
  41298. }
  41299. viewport.minDepth = minDepth;
  41300. viewport.maxDepth = maxDepth;
  41301. }
  41302. /**
  41303. * Dispatches the resize event.
  41304. *
  41305. * @private
  41306. */
  41307. _dispatchResize() {
  41308. this.dispatchEvent( { type: 'resize' } );
  41309. }
  41310. /**
  41311. * Frees the GPU-related resources allocated by this instance. Call this
  41312. * method whenever this instance is no longer used in your app.
  41313. *
  41314. * @fires RenderTarget#dispose
  41315. */
  41316. dispose() {
  41317. this.dispatchEvent( { type: 'dispose' } );
  41318. }
  41319. }
  41320. const _scene = /*@__PURE__*/ new Scene();
  41321. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  41322. const _screen = /*@__PURE__*/ new Vector4();
  41323. const _frustum = /*@__PURE__*/ new Frustum();
  41324. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  41325. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  41326. const _vector4 = /*@__PURE__*/ new Vector4();
  41327. const _shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  41328. /**
  41329. * Base class for renderers.
  41330. */
  41331. class Renderer {
  41332. /**
  41333. * Renderer options.
  41334. *
  41335. * @typedef {Object} Renderer~Options
  41336. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  41337. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  41338. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  41339. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  41340. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  41341. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  41342. * @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
  41343. * to overwrite the default.
  41344. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  41345. * @property {number} [outputBufferType=HalfFloatType] - Defines the type of output buffers. The default `HalfFloatType` is recommend for best
  41346. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  41347. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  41348. */
  41349. /**
  41350. * Constructs a new renderer.
  41351. *
  41352. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  41353. * @param {Renderer~Options} [parameters] - The configuration parameter.
  41354. */
  41355. constructor( backend, parameters = {} ) {
  41356. /**
  41357. * This flag can be used for type testing.
  41358. *
  41359. * @type {boolean}
  41360. * @readonly
  41361. * @default true
  41362. */
  41363. this.isRenderer = true;
  41364. //
  41365. const {
  41366. logarithmicDepthBuffer = false,
  41367. reversedDepthBuffer = false,
  41368. alpha = true,
  41369. depth = true,
  41370. stencil = false,
  41371. antialias = false,
  41372. samples = 0,
  41373. getFallback = null,
  41374. outputBufferType = HalfFloatType,
  41375. multiview = false
  41376. } = parameters;
  41377. /**
  41378. * A reference to the current backend.
  41379. *
  41380. * @type {Backend}
  41381. */
  41382. this.backend = backend;
  41383. /**
  41384. * Whether the renderer should automatically clear the current rendering target
  41385. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  41386. * or the current bound render target (custom framebuffer).
  41387. *
  41388. * @type {boolean}
  41389. * @default true
  41390. */
  41391. this.autoClear = true;
  41392. /**
  41393. * When `autoClear` is set to `true`, this property defines whether the renderer
  41394. * should clear the color buffer.
  41395. *
  41396. * @type {boolean}
  41397. * @default true
  41398. */
  41399. this.autoClearColor = true;
  41400. /**
  41401. * When `autoClear` is set to `true`, this property defines whether the renderer
  41402. * should clear the depth buffer.
  41403. *
  41404. * @type {boolean}
  41405. * @default true
  41406. */
  41407. this.autoClearDepth = true;
  41408. /**
  41409. * When `autoClear` is set to `true`, this property defines whether the renderer
  41410. * should clear the stencil buffer.
  41411. *
  41412. * @type {boolean}
  41413. * @default true
  41414. */
  41415. this.autoClearStencil = true;
  41416. /**
  41417. * Whether the default framebuffer should be transparent or opaque.
  41418. *
  41419. * @type {boolean}
  41420. * @default true
  41421. */
  41422. this.alpha = alpha;
  41423. /**
  41424. * Whether logarithmic depth buffer is enabled or not.
  41425. *
  41426. * @type {boolean}
  41427. * @default false
  41428. * @readonly
  41429. */
  41430. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  41431. /**
  41432. * Whether reversed depth buffer is enabled or not.
  41433. *
  41434. * @type {boolean}
  41435. * @default false
  41436. * @readonly
  41437. */
  41438. this.reversedDepthBuffer = reversedDepthBuffer;
  41439. /**
  41440. * Defines the output color space of the renderer.
  41441. *
  41442. * @type {string}
  41443. * @default SRGBColorSpace
  41444. */
  41445. this.outputColorSpace = SRGBColorSpace;
  41446. /**
  41447. * Defines the tone mapping of the renderer.
  41448. *
  41449. * @type {number}
  41450. * @default NoToneMapping
  41451. */
  41452. this.toneMapping = NoToneMapping;
  41453. /**
  41454. * Defines the tone mapping exposure.
  41455. *
  41456. * @type {number}
  41457. * @default 1
  41458. */
  41459. this.toneMappingExposure = 1.0;
  41460. /**
  41461. * Whether the renderer should sort its render lists or not.
  41462. *
  41463. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  41464. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  41465. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  41466. * e.g. manually determining each object's rendering order.
  41467. *
  41468. * @type {boolean}
  41469. * @default true
  41470. */
  41471. this.sortObjects = true;
  41472. /**
  41473. * Whether the default framebuffer should have a depth buffer or not.
  41474. *
  41475. * @type {boolean}
  41476. * @default true
  41477. */
  41478. this.depth = depth;
  41479. /**
  41480. * Whether the default framebuffer should have a stencil buffer or not.
  41481. *
  41482. * @type {boolean}
  41483. * @default false
  41484. */
  41485. this.stencil = stencil;
  41486. /**
  41487. * Holds a series of statistical information about the GPU memory
  41488. * and the rendering process. Useful for debugging and monitoring.
  41489. *
  41490. * @type {Info}
  41491. */
  41492. this.info = new Info();
  41493. /**
  41494. * A global context node that stores override nodes for specific transformations or calculations.
  41495. * These nodes can be used to replace default behavior in the rendering pipeline.
  41496. *
  41497. * @type {ContextNode}
  41498. * @property {Object} value - The context value object.
  41499. */
  41500. this.contextNode = context();
  41501. /**
  41502. * The node library defines how certain library objects like materials, lights
  41503. * or tone mapping functions are mapped to node types. This is required since
  41504. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  41505. * be part of the scene graph, they are internally represented as nodes for
  41506. * further processing.
  41507. *
  41508. * @type {NodeLibrary}
  41509. */
  41510. this.library = new NodeLibrary();
  41511. /**
  41512. * A map-like data structure for managing lights.
  41513. *
  41514. * @type {Lighting}
  41515. */
  41516. this.lighting = new Lighting();
  41517. // internals
  41518. /**
  41519. * The number of MSAA samples.
  41520. *
  41521. * @private
  41522. * @type {number}
  41523. * @default 0
  41524. */
  41525. this._samples = samples || ( antialias === true ) ? 4 : 0;
  41526. /**
  41527. * OnCanvasTargetResize callback function.
  41528. *
  41529. * @private
  41530. * @type {Function}
  41531. */
  41532. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  41533. /**
  41534. * The canvas target for rendering.
  41535. *
  41536. * @private
  41537. * @type {CanvasTarget}
  41538. */
  41539. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  41540. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  41541. this._canvasTarget.isDefaultCanvasTarget = true;
  41542. /**
  41543. * The inspector provides information about the internal renderer state.
  41544. *
  41545. * @private
  41546. * @type {InspectorBase}
  41547. */
  41548. this._inspector = new InspectorBase();
  41549. this._inspector.setRenderer( this );
  41550. /**
  41551. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  41552. *
  41553. * @private
  41554. * @type {?Function}
  41555. */
  41556. this._getFallback = getFallback;
  41557. /**
  41558. * A reference to a renderer module for managing shader attributes.
  41559. *
  41560. * @private
  41561. * @type {?Attributes}
  41562. * @default null
  41563. */
  41564. this._attributes = null;
  41565. /**
  41566. * A reference to a renderer module for managing geometries.
  41567. *
  41568. * @private
  41569. * @type {?Geometries}
  41570. * @default null
  41571. */
  41572. this._geometries = null;
  41573. /**
  41574. * A reference to a renderer module for managing node related logic.
  41575. *
  41576. * @private
  41577. * @type {?NodeManager}
  41578. * @default null
  41579. */
  41580. this._nodes = null;
  41581. /**
  41582. * A reference to a renderer module for managing the internal animation loop.
  41583. *
  41584. * @private
  41585. * @type {?Animation}
  41586. * @default null
  41587. */
  41588. this._animation = null;
  41589. /**
  41590. * A reference to a renderer module for managing shader program bindings.
  41591. *
  41592. * @private
  41593. * @type {?Bindings}
  41594. * @default null
  41595. */
  41596. this._bindings = null;
  41597. /**
  41598. * A reference to a renderer module for managing render objects.
  41599. *
  41600. * @private
  41601. * @type {?RenderObjects}
  41602. * @default null
  41603. */
  41604. this._objects = null;
  41605. /**
  41606. * A reference to a renderer module for managing render and compute pipelines.
  41607. *
  41608. * @private
  41609. * @type {?Pipelines}
  41610. * @default null
  41611. */
  41612. this._pipelines = null;
  41613. /**
  41614. * A reference to a renderer module for managing render bundles.
  41615. *
  41616. * @private
  41617. * @type {?RenderBundles}
  41618. * @default null
  41619. */
  41620. this._bundles = null;
  41621. /**
  41622. * A reference to a renderer module for managing render lists.
  41623. *
  41624. * @private
  41625. * @type {?RenderLists}
  41626. * @default null
  41627. */
  41628. this._renderLists = null;
  41629. /**
  41630. * A reference to a renderer module for managing render contexts.
  41631. *
  41632. * @private
  41633. * @type {?RenderContexts}
  41634. * @default null
  41635. */
  41636. this._renderContexts = null;
  41637. /**
  41638. * A reference to a renderer module for managing textures.
  41639. *
  41640. * @private
  41641. * @type {?Textures}
  41642. * @default null
  41643. */
  41644. this._textures = null;
  41645. /**
  41646. * A reference to a renderer module for backgrounds.
  41647. *
  41648. * @private
  41649. * @type {?Background}
  41650. * @default null
  41651. */
  41652. this._background = null;
  41653. /**
  41654. * Cache for the fullscreen quad.
  41655. * This fullscreen quad is used for internal render passes
  41656. * like the tone mapping and color space output pass.
  41657. *
  41658. * @private
  41659. * @type {Map<Texture,QuadMesh>}
  41660. */
  41661. this._quadCache = new Map();
  41662. /**
  41663. * A reference to the current render context.
  41664. *
  41665. * @private
  41666. * @type {?RenderContext}
  41667. * @default null
  41668. */
  41669. this._currentRenderContext = null;
  41670. /**
  41671. * A custom sort function for the opaque render list.
  41672. *
  41673. * @private
  41674. * @type {?Function}
  41675. * @default null
  41676. */
  41677. this._opaqueSort = null;
  41678. /**
  41679. * A custom sort function for the transparent render list.
  41680. *
  41681. * @private
  41682. * @type {?Function}
  41683. * @default null
  41684. */
  41685. this._transparentSort = null;
  41686. /**
  41687. * Cache of framebuffer targets per canvas target.
  41688. *
  41689. * @private
  41690. * @type {Map<CanvasTarget, RenderTarget>}
  41691. */
  41692. this._frameBufferTargets = new Map();
  41693. const alphaClear = this.alpha === true ? 0 : 1;
  41694. /**
  41695. * The clear color value.
  41696. *
  41697. * @private
  41698. * @type {Color4}
  41699. */
  41700. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  41701. /**
  41702. * The clear depth value.
  41703. *
  41704. * @private
  41705. * @type {number}
  41706. * @default 1
  41707. */
  41708. this._clearDepth = 1;
  41709. /**
  41710. * The clear stencil value.
  41711. *
  41712. * @private
  41713. * @type {number}
  41714. * @default 0
  41715. */
  41716. this._clearStencil = 0;
  41717. /**
  41718. * The current render target.
  41719. *
  41720. * @private
  41721. * @type {?RenderTarget}
  41722. * @default null
  41723. */
  41724. this._renderTarget = null;
  41725. /**
  41726. * The active cube face.
  41727. *
  41728. * @private
  41729. * @type {number}
  41730. * @default 0
  41731. */
  41732. this._activeCubeFace = 0;
  41733. /**
  41734. * The active mipmap level.
  41735. *
  41736. * @private
  41737. * @type {number}
  41738. * @default 0
  41739. */
  41740. this._activeMipmapLevel = 0;
  41741. /**
  41742. * The current output render target.
  41743. *
  41744. * @private
  41745. * @type {?RenderTarget}
  41746. * @default null
  41747. */
  41748. this._outputRenderTarget = null;
  41749. /**
  41750. * The MRT setting.
  41751. *
  41752. * @private
  41753. * @type {?MRTNode}
  41754. * @default null
  41755. */
  41756. this._mrt = null;
  41757. /**
  41758. * This function defines how a render object is going
  41759. * to be rendered.
  41760. *
  41761. * @private
  41762. * @type {?Function}
  41763. * @default null
  41764. */
  41765. this._renderObjectFunction = null;
  41766. /**
  41767. * Used to keep track of the current render object function.
  41768. *
  41769. * @private
  41770. * @type {?Function}
  41771. * @default null
  41772. */
  41773. this._currentRenderObjectFunction = null;
  41774. /**
  41775. * Used to keep track of the current render bundle.
  41776. *
  41777. * @private
  41778. * @type {?RenderBundle}
  41779. * @default null
  41780. */
  41781. this._currentRenderBundle = null;
  41782. /**
  41783. * Next to `_renderObjectFunction()`, this function provides another hook
  41784. * for influencing the render process of a render object. It is meant for internal
  41785. * use and only relevant for `compileAsync()` right now. Instead of using
  41786. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  41787. * a different function might be used which performs no draw but just the node
  41788. * and pipeline updates.
  41789. *
  41790. * @private
  41791. * @type {Function}
  41792. */
  41793. this._handleObjectFunction = this._renderObjectDirect;
  41794. /**
  41795. * Indicates whether the device has been lost or not. In WebGL terms, the device
  41796. * lost is considered as a context lost. When this is set to `true`, rendering
  41797. * isn't possible anymore.
  41798. *
  41799. * @private
  41800. * @type {boolean}
  41801. * @default false
  41802. */
  41803. this._isDeviceLost = false;
  41804. /**
  41805. * A callback function that defines what should happen when a device/context lost occurs.
  41806. *
  41807. * @type {Function}
  41808. */
  41809. this.onDeviceLost = this._onDeviceLost;
  41810. /**
  41811. * Defines the type of output buffers. The default `HalfFloatType` is recommend for
  41812. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  41813. * This will reduce rendering quality though.
  41814. *
  41815. * @private
  41816. * @type {number}
  41817. * @default HalfFloatType
  41818. */
  41819. this._outputBufferType = outputBufferType;
  41820. /**
  41821. * A cache for shadow nodes per material
  41822. *
  41823. * @private
  41824. * @type {WeakMap<Material, Object>}
  41825. */
  41826. this._cacheShadowNodes = new WeakMap();
  41827. /**
  41828. * Whether the renderer has been initialized or not.
  41829. *
  41830. * @private
  41831. * @type {boolean}
  41832. * @default false
  41833. */
  41834. this._initialized = false;
  41835. /**
  41836. * The call depth of the renderer. Counts the number of
  41837. * nested render calls.
  41838. *
  41839. * @private
  41840. * @type {number}
  41841. * @default - 1
  41842. */
  41843. this._callDepth = -1;
  41844. /**
  41845. * A reference to the promise which initializes the renderer.
  41846. *
  41847. * @private
  41848. * @type {?Promise<this>}
  41849. * @default null
  41850. */
  41851. this._initPromise = null;
  41852. /**
  41853. * An array of compilation promises which are used in `compileAsync()`.
  41854. *
  41855. * @private
  41856. * @type {?Array<Promise>}
  41857. * @default null
  41858. */
  41859. this._compilationPromises = null;
  41860. /**
  41861. * Whether the renderer should render transparent render objects or not.
  41862. *
  41863. * @type {boolean}
  41864. * @default true
  41865. */
  41866. this.transparent = true;
  41867. /**
  41868. * Whether the renderer should render opaque render objects or not.
  41869. *
  41870. * @type {boolean}
  41871. * @default true
  41872. */
  41873. this.opaque = true;
  41874. /**
  41875. * Shadow map configuration
  41876. * @typedef {Object} ShadowMapConfig
  41877. * @property {boolean} enabled - Whether to globally enable shadows or not.
  41878. * @property {boolean} transmitted - Whether to enable light transmission through non-opaque materials.
  41879. * @property {number} type - The shadow map type.
  41880. */
  41881. /**
  41882. * The renderer's shadow configuration.
  41883. *
  41884. * @type {ShadowMapConfig}
  41885. */
  41886. this.shadowMap = {
  41887. enabled: false,
  41888. transmitted: false,
  41889. type: PCFShadowMap
  41890. };
  41891. /**
  41892. * XR configuration.
  41893. * @typedef {Object} XRConfig
  41894. * @property {boolean} enabled - Whether to globally enable XR or not.
  41895. */
  41896. /**
  41897. * The renderer's XR manager.
  41898. *
  41899. * @type {XRManager}
  41900. */
  41901. this.xr = new XRManager( this, multiview );
  41902. /**
  41903. * Debug configuration.
  41904. * @typedef {Object} DebugConfig
  41905. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  41906. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  41907. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  41908. */
  41909. /**
  41910. * The renderer's debug configuration.
  41911. *
  41912. * @type {DebugConfig}
  41913. */
  41914. this.debug = {
  41915. checkShaderErrors: true,
  41916. onShaderError: null,
  41917. getShaderAsync: async ( scene, camera, object ) => {
  41918. await this.compileAsync( scene, camera );
  41919. const renderList = this._renderLists.get( scene, camera );
  41920. const renderContext = this._renderContexts.get( this._renderTarget, this._mrt );
  41921. const material = scene.overrideMaterial || object.material;
  41922. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  41923. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  41924. return { fragmentShader, vertexShader };
  41925. }
  41926. };
  41927. }
  41928. /**
  41929. * Initializes the renderer so it is ready for usage.
  41930. *
  41931. * @async
  41932. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  41933. */
  41934. async init() {
  41935. if ( this._initPromise !== null ) {
  41936. return this._initPromise;
  41937. }
  41938. this._initPromise = new Promise( async ( resolve, reject ) => {
  41939. let backend = this.backend;
  41940. try {
  41941. await backend.init( this );
  41942. } catch ( error ) {
  41943. if ( this._getFallback !== null ) {
  41944. // try the fallback
  41945. try {
  41946. this.backend = backend = this._getFallback( error );
  41947. await backend.init( this );
  41948. } catch ( error ) {
  41949. reject( error );
  41950. return;
  41951. }
  41952. } else {
  41953. reject( error );
  41954. return;
  41955. }
  41956. }
  41957. this._nodes = new NodeManager( this, backend );
  41958. this._animation = new Animation( this, this._nodes, this.info );
  41959. this._attributes = new Attributes( backend, this.info );
  41960. this._background = new Background( this, this._nodes );
  41961. this._geometries = new Geometries( this._attributes, this.info );
  41962. this._textures = new Textures( this, backend, this.info );
  41963. this._pipelines = new Pipelines( backend, this._nodes, this.info );
  41964. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  41965. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  41966. this._renderLists = new RenderLists( this.lighting );
  41967. this._bundles = new RenderBundles();
  41968. this._renderContexts = new RenderContexts( this );
  41969. //
  41970. this._animation.start();
  41971. this._initialized = true;
  41972. //
  41973. this._inspector.init();
  41974. //
  41975. resolve( this );
  41976. } );
  41977. return this._initPromise;
  41978. }
  41979. /**
  41980. * A reference to the canvas element the renderer is drawing to.
  41981. * This value of this property will automatically be created by
  41982. * the renderer.
  41983. *
  41984. * @type {HTMLCanvasElement|OffscreenCanvas}
  41985. */
  41986. get domElement() {
  41987. return this._canvasTarget.domElement;
  41988. }
  41989. /**
  41990. * The coordinate system of the renderer. The value of this property
  41991. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  41992. * `THREE.WebGPUCoordinateSystem`.
  41993. *
  41994. * @readonly
  41995. * @type {number}
  41996. */
  41997. get coordinateSystem() {
  41998. return this.backend.coordinateSystem;
  41999. }
  42000. /**
  42001. * Compiles all materials in the given scene. This can be useful to avoid a
  42002. * phenomenon which is called "shader compilation stutter", which occurs when
  42003. * rendering an object with a new shader for the first time.
  42004. *
  42005. * If you want to add a 3D object to an existing scene, use the third optional
  42006. * parameter for applying the target scene. Note that the (target) scene's lighting
  42007. * and environment must be configured before calling this method.
  42008. *
  42009. * @async
  42010. * @param {Object3D} scene - The scene or 3D object to precompile.
  42011. * @param {Camera} camera - The camera that is used to render the scene.
  42012. * @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.
  42013. * @return {Promise} A Promise that resolves when the compile has been finished.
  42014. */
  42015. async compileAsync( scene, camera, targetScene = null ) {
  42016. if ( this._isDeviceLost === true ) return;
  42017. if ( this._initialized === false ) await this.init();
  42018. // preserve render tree
  42019. const nodeFrame = this._nodes.nodeFrame;
  42020. const previousRenderId = nodeFrame.renderId;
  42021. const previousRenderContext = this._currentRenderContext;
  42022. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  42023. const previousHandleObjectFunction = this._handleObjectFunction;
  42024. const previousCompilationPromises = this._compilationPromises;
  42025. //
  42026. if ( targetScene === null ) targetScene = scene;
  42027. // Use the actual scene for caching when compiling individual objects
  42028. // This ensures cache keys match between compileAsync and render
  42029. const sceneRef = ( scene.isScene === true ) ? scene : ( targetScene.isScene === true ) ? targetScene : _scene;
  42030. // Match render()'s logic: use frameBufferTarget when needsFrameBufferTarget is true
  42031. const useFrameBufferTarget = this.needsFrameBufferTarget && this._renderTarget === null;
  42032. const renderTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : ( this._renderTarget || this._outputRenderTarget );
  42033. const renderContext = this._renderContexts.get( renderTarget, this._mrt );
  42034. const activeMipmapLevel = this._activeMipmapLevel;
  42035. const compilationPromises = [];
  42036. this._currentRenderContext = renderContext;
  42037. this._currentRenderObjectFunction = this.renderObject;
  42038. this._handleObjectFunction = this._createObjectPipeline;
  42039. this._compilationPromises = compilationPromises;
  42040. nodeFrame.renderId ++;
  42041. //
  42042. nodeFrame.update();
  42043. //
  42044. renderContext.depth = this.depth;
  42045. renderContext.stencil = this.stencil;
  42046. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  42047. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  42048. //
  42049. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  42050. //
  42051. // Use sceneRef for render list to ensure lightsNode matches between compileAsync and render
  42052. const renderList = this._renderLists.get( sceneRef, camera );
  42053. renderList.begin();
  42054. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  42055. // include lights from target scene
  42056. if ( targetScene !== scene ) {
  42057. targetScene.traverseVisible( function ( object ) {
  42058. if ( object.isLight && object.layers.test( camera.layers ) ) {
  42059. renderList.pushLight( object );
  42060. }
  42061. } );
  42062. }
  42063. renderList.finish();
  42064. //
  42065. if ( renderTarget !== null ) {
  42066. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  42067. const renderTargetData = this._textures.get( renderTarget );
  42068. renderContext.textures = renderTargetData.textures;
  42069. renderContext.depthTexture = renderTargetData.depthTexture;
  42070. } else {
  42071. renderContext.textures = null;
  42072. renderContext.depthTexture = null;
  42073. }
  42074. //
  42075. if ( targetScene !== scene ) {
  42076. this._background.update( targetScene, renderList, renderContext );
  42077. } else {
  42078. this._background.update( sceneRef, renderList, renderContext );
  42079. }
  42080. // process render lists - _createObjectPipeline will push async promises to _compilationPromises
  42081. const opaqueObjects = renderList.opaque;
  42082. const transparentObjects = renderList.transparent;
  42083. const transparentDoublePassObjects = renderList.transparentDoublePass;
  42084. const lightsNode = renderList.lightsNode;
  42085. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  42086. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  42087. // restore render tree
  42088. nodeFrame.renderId = previousRenderId;
  42089. this._currentRenderContext = previousRenderContext;
  42090. this._currentRenderObjectFunction = previousRenderObjectFunction;
  42091. this._handleObjectFunction = previousHandleObjectFunction;
  42092. this._compilationPromises = previousCompilationPromises;
  42093. // Process compilation work items sequentially to avoid freezing
  42094. // Yields between objects to keep animation smooth
  42095. for ( const item of compilationPromises ) {
  42096. const renderObject = this._objects.get( item.object, item.material, item.scene, item.camera, item.lightsNode, item.renderContext, item.clippingContext, item.passId );
  42097. renderObject.drawRange = item.object.geometry.drawRange;
  42098. renderObject.group = item.group;
  42099. this._geometries.updateForRender( renderObject );
  42100. // Use async node building to yield to main thread
  42101. await this._nodes.getForRenderAsync( renderObject );
  42102. this._nodes.updateBefore( renderObject );
  42103. this._nodes.updateForRender( renderObject );
  42104. this._bindings.updateForRender( renderObject );
  42105. // Wait for pipeline creation
  42106. const pipelinePromises = [];
  42107. this._pipelines.getForRender( renderObject, pipelinePromises );
  42108. if ( pipelinePromises.length > 0 ) {
  42109. await Promise.all( pipelinePromises );
  42110. }
  42111. this._nodes.updateAfter( renderObject );
  42112. // Yield between objects to allow animation frames
  42113. await yieldToMain();
  42114. }
  42115. }
  42116. /**
  42117. * Renders the scene in an async fashion.
  42118. *
  42119. * @async
  42120. * @deprecated
  42121. * @param {Object3D} scene - The scene or 3D object to render.
  42122. * @param {Camera} camera - The camera.
  42123. * @return {Promise} A Promise that resolves when the render has been finished.
  42124. */
  42125. async renderAsync( scene, camera ) {
  42126. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42127. await this.init();
  42128. this.render( scene, camera );
  42129. }
  42130. /**
  42131. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  42132. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  42133. *
  42134. * @async
  42135. * @deprecated
  42136. * @return {Promise} A Promise that resolves when synchronization has been finished.
  42137. */
  42138. async waitForGPU() {
  42139. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  42140. }
  42141. //
  42142. set inspector( value ) {
  42143. if ( this._inspector !== null ) {
  42144. this._inspector.setRenderer( null );
  42145. }
  42146. this._inspector = value;
  42147. this._inspector.setRenderer( this );
  42148. }
  42149. /**
  42150. * The inspector instance. The inspector can be any class that extends from `InspectorBase`.
  42151. *
  42152. * @type {InspectorBase}
  42153. */
  42154. get inspector() {
  42155. return this._inspector;
  42156. }
  42157. /**
  42158. * Enables or disables high precision for model-view and normal-view matrices.
  42159. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  42160. *
  42161. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  42162. *
  42163. * @param {boolean} value - Whether to enable or disable high precision.
  42164. * @type {boolean}
  42165. */
  42166. set highPrecision( value ) {
  42167. const contextNodeData = this.contextNode.value;
  42168. if ( value === true ) {
  42169. contextNodeData.modelViewMatrix = highpModelViewMatrix;
  42170. contextNodeData.modelNormalViewMatrix = highpModelNormalViewMatrix;
  42171. } else if ( this.highPrecision ) {
  42172. delete contextNodeData.modelViewMatrix;
  42173. delete contextNodeData.modelNormalViewMatrix;
  42174. }
  42175. }
  42176. /**
  42177. * Returns whether high precision is enabled or not.
  42178. *
  42179. * @return {boolean} Whether high precision is enabled or not.
  42180. * @type {boolean}
  42181. */
  42182. get highPrecision() {
  42183. const contextNodeData = this.contextNode.value;
  42184. return contextNodeData.modelViewMatrix === highpModelViewMatrix && contextNodeData.modelNormalViewMatrix === highpModelNormalViewMatrix;
  42185. }
  42186. /**
  42187. * Sets the given MRT configuration.
  42188. *
  42189. * @param {MRTNode} mrt - The MRT node to set.
  42190. * @return {Renderer} A reference to this renderer.
  42191. */
  42192. setMRT( mrt ) {
  42193. this._mrt = mrt;
  42194. return this;
  42195. }
  42196. /**
  42197. * Returns the MRT configuration.
  42198. *
  42199. * @return {MRTNode} The MRT configuration.
  42200. */
  42201. getMRT() {
  42202. return this._mrt;
  42203. }
  42204. /**
  42205. * Returns the output buffer type.
  42206. *
  42207. * @return {number} The output buffer type.
  42208. */
  42209. getOutputBufferType() {
  42210. return this._outputBufferType;
  42211. }
  42212. /**
  42213. * Returns the output buffer type.
  42214. *
  42215. * @deprecated since r182. Use `.getOutputBufferType()` instead.
  42216. * @return {number} The output buffer type.
  42217. */
  42218. getColorBufferType() { // @deprecated, r182
  42219. warnOnce( 'Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".' );
  42220. return this.getOutputBufferType();
  42221. }
  42222. /**
  42223. * Default implementation of the device lost callback.
  42224. *
  42225. * @private
  42226. * @param {Object} info - Information about the context lost.
  42227. */
  42228. _onDeviceLost( info ) {
  42229. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  42230. if ( info.reason ) {
  42231. errorMessage += `\nReason: ${info.reason}`;
  42232. }
  42233. error( errorMessage );
  42234. this._isDeviceLost = true;
  42235. }
  42236. /**
  42237. * Renders the given render bundle.
  42238. *
  42239. * @private
  42240. * @param {Object} bundle - Render bundle data.
  42241. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  42242. * @param {LightsNode} lightsNode - The lights node.
  42243. */
  42244. _renderBundle( bundle, sceneRef, lightsNode ) {
  42245. const { bundleGroup, camera, renderList } = bundle;
  42246. const renderContext = this._currentRenderContext;
  42247. //
  42248. const renderBundle = this._bundles.get( bundleGroup, camera );
  42249. const renderBundleData = this.backend.get( renderBundle );
  42250. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  42251. //
  42252. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  42253. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  42254. renderBundleData.renderContexts.add( renderContext );
  42255. if ( renderBundleNeedsUpdate ) {
  42256. this.backend.beginBundle( renderContext );
  42257. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  42258. renderBundleData.renderObjects = [];
  42259. }
  42260. this._currentRenderBundle = renderBundle;
  42261. const {
  42262. transparentDoublePass: transparentDoublePassObjects,
  42263. transparent: transparentObjects,
  42264. opaque: opaqueObjects
  42265. } = renderList;
  42266. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  42267. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  42268. this._currentRenderBundle = null;
  42269. //
  42270. this.backend.finishBundle( renderContext, renderBundle );
  42271. renderBundleData.version = bundleGroup.version;
  42272. } else {
  42273. const { renderObjects } = renderBundleData;
  42274. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  42275. const renderObject = renderObjects[ i ];
  42276. if ( this._nodes.needsRefresh( renderObject ) ) {
  42277. this._nodes.updateBefore( renderObject );
  42278. this._nodes.updateForRender( renderObject );
  42279. this._bindings.updateForRender( renderObject );
  42280. this._nodes.updateAfter( renderObject );
  42281. }
  42282. }
  42283. }
  42284. this.backend.addBundle( renderContext, renderBundle );
  42285. }
  42286. /**
  42287. * Renders the scene or 3D object with the given camera. This method can only be called
  42288. * if the renderer has been initialized. When using `render()` inside an animation loop,
  42289. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  42290. * with {@link Renderer#setAnimationLoop} though.
  42291. *
  42292. * For all other use cases (like when using on-demand rendering), you must call
  42293. * {@link Renderer#init} before rendering.
  42294. *
  42295. * The target of the method is the default framebuffer (meaning the canvas)
  42296. * or alternatively a render target when specified via `setRenderTarget()`.
  42297. *
  42298. * @param {Object3D} scene - The scene or 3D object to render.
  42299. * @param {Camera} camera - The camera to render the scene with.
  42300. */
  42301. render( scene, camera ) {
  42302. if ( this._initialized === false ) {
  42303. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  42304. }
  42305. this._renderScene( scene, camera );
  42306. }
  42307. /**
  42308. * Returns whether the renderer has been initialized or not.
  42309. *
  42310. * @readonly
  42311. * @return {boolean} Whether the renderer has been initialized or not.
  42312. */
  42313. get initialized() {
  42314. return this._initialized;
  42315. }
  42316. /**
  42317. * Returns an internal render target which is used when computing the output tone mapping
  42318. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  42319. * pass and not inline to achieve more correct results.
  42320. *
  42321. * @private
  42322. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  42323. */
  42324. _getFrameBufferTarget() {
  42325. const { currentToneMapping, currentColorSpace } = this;
  42326. const useToneMapping = currentToneMapping !== NoToneMapping;
  42327. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  42328. if ( useToneMapping === false && useColorSpace === false ) return null;
  42329. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  42330. const { depth, stencil } = this;
  42331. // TODO: Unify CanvasTarget and OutputRenderTarget
  42332. const target = this._outputRenderTarget || this._canvasTarget;
  42333. let frameBufferTarget = this._frameBufferTargets.get( target );
  42334. if ( frameBufferTarget === undefined ) {
  42335. frameBufferTarget = new RenderTarget( width, height, {
  42336. depthBuffer: depth,
  42337. stencilBuffer: stencil,
  42338. type: this._outputBufferType,
  42339. format: RGBAFormat,
  42340. colorSpace: ColorManagement.workingColorSpace,
  42341. generateMipmaps: false,
  42342. minFilter: LinearFilter,
  42343. magFilter: LinearFilter,
  42344. samples: this.samples
  42345. } );
  42346. frameBufferTarget.isPostProcessingRenderTarget = true;
  42347. const dispose = () => {
  42348. target.removeEventListener( 'dispose', dispose );
  42349. frameBufferTarget.dispose();
  42350. this._frameBufferTargets.delete( target );
  42351. };
  42352. target.addEventListener( 'dispose', dispose );
  42353. this._frameBufferTargets.set( target, frameBufferTarget );
  42354. }
  42355. const outputRenderTarget = this.getOutputRenderTarget();
  42356. frameBufferTarget.depthBuffer = depth;
  42357. frameBufferTarget.stencilBuffer = stencil;
  42358. if ( outputRenderTarget !== null ) {
  42359. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  42360. } else {
  42361. frameBufferTarget.setSize( width, height, 1 );
  42362. }
  42363. // RenderTarget || CanvasTarget
  42364. const viewport = this._outputRenderTarget ? this._outputRenderTarget.viewport : target._viewport;
  42365. const scissor = this._outputRenderTarget ? this._outputRenderTarget.scissor : target._scissor;
  42366. const pixelRatio = this._outputRenderTarget ? 1 : target._pixelRatio;
  42367. const scissorTest = this._outputRenderTarget ? this._outputRenderTarget.scissorTest : target._scissorTest;
  42368. frameBufferTarget.viewport.copy( viewport );
  42369. frameBufferTarget.scissor.copy( scissor );
  42370. frameBufferTarget.viewport.multiplyScalar( pixelRatio );
  42371. frameBufferTarget.scissor.multiplyScalar( pixelRatio );
  42372. frameBufferTarget.scissorTest = scissorTest;
  42373. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  42374. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  42375. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  42376. return frameBufferTarget;
  42377. }
  42378. /**
  42379. * Renders the scene or 3D object with the given camera.
  42380. *
  42381. * @private
  42382. * @param {Object3D} scene - The scene or 3D object to render.
  42383. * @param {Camera} camera - The camera to render the scene with.
  42384. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  42385. * @return {RenderContext} The current render context.
  42386. */
  42387. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  42388. if ( this._isDeviceLost === true ) return;
  42389. //
  42390. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  42391. // preserve render tree
  42392. const nodeFrame = this._nodes.nodeFrame;
  42393. const previousRenderId = nodeFrame.renderId;
  42394. const previousRenderContext = this._currentRenderContext;
  42395. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  42396. const previousHandleObjectFunction = this._handleObjectFunction;
  42397. //
  42398. this._callDepth ++;
  42399. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  42400. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  42401. const activeCubeFace = this._activeCubeFace;
  42402. const activeMipmapLevel = this._activeMipmapLevel;
  42403. //
  42404. let renderTarget;
  42405. if ( frameBufferTarget !== null ) {
  42406. renderTarget = frameBufferTarget;
  42407. this.setRenderTarget( renderTarget );
  42408. } else {
  42409. renderTarget = outputRenderTarget;
  42410. }
  42411. // make sure a new render target has correct default depth values
  42412. if ( renderTarget !== null && renderTarget.depthBuffer === true ) {
  42413. const renderTargetData = this._textures.get( renderTarget );
  42414. if ( renderTargetData.depthInitialized !== true ) {
  42415. // we need a single manual clear if auto clear depth is disabled
  42416. if ( this.autoClear === false || ( this.autoClear === true && this.autoClearDepth === false ) ) {
  42417. this.clearDepth();
  42418. }
  42419. renderTargetData.depthInitialized = true;
  42420. }
  42421. }
  42422. //
  42423. const renderContext = this._renderContexts.get( renderTarget, this._mrt, this._callDepth );
  42424. this._currentRenderContext = renderContext;
  42425. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  42426. this._handleObjectFunction = this._renderObjectDirect;
  42427. //
  42428. this.info.calls ++;
  42429. this.info.render.calls ++;
  42430. this.info.render.frameCalls ++;
  42431. nodeFrame.renderId = this.info.calls;
  42432. //
  42433. this.backend.updateTimeStampUID( renderContext );
  42434. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  42435. //
  42436. const xr = this.xr;
  42437. if ( xr.isPresenting === false ) {
  42438. let projectionMatrixNeedsUpdate = false;
  42439. // reversed depth
  42440. if ( this.reversedDepthBuffer === true && camera.reversedDepth !== true ) {
  42441. camera._reversedDepth = true;
  42442. if ( camera.isArrayCamera ) {
  42443. for ( const subCamera of camera.cameras ) {
  42444. subCamera._reversedDepth = true;
  42445. }
  42446. }
  42447. projectionMatrixNeedsUpdate = true;
  42448. }
  42449. // WebGPU/WebGL coordinate system
  42450. const coordinateSystem = this.coordinateSystem;
  42451. if ( camera.coordinateSystem !== coordinateSystem ) {
  42452. camera.coordinateSystem = coordinateSystem;
  42453. if ( camera.isArrayCamera ) {
  42454. for ( const subCamera of camera.cameras ) {
  42455. subCamera.coordinateSystem = coordinateSystem;
  42456. }
  42457. }
  42458. projectionMatrixNeedsUpdate = true;
  42459. }
  42460. // camera update
  42461. if ( projectionMatrixNeedsUpdate === true ) {
  42462. camera.updateProjectionMatrix();
  42463. if ( camera.isArrayCamera ) {
  42464. for ( const subCamera of camera.cameras ) {
  42465. subCamera.updateProjectionMatrix();
  42466. }
  42467. }
  42468. }
  42469. }
  42470. //
  42471. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  42472. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  42473. if ( xr.enabled === true && xr.isPresenting === true ) {
  42474. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  42475. camera = xr.getCamera(); // use XR camera for rendering
  42476. }
  42477. //
  42478. const canvasTarget = this._canvasTarget;
  42479. let viewport = canvasTarget._viewport;
  42480. let scissor = canvasTarget._scissor;
  42481. let pixelRatio = canvasTarget._pixelRatio;
  42482. if ( renderTarget !== null ) {
  42483. viewport = renderTarget.viewport;
  42484. scissor = renderTarget.scissor;
  42485. pixelRatio = 1;
  42486. }
  42487. this.getDrawingBufferSize( _drawingBufferSize );
  42488. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  42489. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  42490. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  42491. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  42492. renderContext.viewportValue.width >>= activeMipmapLevel;
  42493. renderContext.viewportValue.height >>= activeMipmapLevel;
  42494. renderContext.viewportValue.minDepth = minDepth;
  42495. renderContext.viewportValue.maxDepth = maxDepth;
  42496. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  42497. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  42498. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  42499. renderContext.scissorValue.width >>= activeMipmapLevel;
  42500. renderContext.scissorValue.height >>= activeMipmapLevel;
  42501. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  42502. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  42503. //
  42504. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  42505. //
  42506. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42507. if ( ! camera.isArrayCamera ) {
  42508. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  42509. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  42510. }
  42511. const renderList = this._renderLists.get( scene, camera );
  42512. renderList.begin();
  42513. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  42514. renderList.finish();
  42515. if ( this.sortObjects === true ) {
  42516. renderList.sort( this._opaqueSort, this._transparentSort );
  42517. }
  42518. //
  42519. if ( renderTarget !== null ) {
  42520. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  42521. const renderTargetData = this._textures.get( renderTarget );
  42522. renderContext.textures = renderTargetData.textures;
  42523. renderContext.depthTexture = renderTargetData.depthTexture;
  42524. renderContext.width = renderTargetData.width;
  42525. renderContext.height = renderTargetData.height;
  42526. renderContext.renderTarget = renderTarget;
  42527. renderContext.depth = renderTarget.depthBuffer;
  42528. renderContext.stencil = renderTarget.stencilBuffer;
  42529. } else {
  42530. renderContext.textures = null;
  42531. renderContext.depthTexture = null;
  42532. renderContext.width = _drawingBufferSize.width;
  42533. renderContext.height = _drawingBufferSize.height;
  42534. renderContext.depth = this.depth;
  42535. renderContext.stencil = this.stencil;
  42536. }
  42537. renderContext.width >>= activeMipmapLevel;
  42538. renderContext.height >>= activeMipmapLevel;
  42539. renderContext.activeCubeFace = activeCubeFace;
  42540. renderContext.activeMipmapLevel = activeMipmapLevel;
  42541. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  42542. //
  42543. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  42544. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  42545. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  42546. }
  42547. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  42548. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  42549. }
  42550. //
  42551. this._background.update( sceneRef, renderList, renderContext );
  42552. //
  42553. renderContext.camera = camera;
  42554. this.backend.beginRender( renderContext );
  42555. // process render lists
  42556. const {
  42557. bundles,
  42558. lightsNode,
  42559. transparentDoublePass: transparentDoublePassObjects,
  42560. transparent: transparentObjects,
  42561. opaque: opaqueObjects
  42562. } = renderList;
  42563. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  42564. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  42565. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  42566. // finish render pass
  42567. this.backend.finishRender( renderContext );
  42568. // restore render tree
  42569. nodeFrame.renderId = previousRenderId;
  42570. this._currentRenderContext = previousRenderContext;
  42571. this._currentRenderObjectFunction = previousRenderObjectFunction;
  42572. this._handleObjectFunction = previousHandleObjectFunction;
  42573. //
  42574. this._callDepth --;
  42575. if ( frameBufferTarget !== null ) {
  42576. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  42577. this._renderOutput( renderTarget );
  42578. }
  42579. //
  42580. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  42581. //
  42582. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  42583. //
  42584. return renderContext;
  42585. }
  42586. _setXRLayerSize( width, height ) {
  42587. // TODO: Find a better solution to resize the canvas when in XR.
  42588. this._canvasTarget._width = width;
  42589. this._canvasTarget._height = height;
  42590. this.setViewport( 0, 0, width, height );
  42591. }
  42592. /**
  42593. * The output pass performs tone mapping and color space conversion.
  42594. *
  42595. * @private
  42596. * @param {RenderTarget} renderTarget - The current render target.
  42597. */
  42598. _renderOutput( renderTarget ) {
  42599. const cacheKey = this._nodes.getOutputCacheKey();
  42600. let quadData = this._quadCache.get( renderTarget.texture );
  42601. let quad;
  42602. if ( quadData === undefined ) {
  42603. quad = new QuadMesh( new NodeMaterial() );
  42604. quad.name = 'Output Color Transform';
  42605. quad.material.name = 'outputColorTransform';
  42606. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  42607. quadData = {
  42608. quad,
  42609. cacheKey
  42610. };
  42611. this._quadCache.set( renderTarget.texture, quadData );
  42612. // dispose logic
  42613. const dispose = () => {
  42614. quad.material.dispose();
  42615. this._quadCache.delete( renderTarget.texture );
  42616. renderTarget.texture.removeEventListener( 'dispose', dispose );
  42617. };
  42618. renderTarget.texture.addEventListener( 'dispose', dispose );
  42619. } else {
  42620. quad = quadData.quad;
  42621. if ( quadData.cacheKey !== cacheKey ) {
  42622. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  42623. quad.material.needsUpdate = true;
  42624. quadData.cacheKey = cacheKey;
  42625. }
  42626. }
  42627. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  42628. const currentAutoClear = this.autoClear;
  42629. const currentXR = this.xr.enabled;
  42630. this.autoClear = false;
  42631. this.xr.enabled = false;
  42632. this._renderScene( quad, quad.camera, false );
  42633. this.autoClear = currentAutoClear;
  42634. this.xr.enabled = currentXR;
  42635. }
  42636. /**
  42637. * Returns the maximum available anisotropy for texture filtering.
  42638. *
  42639. * @return {number} The maximum available anisotropy.
  42640. */
  42641. getMaxAnisotropy() {
  42642. return this.backend.capabilities.getMaxAnisotropy();
  42643. }
  42644. /**
  42645. * Returns the active cube face.
  42646. *
  42647. * @return {number} The active cube face.
  42648. */
  42649. getActiveCubeFace() {
  42650. return this._activeCubeFace;
  42651. }
  42652. /**
  42653. * Returns the active mipmap level.
  42654. *
  42655. * @return {number} The active mipmap level.
  42656. */
  42657. getActiveMipmapLevel() {
  42658. return this._activeMipmapLevel;
  42659. }
  42660. /**
  42661. * Applications are advised to always define the animation loop
  42662. * with this method and not manually with `requestAnimationFrame()`
  42663. * for best compatibility.
  42664. *
  42665. * @async
  42666. * @param {?onAnimationCallback} callback - The application's animation loop.
  42667. * @return {Promise} A Promise that resolves when the set has been executed.
  42668. */
  42669. async setAnimationLoop( callback ) {
  42670. if ( this._initialized === false ) await this.init();
  42671. this._animation.setAnimationLoop( callback );
  42672. }
  42673. /**
  42674. * Returns the current animation loop callback.
  42675. *
  42676. * @return {?Function} The current animation loop callback.
  42677. */
  42678. getAnimationLoop() {
  42679. return this._animation.getAnimationLoop();
  42680. }
  42681. /**
  42682. * Can be used to transfer buffer data from a storage buffer attribute
  42683. * from the GPU to the CPU in context of compute shaders.
  42684. *
  42685. * @async
  42686. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42687. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42688. */
  42689. async getArrayBufferAsync( attribute ) {
  42690. return await this.backend.getArrayBufferAsync( attribute );
  42691. }
  42692. /**
  42693. * Returns the rendering context.
  42694. *
  42695. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  42696. */
  42697. getContext() {
  42698. return this.backend.getContext();
  42699. }
  42700. /**
  42701. * Returns the pixel ratio.
  42702. *
  42703. * @return {number} The pixel ratio.
  42704. */
  42705. getPixelRatio() {
  42706. return this._canvasTarget.getPixelRatio();
  42707. }
  42708. /**
  42709. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  42710. *
  42711. * @param {Vector2} target - The method writes the result in this target object.
  42712. * @return {Vector2} The drawing buffer size.
  42713. */
  42714. getDrawingBufferSize( target ) {
  42715. return this._canvasTarget.getDrawingBufferSize( target );
  42716. }
  42717. /**
  42718. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  42719. *
  42720. * @param {Vector2} target - The method writes the result in this target object.
  42721. * @return {Vector2} The renderer's size in logical pixels.
  42722. */
  42723. getSize( target ) {
  42724. return this._canvasTarget.getSize( target );
  42725. }
  42726. /**
  42727. * Sets the given pixel ratio and resizes the canvas if necessary.
  42728. *
  42729. * @param {number} [value=1] - The pixel ratio.
  42730. */
  42731. setPixelRatio( value = 1 ) {
  42732. this._canvasTarget.setPixelRatio( value );
  42733. }
  42734. /**
  42735. * This method allows to define the drawing buffer size by specifying
  42736. * width, height and pixel ratio all at once. The size of the drawing
  42737. * buffer is computed with this formula:
  42738. * ```js
  42739. * size.x = width * pixelRatio;
  42740. * size.y = height * pixelRatio;
  42741. * ```
  42742. *
  42743. * @param {number} width - The width in logical pixels.
  42744. * @param {number} height - The height in logical pixels.
  42745. * @param {number} pixelRatio - The pixel ratio.
  42746. */
  42747. setDrawingBufferSize( width, height, pixelRatio ) {
  42748. // Renderer can't be resized while presenting in XR.
  42749. if ( this.xr && this.xr.isPresenting ) return;
  42750. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  42751. }
  42752. /**
  42753. * Sets the size of the renderer.
  42754. *
  42755. * @param {number} width - The width in logical pixels.
  42756. * @param {number} height - The height in logical pixels.
  42757. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  42758. */
  42759. setSize( width, height, updateStyle = true ) {
  42760. // Renderer can't be resized while presenting in XR.
  42761. if ( this.xr && this.xr.isPresenting ) return;
  42762. this._canvasTarget.setSize( width, height, updateStyle );
  42763. }
  42764. /**
  42765. * Defines a manual sort function for the opaque render list.
  42766. * Pass `null` to use the default sort.
  42767. *
  42768. * @param {Function} method - The sort function.
  42769. */
  42770. setOpaqueSort( method ) {
  42771. this._opaqueSort = method;
  42772. }
  42773. /**
  42774. * Defines a manual sort function for the transparent render list.
  42775. * Pass `null` to use the default sort.
  42776. *
  42777. * @param {Function} method - The sort function.
  42778. */
  42779. setTransparentSort( method ) {
  42780. this._transparentSort = method;
  42781. }
  42782. /**
  42783. * Returns the scissor rectangle.
  42784. *
  42785. * @param {Vector4} target - The method writes the result in this target object.
  42786. * @return {Vector4} The scissor rectangle.
  42787. */
  42788. getScissor( target ) {
  42789. return this._canvasTarget.getScissor( target );
  42790. }
  42791. /**
  42792. * Defines the scissor rectangle.
  42793. *
  42794. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the box in logical pixel unit.
  42795. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  42796. * @param {number} y - The vertical coordinate for the upper left corner of the box in logical pixel unit.
  42797. * @param {number} width - The width of the scissor box in logical pixel unit.
  42798. * @param {number} height - The height of the scissor box in logical pixel unit.
  42799. */
  42800. setScissor( x, y, width, height ) {
  42801. this._canvasTarget.setScissor( x, y, width, height );
  42802. }
  42803. /**
  42804. * Returns the scissor test value.
  42805. *
  42806. * @return {boolean} Whether the scissor test should be enabled or not.
  42807. */
  42808. getScissorTest() {
  42809. return this._canvasTarget.getScissorTest();
  42810. }
  42811. /**
  42812. * Defines the scissor test.
  42813. *
  42814. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42815. */
  42816. setScissorTest( boolean ) {
  42817. this._canvasTarget.setScissorTest( boolean );
  42818. // TODO: Move it to CanvasTarget event listener.
  42819. this.backend.setScissorTest( boolean );
  42820. }
  42821. /**
  42822. * Returns the viewport definition.
  42823. *
  42824. * @param {Vector4} target - The method writes the result in this target object.
  42825. * @return {Vector4} The viewport definition.
  42826. */
  42827. getViewport( target ) {
  42828. return this._canvasTarget.getViewport( target );
  42829. }
  42830. /**
  42831. * Defines the viewport.
  42832. *
  42833. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the viewport origin in logical pixel unit.
  42834. * @param {number} y - The vertical coordinate for the upper left corner of the viewport origin in logical pixel unit.
  42835. * @param {number} width - The width of the viewport in logical pixel unit.
  42836. * @param {number} height - The height of the viewport in logical pixel unit.
  42837. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  42838. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  42839. */
  42840. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  42841. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  42842. }
  42843. /**
  42844. * Returns the clear color.
  42845. *
  42846. * @param {Color} target - The method writes the result in this target object.
  42847. * @return {Color} The clear color.
  42848. */
  42849. getClearColor( target ) {
  42850. return target.copy( this._clearColor );
  42851. }
  42852. /**
  42853. * Defines the clear color and optionally the clear alpha.
  42854. *
  42855. * @param {Color} color - The clear color.
  42856. * @param {number} [alpha=1] - The clear alpha.
  42857. */
  42858. setClearColor( color, alpha = 1 ) {
  42859. this._clearColor.set( color );
  42860. this._clearColor.a = alpha;
  42861. }
  42862. /**
  42863. * Returns the clear alpha.
  42864. *
  42865. * @return {number} The clear alpha.
  42866. */
  42867. getClearAlpha() {
  42868. return this._clearColor.a;
  42869. }
  42870. /**
  42871. * Defines the clear alpha.
  42872. *
  42873. * @param {number} alpha - The clear alpha.
  42874. */
  42875. setClearAlpha( alpha ) {
  42876. this._clearColor.a = alpha;
  42877. }
  42878. /**
  42879. * Returns the clear depth.
  42880. *
  42881. * @return {number} The clear depth.
  42882. */
  42883. getClearDepth() {
  42884. return ( this.reversedDepthBuffer === true ) ? 1 - this._clearDepth : this._clearDepth;
  42885. }
  42886. /**
  42887. * Defines the clear depth.
  42888. *
  42889. * @param {number} depth - The clear depth.
  42890. */
  42891. setClearDepth( depth ) {
  42892. this._clearDepth = depth;
  42893. }
  42894. /**
  42895. * Returns the clear stencil.
  42896. *
  42897. * @return {number} The clear stencil.
  42898. */
  42899. getClearStencil() {
  42900. return this._clearStencil;
  42901. }
  42902. /**
  42903. * Defines the clear stencil.
  42904. *
  42905. * @param {number} stencil - The clear stencil.
  42906. */
  42907. setClearStencil( stencil ) {
  42908. this._clearStencil = stencil;
  42909. }
  42910. /**
  42911. * This method performs an occlusion query for the given 3D object.
  42912. * It returns `true` if the given 3D object is fully occluded by other
  42913. * 3D objects in the scene.
  42914. *
  42915. * @param {Object3D} object - The 3D object to test.
  42916. * @return {boolean} Whether the 3D object is fully occluded or not.
  42917. */
  42918. isOccluded( object ) {
  42919. const renderContext = this._currentRenderContext;
  42920. return renderContext && this.backend.isOccluded( renderContext, object );
  42921. }
  42922. /**
  42923. * Performs a manual clear operation. This method ignores `autoClear` properties.
  42924. *
  42925. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42926. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42927. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42928. */
  42929. clear( color = true, depth = true, stencil = true ) {
  42930. if ( this._initialized === false ) {
  42931. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42932. }
  42933. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42934. let renderContext = null;
  42935. if ( renderTarget !== null ) {
  42936. this._textures.updateRenderTarget( renderTarget );
  42937. const renderTargetData = this._textures.get( renderTarget );
  42938. renderContext = this._renderContexts.get( renderTarget, null, -1 ); // using - 1 for the call depth to get a render context for the clear operation
  42939. renderContext.textures = renderTargetData.textures;
  42940. renderContext.depthTexture = renderTargetData.depthTexture;
  42941. renderContext.width = renderTargetData.width;
  42942. renderContext.height = renderTargetData.height;
  42943. renderContext.renderTarget = renderTarget;
  42944. renderContext.depth = renderTarget.depthBuffer;
  42945. renderContext.stencil = renderTarget.stencilBuffer;
  42946. // #30329
  42947. const color = this.backend.getClearColor();
  42948. renderContext.clearColorValue.r = color.r;
  42949. renderContext.clearColorValue.g = color.g;
  42950. renderContext.clearColorValue.b = color.b;
  42951. renderContext.clearColorValue.a = color.a;
  42952. renderContext.clearDepthValue = this.getClearDepth();
  42953. renderContext.clearStencilValue = this.getClearStencil();
  42954. renderContext.activeCubeFace = this.getActiveCubeFace();
  42955. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  42956. if ( renderTarget.depthBuffer === true ) renderTargetData.depthInitialized = true;
  42957. }
  42958. this.backend.clear( color, depth, stencil, renderContext );
  42959. if ( renderTarget !== null && this._renderTarget === null ) {
  42960. this._renderOutput( renderTarget );
  42961. }
  42962. }
  42963. /**
  42964. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  42965. */
  42966. clearColor() {
  42967. this.clear( true, false, false );
  42968. }
  42969. /**
  42970. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  42971. */
  42972. clearDepth() {
  42973. this.clear( false, true, false );
  42974. }
  42975. /**
  42976. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  42977. */
  42978. clearStencil() {
  42979. this.clear( false, false, true );
  42980. }
  42981. /**
  42982. * Async version of {@link Renderer#clear}.
  42983. *
  42984. * @async
  42985. * @deprecated
  42986. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42987. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42988. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42989. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42990. */
  42991. async clearAsync( color = true, depth = true, stencil = true ) {
  42992. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42993. await this.init();
  42994. this.clear( color, depth, stencil );
  42995. }
  42996. /**
  42997. * Async version of {@link Renderer#clearColor}.
  42998. *
  42999. * @async
  43000. * @deprecated
  43001. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  43002. */
  43003. async clearColorAsync() {
  43004. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  43005. this.clear( true, false, false );
  43006. }
  43007. /**
  43008. * Async version of {@link Renderer#clearDepth}.
  43009. *
  43010. * @async
  43011. * @deprecated
  43012. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  43013. */
  43014. async clearDepthAsync() {
  43015. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  43016. this.clear( false, true, false );
  43017. }
  43018. /**
  43019. * Async version of {@link Renderer#clearStencil}.
  43020. *
  43021. * @async
  43022. * @deprecated
  43023. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  43024. */
  43025. async clearStencilAsync() {
  43026. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  43027. this.clear( false, false, true );
  43028. }
  43029. /**
  43030. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  43031. * If this is the case, the renderer allocates an internal render target for that purpose.
  43032. *
  43033. */
  43034. get needsFrameBufferTarget() {
  43035. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  43036. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  43037. return useToneMapping || useColorSpace;
  43038. }
  43039. /**
  43040. * The number of samples used for multi-sample anti-aliasing (MSAA).
  43041. *
  43042. * @type {number}
  43043. * @default 0
  43044. */
  43045. get samples() {
  43046. return this._samples;
  43047. }
  43048. /**
  43049. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  43050. *
  43051. * When rendering to a custom render target, the number of samples of that render target is used.
  43052. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  43053. * the number of samples is set to 0.
  43054. *
  43055. * @type {number}
  43056. */
  43057. get currentSamples() {
  43058. let samples = this._samples;
  43059. if ( this._renderTarget !== null ) {
  43060. samples = this._renderTarget.samples;
  43061. } else if ( this.needsFrameBufferTarget ) {
  43062. samples = 0;
  43063. }
  43064. return samples;
  43065. }
  43066. /**
  43067. * The current tone mapping of the renderer. When not producing screen output,
  43068. * the tone mapping is always `NoToneMapping`.
  43069. *
  43070. * @type {number}
  43071. */
  43072. get currentToneMapping() {
  43073. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  43074. }
  43075. /**
  43076. * The current color space of the renderer. When not producing screen output,
  43077. * the color space is always the working color space.
  43078. *
  43079. * @type {string}
  43080. */
  43081. get currentColorSpace() {
  43082. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  43083. }
  43084. /**
  43085. * Returns `true` if the rendering settings are set to screen output.
  43086. *
  43087. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  43088. */
  43089. get isOutputTarget() {
  43090. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  43091. }
  43092. /**
  43093. * Frees all internal resources of the renderer. Call this method if the renderer
  43094. * is no longer in use by your app.
  43095. */
  43096. dispose() {
  43097. if ( this._initialized === true ) {
  43098. this.info.dispose();
  43099. this.backend.dispose();
  43100. this._animation.dispose();
  43101. this._objects.dispose();
  43102. this._geometries.dispose();
  43103. this._pipelines.dispose();
  43104. this._nodes.dispose();
  43105. this._bindings.dispose();
  43106. this._renderLists.dispose();
  43107. this._renderContexts.dispose();
  43108. this._textures.dispose();
  43109. for ( const canvasTarget of this._frameBufferTargets.keys() ) {
  43110. canvasTarget.dispose();
  43111. }
  43112. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  43113. if ( queryPool !== null ) queryPool.dispose();
  43114. } );
  43115. }
  43116. this.setRenderTarget( null );
  43117. this.setAnimationLoop( null );
  43118. }
  43119. /**
  43120. * Sets the given render target. Calling this method means the renderer does not
  43121. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  43122. * Use `null` as the first argument to reset the state.
  43123. *
  43124. * @param {?RenderTarget} renderTarget - The render target to set.
  43125. * @param {number} [activeCubeFace=0] - The active cube face.
  43126. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  43127. */
  43128. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  43129. this._renderTarget = renderTarget;
  43130. this._activeCubeFace = activeCubeFace;
  43131. this._activeMipmapLevel = activeMipmapLevel;
  43132. }
  43133. /**
  43134. * Returns the current render target.
  43135. *
  43136. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  43137. */
  43138. getRenderTarget() {
  43139. return this._renderTarget;
  43140. }
  43141. /**
  43142. * Sets the output render target for the renderer.
  43143. *
  43144. * @param {?RenderTarget} renderTarget - The render target to set as the output target.
  43145. */
  43146. setOutputRenderTarget( renderTarget ) {
  43147. this._outputRenderTarget = renderTarget;
  43148. }
  43149. /**
  43150. * Returns the current output target.
  43151. *
  43152. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  43153. */
  43154. getOutputRenderTarget() {
  43155. return this._outputRenderTarget;
  43156. }
  43157. /**
  43158. * Sets the canvas target. The canvas target manages the HTML canvas
  43159. * or the offscreen canvas the renderer draws into.
  43160. *
  43161. * @param {CanvasTarget} canvasTarget - The canvas target.
  43162. */
  43163. setCanvasTarget( canvasTarget ) {
  43164. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  43165. this._canvasTarget = canvasTarget;
  43166. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  43167. }
  43168. /**
  43169. * Returns the current canvas target.
  43170. *
  43171. * @return {CanvasTarget} The current canvas target.
  43172. */
  43173. getCanvasTarget() {
  43174. return this._canvasTarget;
  43175. }
  43176. /**
  43177. * Resets the renderer to the initial state before WebXR started.
  43178. *
  43179. * @private
  43180. */
  43181. _resetXRState() {
  43182. this.backend.setXRTarget( null );
  43183. this.setOutputRenderTarget( null );
  43184. this.setRenderTarget( null );
  43185. for ( const canvasTarget of this._frameBufferTargets.keys() ) {
  43186. canvasTarget.dispose();
  43187. }
  43188. }
  43189. /**
  43190. * Callback for {@link Renderer#setRenderObjectFunction}.
  43191. *
  43192. * @callback renderObjectFunction
  43193. * @param {Object3D} object - The 3D object.
  43194. * @param {Scene} scene - The scene the 3D object belongs to.
  43195. * @param {Camera} camera - The camera the object should be rendered with.
  43196. * @param {BufferGeometry} geometry - The object's geometry.
  43197. * @param {Material} material - The object's material.
  43198. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43199. * @param {LightsNode} lightsNode - The current lights node.
  43200. * @param {ClippingContext} clippingContext - The clipping context.
  43201. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  43202. */
  43203. /**
  43204. * Sets the given render object function. Calling this method overwrites the default implementation
  43205. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  43206. * if you want to modify the way objects are rendered. For example you can define things like "every
  43207. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  43208. * The custom function must always call `renderObject()` in its implementation.
  43209. *
  43210. * Use `null` as the first argument to reset the state.
  43211. *
  43212. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  43213. */
  43214. setRenderObjectFunction( renderObjectFunction ) {
  43215. this._renderObjectFunction = renderObjectFunction;
  43216. }
  43217. /**
  43218. * Returns the current render object function.
  43219. *
  43220. * @return {?Function} The current render object function. Returns `null` if no function is set.
  43221. */
  43222. getRenderObjectFunction() {
  43223. return this._renderObjectFunction;
  43224. }
  43225. /**
  43226. * Execute a single or an array of compute nodes. This method can only be called
  43227. * if the renderer has been initialized.
  43228. *
  43229. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  43230. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  43231. * - A single number representing count, or
  43232. * - An array [x, y, z] representing dispatch size, or
  43233. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  43234. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  43235. */
  43236. compute( computeNodes, dispatchSize = null ) {
  43237. if ( this._isDeviceLost === true ) return;
  43238. if ( this._initialized === false ) {
  43239. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  43240. return this.computeAsync( computeNodes, dispatchSize );
  43241. }
  43242. //
  43243. const nodeFrame = this._nodes.nodeFrame;
  43244. const previousRenderId = nodeFrame.renderId;
  43245. //
  43246. this.info.calls ++;
  43247. this.info.compute.calls ++;
  43248. this.info.compute.frameCalls ++;
  43249. nodeFrame.renderId = this.info.calls;
  43250. //
  43251. this.backend.updateTimeStampUID( computeNodes );
  43252. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  43253. //
  43254. const backend = this.backend;
  43255. const pipelines = this._pipelines;
  43256. const bindings = this._bindings;
  43257. const nodes = this._nodes;
  43258. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  43259. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  43260. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  43261. }
  43262. backend.beginCompute( computeNodes );
  43263. for ( const computeNode of computeList ) {
  43264. // onInit
  43265. if ( pipelines.has( computeNode ) === false ) {
  43266. const dispose = () => {
  43267. computeNode.removeEventListener( 'dispose', dispose );
  43268. pipelines.delete( computeNode );
  43269. bindings.deleteForCompute( computeNode );
  43270. nodes.delete( computeNode );
  43271. };
  43272. computeNode.addEventListener( 'dispose', dispose );
  43273. //
  43274. const onInitFn = computeNode.onInitFunction;
  43275. if ( onInitFn !== null ) {
  43276. onInitFn.call( computeNode, { renderer: this } );
  43277. }
  43278. }
  43279. nodes.updateForCompute( computeNode );
  43280. bindings.updateForCompute( computeNode );
  43281. const computeBindings = bindings.getForCompute( computeNode );
  43282. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  43283. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSize );
  43284. }
  43285. backend.finishCompute( computeNodes );
  43286. //
  43287. nodeFrame.renderId = previousRenderId;
  43288. //
  43289. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  43290. }
  43291. /**
  43292. * Execute a single or an array of compute nodes.
  43293. *
  43294. * @async
  43295. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  43296. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  43297. * - A single number representing count, or
  43298. * - An array [x, y, z] representing dispatch size, or
  43299. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  43300. * @return {Promise} A Promise that resolve when the compute has finished.
  43301. */
  43302. async computeAsync( computeNodes, dispatchSize = null ) {
  43303. if ( this._initialized === false ) await this.init();
  43304. this.compute( computeNodes, dispatchSize );
  43305. }
  43306. /**
  43307. * Checks if the given feature is supported by the selected backend.
  43308. *
  43309. * @async
  43310. * @deprecated
  43311. * @param {string} name - The feature's name.
  43312. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  43313. */
  43314. async hasFeatureAsync( name ) {
  43315. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  43316. await this.init();
  43317. return this.hasFeature( name );
  43318. }
  43319. async resolveTimestampsAsync( type = 'render' ) {
  43320. if ( this._initialized === false ) await this.init();
  43321. return this.backend.resolveTimestampsAsync( type );
  43322. }
  43323. /**
  43324. * Checks if the given feature is supported by the selected backend. If the
  43325. * renderer has not been initialized, this method always returns `false`.
  43326. *
  43327. * @param {string} name - The feature's name.
  43328. * @return {boolean} Whether the feature is supported or not.
  43329. */
  43330. hasFeature( name ) {
  43331. if ( this._initialized === false ) {
  43332. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  43333. }
  43334. return this.backend.hasFeature( name );
  43335. }
  43336. /**
  43337. * Returns `true` when the renderer has been initialized.
  43338. *
  43339. * @return {boolean} Whether the renderer has been initialized or not.
  43340. */
  43341. hasInitialized() {
  43342. return this._initialized;
  43343. }
  43344. /**
  43345. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  43346. * (which can cause noticeable lags due to decode and GPU upload overhead).
  43347. *
  43348. * @async
  43349. * @deprecated
  43350. * @param {Texture} texture - The texture.
  43351. * @return {Promise} A Promise that resolves when the texture has been initialized.
  43352. */
  43353. async initTextureAsync( texture ) {
  43354. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  43355. await this.init();
  43356. this.initTexture( texture );
  43357. }
  43358. /**
  43359. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  43360. * (which can cause noticeable lags due to decode and GPU upload overhead).
  43361. *
  43362. * This method can only be used if the renderer has been initialized.
  43363. *
  43364. * @param {Texture} texture - The texture.
  43365. */
  43366. initTexture( texture ) {
  43367. if ( this._initialized === false ) {
  43368. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  43369. }
  43370. this._textures.updateTexture( texture );
  43371. }
  43372. /**
  43373. * Initializes the given render target.
  43374. *
  43375. * @param {RenderTarget} renderTarget - The render target to intialize.
  43376. */
  43377. initRenderTarget( renderTarget ) {
  43378. if ( this._initialized === false ) {
  43379. throw new Error( 'Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  43380. }
  43381. this._textures.updateRenderTarget( renderTarget );
  43382. const renderTargetData = this._textures.get( renderTarget );
  43383. const renderContext = this._renderContexts.get( renderTarget );
  43384. renderContext.textures = renderTargetData.textures;
  43385. renderContext.depthTexture = renderTargetData.depthTexture;
  43386. renderContext.width = renderTargetData.width;
  43387. renderContext.height = renderTargetData.height;
  43388. renderContext.renderTarget = renderTarget;
  43389. renderContext.depth = renderTarget.depthBuffer;
  43390. renderContext.stencil = renderTarget.stencilBuffer;
  43391. this.backend.initRenderTarget( renderContext );
  43392. }
  43393. /**
  43394. * Copies the current bound framebuffer into the given texture.
  43395. *
  43396. * @param {FramebufferTexture} framebufferTexture - The texture.
  43397. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  43398. */
  43399. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  43400. if ( rectangle !== null ) {
  43401. if ( rectangle.isVector2 ) {
  43402. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  43403. } else if ( rectangle.isVector4 ) {
  43404. rectangle = _vector4.copy( rectangle ).floor();
  43405. } else {
  43406. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  43407. return;
  43408. }
  43409. } else {
  43410. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  43411. }
  43412. //
  43413. let renderContext = this._currentRenderContext;
  43414. let renderTarget;
  43415. if ( renderContext !== null ) {
  43416. renderTarget = renderContext.renderTarget;
  43417. } else {
  43418. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  43419. if ( renderTarget !== null ) {
  43420. this._textures.updateRenderTarget( renderTarget );
  43421. renderContext = this._textures.get( renderTarget );
  43422. }
  43423. }
  43424. //
  43425. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  43426. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  43427. this._inspector.copyFramebufferToTexture( framebufferTexture );
  43428. }
  43429. /**
  43430. * Copies data of the given source texture into a destination texture.
  43431. *
  43432. * @param {Texture} srcTexture - The source texture.
  43433. * @param {Texture} dstTexture - The destination texture.
  43434. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  43435. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  43436. * @param {number} [srcLevel=0] - The source mip level to copy from.
  43437. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  43438. */
  43439. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  43440. this._textures.updateTexture( srcTexture );
  43441. this._textures.updateTexture( dstTexture );
  43442. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  43443. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  43444. }
  43445. /**
  43446. * Reads pixel data from the given render target.
  43447. *
  43448. * @async
  43449. * @param {RenderTarget} renderTarget - The render target to read from.
  43450. * @param {number} x - The `x` coordinate of the copy region's origin.
  43451. * @param {number} y - The `y` coordinate of the copy region's origin.
  43452. * @param {number} width - The width of the copy region.
  43453. * @param {number} height - The height of the copy region.
  43454. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  43455. * @param {number} [faceIndex=0] - The active cube face index.
  43456. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  43457. */
  43458. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  43459. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  43460. }
  43461. /**
  43462. * Analyzes the given 3D object's hierarchy and builds render lists from the
  43463. * processed hierarchy.
  43464. *
  43465. * @private
  43466. * @param {Object3D} object - The 3D object to process (usually a scene).
  43467. * @param {Camera} camera - The camera the object is rendered with.
  43468. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  43469. * @param {RenderList} renderList - The current render list.
  43470. * @param {ClippingContext} clippingContext - The current clipping context.
  43471. */
  43472. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  43473. if ( object.visible === false ) return;
  43474. const visible = object.layers.test( camera.layers );
  43475. if ( visible ) {
  43476. if ( object.isGroup ) {
  43477. groupOrder = object.renderOrder;
  43478. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  43479. } else if ( object.isLOD ) {
  43480. if ( object.autoUpdate === true ) object.update( camera );
  43481. } else if ( object.isLight ) {
  43482. renderList.pushLight( object );
  43483. } else if ( object.isSprite ) {
  43484. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  43485. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  43486. if ( this.sortObjects === true ) {
  43487. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  43488. }
  43489. const { geometry, material } = object;
  43490. if ( material.visible ) {
  43491. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  43492. }
  43493. }
  43494. } else if ( object.isLineLoop ) {
  43495. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  43496. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  43497. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  43498. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  43499. const { geometry, material } = object;
  43500. if ( this.sortObjects === true ) {
  43501. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  43502. _vector4
  43503. .copy( geometry.boundingSphere.center )
  43504. .applyMatrix4( object.matrixWorld )
  43505. .applyMatrix4( _projScreenMatrix );
  43506. }
  43507. if ( Array.isArray( material ) ) {
  43508. const groups = geometry.groups;
  43509. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  43510. const group = groups[ i ];
  43511. const groupMaterial = material[ group.materialIndex ];
  43512. if ( groupMaterial && groupMaterial.visible ) {
  43513. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  43514. }
  43515. }
  43516. } else if ( material.visible ) {
  43517. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  43518. }
  43519. }
  43520. }
  43521. }
  43522. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  43523. const baseRenderList = renderList;
  43524. // replace render list
  43525. renderList = this._renderLists.get( object, camera );
  43526. renderList.begin();
  43527. baseRenderList.pushBundle( {
  43528. bundleGroup: object,
  43529. camera,
  43530. renderList,
  43531. } );
  43532. renderList.finish();
  43533. }
  43534. const children = object.children;
  43535. for ( let i = 0, l = children.length; i < l; i ++ ) {
  43536. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  43537. }
  43538. }
  43539. /**
  43540. * Renders the given render bundles.
  43541. *
  43542. * @private
  43543. * @param {Array<Object>} bundles - Array with render bundle data.
  43544. * @param {Scene} sceneRef - The scene the render bundles belong to.
  43545. * @param {LightsNode} lightsNode - The current lights node.
  43546. */
  43547. _renderBundles( bundles, sceneRef, lightsNode ) {
  43548. for ( const bundle of bundles ) {
  43549. this._renderBundle( bundle, sceneRef, lightsNode );
  43550. }
  43551. }
  43552. /**
  43553. * Renders the transparent objects from the given render lists.
  43554. *
  43555. * @private
  43556. * @param {Array<Object>} renderList - The transparent render list.
  43557. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  43558. * @param {Camera} camera - The camera the render list should be rendered with.
  43559. * @param {Scene} scene - The scene the render list belongs to.
  43560. * @param {LightsNode} lightsNode - The current lights node.
  43561. */
  43562. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  43563. if ( doublePassList.length > 0 ) {
  43564. // render back side
  43565. for ( const { material } of doublePassList ) {
  43566. material.side = BackSide;
  43567. }
  43568. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  43569. // render front side
  43570. for ( const { material } of doublePassList ) {
  43571. material.side = FrontSide;
  43572. }
  43573. this._renderObjects( renderList, camera, scene, lightsNode );
  43574. // restore
  43575. for ( const { material } of doublePassList ) {
  43576. material.side = DoubleSide;
  43577. }
  43578. } else {
  43579. this._renderObjects( renderList, camera, scene, lightsNode );
  43580. }
  43581. }
  43582. /**
  43583. * Renders the objects from the given render list.
  43584. *
  43585. * @private
  43586. * @param {Array<Object>} renderList - The render list.
  43587. * @param {Camera} camera - The camera the render list should be rendered with.
  43588. * @param {Scene} scene - The scene the render list belongs to.
  43589. * @param {LightsNode} lightsNode - The current lights node.
  43590. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  43591. */
  43592. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  43593. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  43594. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  43595. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  43596. }
  43597. }
  43598. /**
  43599. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  43600. * The result is cached per material and updated when the material's version changes.
  43601. *
  43602. * @private
  43603. * @param {Material} material
  43604. * @returns {Object} - The shadow nodes for the material.
  43605. */
  43606. _getShadowNodes( material ) {
  43607. const version = material.version;
  43608. let cache = this._cacheShadowNodes.get( material );
  43609. if ( cache === undefined || cache.version !== version ) {
  43610. const hasMap = material.map !== null;
  43611. const hasColorNode = material.colorNode && material.colorNode.isNode;
  43612. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  43613. const hasMaskNode = ( material.maskShadowNode && material.maskShadowNode.isNode ) || ( material.maskNode && material.maskNode.isNode );
  43614. let positionNode = null;
  43615. let colorNode = null;
  43616. let depthNode = null;
  43617. if ( hasMap || hasColorNode || hasCastShadowNode || hasMaskNode ) {
  43618. let shadowRGB;
  43619. let shadowAlpha;
  43620. if ( hasCastShadowNode ) {
  43621. shadowRGB = material.castShadowNode.rgb;
  43622. shadowAlpha = material.castShadowNode.a;
  43623. if ( this.shadowMap.transmitted !== true ) {
  43624. warnOnce( 'Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.' );
  43625. }
  43626. } else {
  43627. shadowRGB = vec3( 0 );
  43628. shadowAlpha = float( 1 );
  43629. }
  43630. if ( hasMap ) {
  43631. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  43632. }
  43633. if ( hasColorNode ) {
  43634. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  43635. }
  43636. colorNode = vec4( shadowRGB, shadowAlpha );
  43637. if ( hasMaskNode ) {
  43638. const maskNode = material.maskShadowNode || material.maskNode;
  43639. colorNode = Fn( ( [ color ] ) => {
  43640. maskNode.not().discard();
  43641. return color;
  43642. } )( colorNode );
  43643. }
  43644. }
  43645. if ( material.depthNode && material.depthNode.isNode ) {
  43646. depthNode = material.depthNode;
  43647. }
  43648. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  43649. positionNode = material.castShadowPositionNode;
  43650. } else if ( material.positionNode && material.positionNode.isNode ) {
  43651. positionNode = material.positionNode;
  43652. }
  43653. cache = {
  43654. version,
  43655. colorNode,
  43656. depthNode,
  43657. positionNode
  43658. };
  43659. this._cacheShadowNodes.set( material, cache );
  43660. }
  43661. return cache;
  43662. }
  43663. /**
  43664. * This method represents the default render object function that manages the render lifecycle
  43665. * of the object.
  43666. *
  43667. * @param {Object3D} object - The 3D object.
  43668. * @param {Scene} scene - The scene the 3D object belongs to.
  43669. * @param {Camera} camera - The camera the object should be rendered with.
  43670. * @param {BufferGeometry} geometry - The object's geometry.
  43671. * @param {Material} material - The object's material.
  43672. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43673. * @param {LightsNode} lightsNode - The current lights node.
  43674. * @param {?ClippingContext} clippingContext - The clipping context.
  43675. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  43676. */
  43677. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  43678. let materialOverride = false;
  43679. let materialColorNode;
  43680. let materialDepthNode;
  43681. let materialPositionNode;
  43682. let materialSide;
  43683. //
  43684. object.onBeforeRender( this, scene, camera, geometry, material, group );
  43685. //
  43686. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  43687. const overrideMaterial = scene.overrideMaterial;
  43688. materialOverride = true;
  43689. // store original nodes
  43690. materialColorNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.colorNode : null;
  43691. materialDepthNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.depthNode : null;
  43692. materialPositionNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.positionNode : null;
  43693. materialSide = scene.overrideMaterial.side;
  43694. if ( material.positionNode && material.positionNode.isNode ) {
  43695. overrideMaterial.positionNode = material.positionNode;
  43696. }
  43697. overrideMaterial.alphaTest = material.alphaTest;
  43698. overrideMaterial.alphaMap = material.alphaMap;
  43699. overrideMaterial.transparent = material.transparent || material.transmission > 0 ||
  43700. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  43701. ( material.backdropNode && material.backdropNode.isNode );
  43702. if ( overrideMaterial.isShadowPassMaterial ) {
  43703. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  43704. if ( this.shadowMap.type === VSMShadowMap ) {
  43705. overrideMaterial.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  43706. } else {
  43707. overrideMaterial.side = ( material.shadowSide !== null ) ? material.shadowSide : _shadowSide[ material.side ];
  43708. }
  43709. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  43710. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  43711. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  43712. }
  43713. material = overrideMaterial;
  43714. }
  43715. //
  43716. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  43717. material.side = BackSide;
  43718. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  43719. material.side = FrontSide;
  43720. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  43721. material.side = DoubleSide;
  43722. } else {
  43723. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  43724. }
  43725. //
  43726. if ( materialOverride ) {
  43727. scene.overrideMaterial.colorNode = materialColorNode;
  43728. scene.overrideMaterial.depthNode = materialDepthNode;
  43729. scene.overrideMaterial.positionNode = materialPositionNode;
  43730. scene.overrideMaterial.side = materialSide;
  43731. }
  43732. //
  43733. object.onAfterRender( this, scene, camera, geometry, material, group );
  43734. }
  43735. /**
  43736. * Checks if the given compatibility is supported by the selected backend.
  43737. *
  43738. * @param {string} name - The compatibility's name.
  43739. * @return {boolean} Whether the compatibility is supported or not.
  43740. */
  43741. hasCompatibility( name ) {
  43742. if ( this._initialized === false ) {
  43743. throw new Error( 'Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.' );
  43744. }
  43745. return this.backend.hasCompatibility( name );
  43746. }
  43747. /**
  43748. * This method represents the default `_handleObjectFunction` implementation which creates
  43749. * a render object from the given data and performs the draw command with the selected backend.
  43750. *
  43751. * @private
  43752. * @param {Object3D} object - The 3D object.
  43753. * @param {Material} material - The object's material.
  43754. * @param {Scene} scene - The scene the 3D object belongs to.
  43755. * @param {Camera} camera - The camera the object should be rendered with.
  43756. * @param {LightsNode} lightsNode - The current lights node.
  43757. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43758. * @param {ClippingContext} clippingContext - The clipping context.
  43759. * @param {string} [passId] - An optional ID for identifying the pass.
  43760. */
  43761. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43762. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43763. renderObject.drawRange = object.geometry.drawRange;
  43764. renderObject.group = group;
  43765. if ( this._currentRenderBundle !== null ) {
  43766. const renderBundleData = this.backend.get( this._currentRenderBundle );
  43767. renderBundleData.renderObjects.push( renderObject );
  43768. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  43769. }
  43770. //
  43771. const needsRefresh = this._nodes.needsRefresh( renderObject );
  43772. if ( needsRefresh ) {
  43773. this._nodes.updateBefore( renderObject );
  43774. this._geometries.updateForRender( renderObject );
  43775. this._nodes.updateForRender( renderObject );
  43776. this._bindings.updateForRender( renderObject );
  43777. }
  43778. this._pipelines.updateForRender( renderObject );
  43779. //
  43780. if ( this._pipelines.isReady( renderObject ) ) {
  43781. this.backend.draw( renderObject, this.info );
  43782. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  43783. }
  43784. }
  43785. /**
  43786. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  43787. * Used in `compileAsync()`.
  43788. *
  43789. * @private
  43790. * @param {Object3D} object - The 3D object.
  43791. * @param {Material} material - The object's material.
  43792. * @param {Scene} scene - The scene the 3D object belongs to.
  43793. * @param {Camera} camera - The camera the object should be rendered with.
  43794. * @param {LightsNode} lightsNode - The current lights node.
  43795. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43796. * @param {ClippingContext} clippingContext - The clipping context.
  43797. * @param {string} [passId] - An optional ID for identifying the pass.
  43798. */
  43799. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43800. // If in async compilation mode, queue the work for sequential execution
  43801. if ( this._compilationPromises !== null ) {
  43802. // Store work items instead of promises - will be processed sequentially
  43803. this._compilationPromises.push( {
  43804. object,
  43805. material,
  43806. scene,
  43807. camera,
  43808. lightsNode,
  43809. group,
  43810. clippingContext,
  43811. passId,
  43812. renderContext: this._currentRenderContext
  43813. } );
  43814. return;
  43815. }
  43816. // Sync path
  43817. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43818. renderObject.drawRange = object.geometry.drawRange;
  43819. renderObject.group = group;
  43820. //
  43821. this._nodes.updateBefore( renderObject );
  43822. this._geometries.updateForRender( renderObject );
  43823. this._nodes.updateForRender( renderObject );
  43824. this._bindings.updateForRender( renderObject );
  43825. this._pipelines.getForRender( renderObject, this._compilationPromises );
  43826. this._nodes.updateAfter( renderObject );
  43827. }
  43828. /**
  43829. * Callback when the canvas has been resized.
  43830. *
  43831. * @private
  43832. */
  43833. _onCanvasTargetResize() {
  43834. if ( this._initialized ) this.backend.updateSize();
  43835. }
  43836. /**
  43837. * Alias for `compileAsync()`.
  43838. *
  43839. * @method
  43840. * @param {Object3D} scene - The scene or 3D object to precompile.
  43841. * @param {Camera} camera - The camera that is used to render the scene.
  43842. * @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.
  43843. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  43844. */
  43845. get compile() {
  43846. return this.compileAsync;
  43847. }
  43848. }
  43849. /**
  43850. * A binding represents the connection between a resource (like a texture, sampler
  43851. * or uniform buffer) and the resource definition in a shader stage.
  43852. *
  43853. * This module is an abstract base class for all concrete bindings types.
  43854. *
  43855. * @abstract
  43856. * @private
  43857. */
  43858. class Binding {
  43859. /**
  43860. * Constructs a new binding.
  43861. *
  43862. * @param {string} [name=''] - The binding's name.
  43863. */
  43864. constructor( name = '' ) {
  43865. /**
  43866. * The binding's name.
  43867. *
  43868. * @type {string}
  43869. */
  43870. this.name = name;
  43871. /**
  43872. * A bitmask that defines in what shader stages the
  43873. * binding's resource is accessible.
  43874. *
  43875. * @type {number}
  43876. */
  43877. this.visibility = 0;
  43878. }
  43879. /**
  43880. * Makes sure binding's resource is visible for the given shader stage.
  43881. *
  43882. * @param {number} visibility - The shader stage.
  43883. */
  43884. setVisibility( visibility ) {
  43885. this.visibility |= visibility;
  43886. }
  43887. /**
  43888. * The shader stages in which the binding's resource is visible.
  43889. *
  43890. * @return {number} The visibility bitmask.
  43891. */
  43892. getVisibility() {
  43893. return this.visibility;
  43894. }
  43895. /**
  43896. * Clones the binding.
  43897. *
  43898. * @return {Binding} The cloned binding.
  43899. */
  43900. clone() {
  43901. return Object.assign( new this.constructor(), this );
  43902. }
  43903. }
  43904. /**
  43905. * This function is usually called with the length in bytes of an array buffer.
  43906. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  43907. *
  43908. * @function
  43909. * @param {number} floatLength - The buffer length.
  43910. * @return {number} The padded length.
  43911. */
  43912. function getFloatLength( floatLength ) {
  43913. // ensure chunk size alignment (STD140 layout)
  43914. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  43915. }
  43916. /**
  43917. * Represents a buffer binding type.
  43918. *
  43919. * @private
  43920. * @abstract
  43921. * @augments Binding
  43922. */
  43923. class Buffer extends Binding {
  43924. /**
  43925. * Constructs a new buffer.
  43926. *
  43927. * @param {string} name - The buffer's name.
  43928. * @param {TypedArray} [buffer=null] - The buffer.
  43929. */
  43930. constructor( name, buffer = null ) {
  43931. super( name );
  43932. /**
  43933. * This flag can be used for type testing.
  43934. *
  43935. * @type {boolean}
  43936. * @readonly
  43937. * @default true
  43938. */
  43939. this.isBuffer = true;
  43940. /**
  43941. * The bytes per element.
  43942. *
  43943. * @type {number}
  43944. */
  43945. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  43946. /**
  43947. * A reference to the internal buffer.
  43948. *
  43949. * @private
  43950. * @type {TypedArray}
  43951. */
  43952. this._buffer = buffer;
  43953. /**
  43954. * An array of update ranges.
  43955. *
  43956. * @private
  43957. * @type {Array<{start: number, count: number}>}
  43958. */
  43959. this._updateRanges = [];
  43960. }
  43961. /**
  43962. * The array of update ranges.
  43963. *
  43964. * @type {Array<{start: number, count: number}>}
  43965. */
  43966. get updateRanges() {
  43967. return this._updateRanges;
  43968. }
  43969. /**
  43970. * Adds an update range.
  43971. *
  43972. * @param {number} start - The start index.
  43973. * @param {number} count - The number of elements.
  43974. */
  43975. addUpdateRange( start, count ) {
  43976. this.updateRanges.push( { start, count } );
  43977. }
  43978. /**
  43979. * Clears all update ranges.
  43980. */
  43981. clearUpdateRanges() {
  43982. this.updateRanges.length = 0;
  43983. }
  43984. /**
  43985. * The buffer's byte length.
  43986. *
  43987. * @type {number}
  43988. * @readonly
  43989. */
  43990. get byteLength() {
  43991. return getFloatLength( this._buffer.byteLength );
  43992. }
  43993. /**
  43994. * A reference to the internal buffer.
  43995. *
  43996. * @type {Float32Array}
  43997. * @readonly
  43998. */
  43999. get buffer() {
  44000. return this._buffer;
  44001. }
  44002. /**
  44003. * Updates the binding.
  44004. *
  44005. * @return {boolean} Whether the buffer has been updated and must be
  44006. * uploaded to the GPU.
  44007. */
  44008. update() {
  44009. return true;
  44010. }
  44011. }
  44012. /**
  44013. * Represents a uniform buffer binding type.
  44014. *
  44015. * @private
  44016. * @augments Buffer
  44017. */
  44018. class UniformBuffer extends Buffer {
  44019. /**
  44020. * Constructs a new uniform buffer.
  44021. *
  44022. * @param {string} name - The buffer's name.
  44023. * @param {TypedArray} [buffer=null] - The buffer.
  44024. */
  44025. constructor( name, buffer = null ) {
  44026. super( name, buffer );
  44027. /**
  44028. * This flag can be used for type testing.
  44029. *
  44030. * @type {boolean}
  44031. * @readonly
  44032. * @default true
  44033. */
  44034. this.isUniformBuffer = true;
  44035. }
  44036. }
  44037. let _id$4 = 0;
  44038. /**
  44039. * A special form of uniform buffer binding type.
  44040. * It's buffer value is managed by a node object.
  44041. *
  44042. * @private
  44043. * @augments UniformBuffer
  44044. */
  44045. class NodeUniformBuffer extends UniformBuffer {
  44046. /**
  44047. * Constructs a new node-based uniform buffer.
  44048. *
  44049. * @param {BufferNode} nodeUniform - The uniform buffer node.
  44050. * @param {UniformGroupNode} groupNode - The uniform group node.
  44051. */
  44052. constructor( nodeUniform, groupNode ) {
  44053. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  44054. /**
  44055. * The uniform buffer node.
  44056. *
  44057. * @type {BufferNode}
  44058. */
  44059. this.nodeUniform = nodeUniform;
  44060. /**
  44061. * The uniform group node.
  44062. *
  44063. * @type {UniformGroupNode}
  44064. */
  44065. this.groupNode = groupNode;
  44066. /**
  44067. * This flag can be used for type testing.
  44068. *
  44069. * @type {boolean}
  44070. * @readonly
  44071. * @default true
  44072. */
  44073. this.isNodeUniformBuffer = true;
  44074. }
  44075. /**
  44076. * The array of update ranges.
  44077. *
  44078. * @param {Array<{start: number, count: number}>} value - The update ranges.
  44079. */
  44080. set updateRanges( value ) {
  44081. this.nodeUniform.updateRanges = value;
  44082. }
  44083. /**
  44084. * The array of update ranges.
  44085. *
  44086. * @type {Array<{start: number, count: number}>}
  44087. */
  44088. get updateRanges() {
  44089. return this.nodeUniform.updateRanges;
  44090. }
  44091. /**
  44092. * Adds a range of data in the data array to be updated on the GPU.
  44093. *
  44094. * @param {number} start - Position at which to start update.
  44095. * @param {number} count - The number of components to update.
  44096. */
  44097. addUpdateRange( start, count ) {
  44098. this.nodeUniform.addUpdateRange( start, count );
  44099. }
  44100. /**
  44101. * Clears all update ranges.
  44102. */
  44103. clearUpdateRanges() {
  44104. this.nodeUniform.clearUpdateRanges();
  44105. }
  44106. /**
  44107. * The uniform buffer.
  44108. *
  44109. * @type {Float32Array}
  44110. */
  44111. get buffer() {
  44112. return this.nodeUniform.value;
  44113. }
  44114. }
  44115. /**
  44116. * This class represents a uniform buffer binding but with
  44117. * an API that allows to maintain individual uniform objects.
  44118. *
  44119. * @private
  44120. * @augments UniformBuffer
  44121. */
  44122. class UniformsGroup extends UniformBuffer {
  44123. /**
  44124. * Constructs a new uniforms group.
  44125. *
  44126. * @param {string} name - The group's name.
  44127. */
  44128. constructor( name ) {
  44129. super( name );
  44130. /**
  44131. * This flag can be used for type testing.
  44132. *
  44133. * @type {boolean}
  44134. * @readonly
  44135. * @default true
  44136. */
  44137. this.isUniformsGroup = true;
  44138. /**
  44139. * An array with the raw uniform values.
  44140. *
  44141. * @private
  44142. * @type {?Array<number>}
  44143. * @default null
  44144. */
  44145. this._values = null;
  44146. /**
  44147. * An array of uniform objects.
  44148. *
  44149. * The order of uniforms in this array must match the order of uniforms in the shader.
  44150. *
  44151. * @type {Array<Uniform>}
  44152. */
  44153. this.uniforms = [];
  44154. /**
  44155. * A cache for the uniform update ranges.
  44156. *
  44157. * @private
  44158. * @type {Map<number, {start: number, count: number}>}
  44159. */
  44160. this._updateRangeCache = new Map();
  44161. }
  44162. /**
  44163. * Adds a uniform's update range to this buffer.
  44164. *
  44165. * @param {Uniform} uniform - The uniform.
  44166. */
  44167. addUniformUpdateRange( uniform ) {
  44168. const index = uniform.index;
  44169. if ( this._updateRangeCache.has( index ) !== true ) {
  44170. const updateRanges = this.updateRanges;
  44171. const start = uniform.offset;
  44172. const count = uniform.itemSize;
  44173. const range = { start, count };
  44174. updateRanges.push( range );
  44175. this._updateRangeCache.set( index, range );
  44176. }
  44177. }
  44178. /**
  44179. * Clears all update ranges of this buffer.
  44180. */
  44181. clearUpdateRanges() {
  44182. this._updateRangeCache.clear();
  44183. super.clearUpdateRanges();
  44184. }
  44185. /**
  44186. * Adds a uniform to this group.
  44187. *
  44188. * @param {Uniform} uniform - The uniform to add.
  44189. * @return {UniformsGroup} A reference to this group.
  44190. */
  44191. addUniform( uniform ) {
  44192. this.uniforms.push( uniform );
  44193. return this;
  44194. }
  44195. /**
  44196. * Removes a uniform from this group.
  44197. *
  44198. * @param {Uniform} uniform - The uniform to remove.
  44199. * @return {UniformsGroup} A reference to this group.
  44200. */
  44201. removeUniform( uniform ) {
  44202. const index = this.uniforms.indexOf( uniform );
  44203. if ( index !== -1 ) {
  44204. this.uniforms.splice( index, 1 );
  44205. }
  44206. return this;
  44207. }
  44208. /**
  44209. * An array with the raw uniform values.
  44210. *
  44211. * @type {Array<number>}
  44212. */
  44213. get values() {
  44214. if ( this._values === null ) {
  44215. this._values = Array.from( this.buffer );
  44216. }
  44217. return this._values;
  44218. }
  44219. /**
  44220. * A Float32 array buffer with the uniform values.
  44221. *
  44222. * @type {Float32Array}
  44223. */
  44224. get buffer() {
  44225. let buffer = this._buffer;
  44226. if ( buffer === null ) {
  44227. const byteLength = this.byteLength;
  44228. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  44229. this._buffer = buffer;
  44230. }
  44231. return buffer;
  44232. }
  44233. /**
  44234. * The byte length of the buffer with correct buffer alignment.
  44235. *
  44236. * @type {number}
  44237. */
  44238. get byteLength() {
  44239. const bytesPerElement = this.bytesPerElement;
  44240. let offset = 0; // global buffer offset in bytes
  44241. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  44242. const uniform = this.uniforms[ i ];
  44243. const boundary = uniform.boundary;
  44244. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  44245. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  44246. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  44247. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  44248. offset += chunkPadding;
  44249. // Check for chunk overflow
  44250. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  44251. // Add padding to the end of the chunk
  44252. offset += ( GPU_CHUNK_BYTES - chunkStart );
  44253. }
  44254. uniform.offset = offset / bytesPerElement;
  44255. uniform.index = i;
  44256. offset += itemSize;
  44257. }
  44258. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  44259. }
  44260. /**
  44261. * Updates this group by updating each uniform object of
  44262. * the internal uniform list. The uniform objects check if their
  44263. * values has actually changed so this method only returns
  44264. * `true` if there is a real value change.
  44265. *
  44266. * @return {boolean} Whether the uniforms have been updated and
  44267. * must be uploaded to the GPU.
  44268. */
  44269. update() {
  44270. let updated = false;
  44271. for ( const uniform of this.uniforms ) {
  44272. if ( this.updateByType( uniform ) === true ) {
  44273. updated = true;
  44274. }
  44275. }
  44276. return updated;
  44277. }
  44278. /**
  44279. * Updates a given uniform by calling an update method matching
  44280. * the uniforms type.
  44281. *
  44282. * @param {Uniform} uniform - The uniform to update.
  44283. * @return {boolean} Whether the uniform has been updated or not.
  44284. */
  44285. updateByType( uniform ) {
  44286. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  44287. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  44288. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  44289. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  44290. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  44291. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  44292. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  44293. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  44294. }
  44295. /**
  44296. * Updates a given Number uniform.
  44297. *
  44298. * @param {NumberUniform} uniform - The Number uniform.
  44299. * @return {boolean} Whether the uniform has been updated or not.
  44300. */
  44301. updateNumber( uniform ) {
  44302. let updated = false;
  44303. const a = this.values;
  44304. const v = uniform.getValue();
  44305. const offset = uniform.offset;
  44306. const type = uniform.getType();
  44307. if ( a[ offset ] !== v ) {
  44308. const b = this._getBufferForType( type );
  44309. b[ offset ] = a[ offset ] = v;
  44310. updated = true;
  44311. this.addUniformUpdateRange( uniform );
  44312. }
  44313. return updated;
  44314. }
  44315. /**
  44316. * Updates a given Vector2 uniform.
  44317. *
  44318. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  44319. * @return {boolean} Whether the uniform has been updated or not.
  44320. */
  44321. updateVector2( uniform ) {
  44322. let updated = false;
  44323. const a = this.values;
  44324. const v = uniform.getValue();
  44325. const offset = uniform.offset;
  44326. const type = uniform.getType();
  44327. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  44328. const b = this._getBufferForType( type );
  44329. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  44330. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  44331. updated = true;
  44332. this.addUniformUpdateRange( uniform );
  44333. }
  44334. return updated;
  44335. }
  44336. /**
  44337. * Updates a given Vector3 uniform.
  44338. *
  44339. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  44340. * @return {boolean} Whether the uniform has been updated or not.
  44341. */
  44342. updateVector3( uniform ) {
  44343. let updated = false;
  44344. const a = this.values;
  44345. const v = uniform.getValue();
  44346. const offset = uniform.offset;
  44347. const type = uniform.getType();
  44348. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  44349. const b = this._getBufferForType( type );
  44350. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  44351. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  44352. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  44353. updated = true;
  44354. this.addUniformUpdateRange( uniform );
  44355. }
  44356. return updated;
  44357. }
  44358. /**
  44359. * Updates a given Vector4 uniform.
  44360. *
  44361. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  44362. * @return {boolean} Whether the uniform has been updated or not.
  44363. */
  44364. updateVector4( uniform ) {
  44365. let updated = false;
  44366. const a = this.values;
  44367. const v = uniform.getValue();
  44368. const offset = uniform.offset;
  44369. const type = uniform.getType();
  44370. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 3 ] !== v.w ) {
  44371. const b = this._getBufferForType( type );
  44372. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  44373. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  44374. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  44375. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  44376. updated = true;
  44377. this.addUniformUpdateRange( uniform );
  44378. }
  44379. return updated;
  44380. }
  44381. /**
  44382. * Updates a given Color uniform.
  44383. *
  44384. * @param {ColorUniform} uniform - The Color uniform.
  44385. * @return {boolean} Whether the uniform has been updated or not.
  44386. */
  44387. updateColor( uniform ) {
  44388. let updated = false;
  44389. const a = this.values;
  44390. const c = uniform.getValue();
  44391. const offset = uniform.offset;
  44392. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  44393. const b = this.buffer;
  44394. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  44395. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  44396. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  44397. updated = true;
  44398. this.addUniformUpdateRange( uniform );
  44399. }
  44400. return updated;
  44401. }
  44402. /**
  44403. * Updates a given Matrix3 uniform.
  44404. *
  44405. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  44406. * @return {boolean} Whether the uniform has been updated or not.
  44407. */
  44408. updateMatrix3( uniform ) {
  44409. let updated = false;
  44410. const a = this.values;
  44411. const e = uniform.getValue().elements;
  44412. const offset = uniform.offset;
  44413. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  44414. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  44415. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  44416. const b = this.buffer;
  44417. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  44418. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  44419. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  44420. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  44421. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  44422. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  44423. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  44424. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  44425. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  44426. updated = true;
  44427. this.addUniformUpdateRange( uniform );
  44428. }
  44429. return updated;
  44430. }
  44431. /**
  44432. * Updates a given Matrix4 uniform.
  44433. *
  44434. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  44435. * @return {boolean} Whether the uniform has been updated or not.
  44436. */
  44437. updateMatrix4( uniform ) {
  44438. let updated = false;
  44439. const a = this.values;
  44440. const e = uniform.getValue().elements;
  44441. const offset = uniform.offset;
  44442. if ( arraysEqual( a, e, offset ) === false ) {
  44443. const b = this.buffer;
  44444. b.set( e, offset );
  44445. setArray( a, e, offset );
  44446. updated = true;
  44447. this.addUniformUpdateRange( uniform );
  44448. }
  44449. return updated;
  44450. }
  44451. /**
  44452. * Returns a typed array that matches the given data type.
  44453. *
  44454. * @private
  44455. * @param {string} type - The data type.
  44456. * @return {TypedArray} The typed array.
  44457. */
  44458. _getBufferForType( type ) {
  44459. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  44460. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  44461. return this.buffer;
  44462. }
  44463. }
  44464. /**
  44465. * Sets the values of the second array to the first array.
  44466. *
  44467. * @private
  44468. * @param {TypedArray} a - The first array.
  44469. * @param {TypedArray} b - The second array.
  44470. * @param {number} offset - An index offset for the first array.
  44471. */
  44472. function setArray( a, b, offset ) {
  44473. for ( let i = 0, l = b.length; i < l; i ++ ) {
  44474. a[ offset + i ] = b[ i ];
  44475. }
  44476. }
  44477. /**
  44478. * Returns `true` if the given arrays are equal.
  44479. *
  44480. * @private
  44481. * @param {TypedArray} a - The first array.
  44482. * @param {TypedArray} b - The second array.
  44483. * @param {number} offset - An index offset for the first array.
  44484. * @return {boolean} Whether the given arrays are equal or not.
  44485. */
  44486. function arraysEqual( a, b, offset ) {
  44487. for ( let i = 0, l = b.length; i < l; i ++ ) {
  44488. if ( a[ offset + i ] !== b[ i ] ) return false;
  44489. }
  44490. return true;
  44491. }
  44492. let _id$3 = 0;
  44493. /**
  44494. * A special form of uniforms group that represents
  44495. * the individual uniforms as node-based uniforms.
  44496. *
  44497. * @private
  44498. * @augments UniformsGroup
  44499. */
  44500. class NodeUniformsGroup extends UniformsGroup {
  44501. /**
  44502. * Constructs a new node-based uniforms group.
  44503. *
  44504. * @param {string} name - The group's name.
  44505. * @param {UniformGroupNode} groupNode - The uniform group node.
  44506. */
  44507. constructor( name, groupNode ) {
  44508. super( name );
  44509. /**
  44510. * The group's ID.
  44511. *
  44512. * @type {number}
  44513. */
  44514. this.id = _id$3 ++;
  44515. /**
  44516. * The uniform group node.
  44517. *
  44518. * @type {UniformGroupNode}
  44519. */
  44520. this.groupNode = groupNode;
  44521. /**
  44522. * This flag can be used for type testing.
  44523. *
  44524. * @type {boolean}
  44525. * @readonly
  44526. * @default true
  44527. */
  44528. this.isNodeUniformsGroup = true;
  44529. }
  44530. }
  44531. /**
  44532. * Represents a sampler binding type.
  44533. *
  44534. * @private
  44535. * @augments Binding
  44536. */
  44537. class Sampler extends Binding {
  44538. /**
  44539. * Constructs a new sampler.
  44540. *
  44541. * @param {string} name - The samplers's name.
  44542. * @param {?Texture} texture - The texture this binding is referring to.
  44543. */
  44544. constructor( name, texture ) {
  44545. super( name );
  44546. /**
  44547. * The texture the sampler is referring to.
  44548. *
  44549. * @private
  44550. * @type {?Texture}
  44551. */
  44552. this._texture = null;
  44553. /**
  44554. * An event listener which is added to {@link texture}'s dispose event.
  44555. *
  44556. * @private
  44557. * @type {Function}
  44558. */
  44559. this._onTextureDispose = () => {
  44560. this.generation = null;
  44561. this.version = -1;
  44562. };
  44563. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  44564. this.texture = texture;
  44565. /**
  44566. * The binding's version.
  44567. *
  44568. * @type {number}
  44569. */
  44570. this.version = texture ? texture.version : -1;
  44571. /**
  44572. * The binding's generation which is an additional version
  44573. * qualifier.
  44574. *
  44575. * @type {?number}
  44576. * @default null
  44577. */
  44578. this.generation = null;
  44579. /**
  44580. * The binding's sampler key.
  44581. *
  44582. * @type {string}
  44583. * @default ''
  44584. */
  44585. this.samplerKey = '';
  44586. /**
  44587. * This flag can be used for type testing.
  44588. *
  44589. * @type {boolean}
  44590. * @readonly
  44591. * @default true
  44592. */
  44593. this.isSampler = true;
  44594. }
  44595. /**
  44596. * Sets the texture of this sampler.
  44597. *
  44598. * @param {Texture} value - The texture to set.
  44599. */
  44600. set texture( value ) {
  44601. if ( this._texture === value ) return;
  44602. if ( this._texture ) {
  44603. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  44604. }
  44605. this._texture = value;
  44606. this.generation = null;
  44607. this.version = -1;
  44608. if ( this._texture ) {
  44609. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  44610. }
  44611. }
  44612. /**
  44613. * Gets the texture of this sampler.
  44614. * @return {?Texture} The texture.
  44615. */
  44616. get texture() {
  44617. return this._texture;
  44618. }
  44619. /**
  44620. * Updates the binding.
  44621. *
  44622. * @return {boolean} Whether the texture has been updated and must be
  44623. * uploaded to the GPU.
  44624. */
  44625. update() {
  44626. const { texture, version } = this;
  44627. if ( version !== texture.version ) {
  44628. this.version = texture.version;
  44629. return true;
  44630. }
  44631. return false;
  44632. }
  44633. clone() {
  44634. const clonedSampler = super.clone();
  44635. // fix dispose handler for cloned instances
  44636. // TODO: Find better solution, see #31747
  44637. clonedSampler._texture = null;
  44638. clonedSampler._onTextureDispose = () => {
  44639. clonedSampler.generation = null;
  44640. clonedSampler.version = -1;
  44641. };
  44642. clonedSampler.texture = this.texture;
  44643. return clonedSampler;
  44644. }
  44645. }
  44646. let _id$2 = 0;
  44647. /**
  44648. * Represents a sampled texture binding type.
  44649. *
  44650. * @private
  44651. * @augments Sampler
  44652. */
  44653. class SampledTexture extends Sampler {
  44654. /**
  44655. * Constructs a new sampled texture.
  44656. *
  44657. * @param {string} name - The sampled texture's name.
  44658. * @param {?Texture} texture - The texture this binding is referring to.
  44659. */
  44660. constructor( name, texture ) {
  44661. super( name, texture );
  44662. /**
  44663. * This identifier.
  44664. *
  44665. * @type {number}
  44666. */
  44667. this.id = _id$2 ++;
  44668. /**
  44669. * Whether the texture is a storage texture or not.
  44670. *
  44671. * @type {boolean}
  44672. * @default false
  44673. */
  44674. this.store = false;
  44675. /**
  44676. * The mip level to bind for storage textures.
  44677. *
  44678. * @type {number}
  44679. * @default 0
  44680. */
  44681. this.mipLevel = 0;
  44682. /**
  44683. * This flag can be used for type testing.
  44684. *
  44685. * @type {boolean}
  44686. * @readonly
  44687. * @default true
  44688. */
  44689. this.isSampledTexture = true;
  44690. }
  44691. }
  44692. /**
  44693. * A special form of sampled texture binding type.
  44694. * It's texture value is managed by a node object.
  44695. *
  44696. * @private
  44697. * @augments SampledTexture
  44698. */
  44699. class NodeSampledTexture extends SampledTexture {
  44700. /**
  44701. * Constructs a new node-based sampled texture.
  44702. *
  44703. * @param {string} name - The textures's name.
  44704. * @param {TextureNode} textureNode - The texture node.
  44705. * @param {UniformGroupNode} groupNode - The uniform group node.
  44706. * @param {?string} [access=null] - The access type.
  44707. */
  44708. constructor( name, textureNode, groupNode, access = null ) {
  44709. super( name, textureNode ? textureNode.value : null );
  44710. /**
  44711. * The texture node.
  44712. *
  44713. * @type {TextureNode}
  44714. */
  44715. this.textureNode = textureNode;
  44716. /**
  44717. * The uniform group node.
  44718. *
  44719. * @type {UniformGroupNode}
  44720. */
  44721. this.groupNode = groupNode;
  44722. /**
  44723. * The access type.
  44724. *
  44725. * @type {?string}
  44726. * @default null
  44727. */
  44728. this.access = access;
  44729. }
  44730. /**
  44731. * Updates the binding.
  44732. *
  44733. * @return {boolean} Whether the texture has been updated and must be
  44734. * uploaded to the GPU.
  44735. */
  44736. update() {
  44737. const { textureNode } = this;
  44738. if ( this.texture !== textureNode.value ) {
  44739. this.texture = textureNode.value;
  44740. return true;
  44741. }
  44742. return super.update();
  44743. }
  44744. }
  44745. /**
  44746. * A special form of sampled cube texture binding type.
  44747. * It's texture value is managed by a node object.
  44748. *
  44749. * @private
  44750. * @augments NodeSampledTexture
  44751. */
  44752. class NodeSampledCubeTexture extends NodeSampledTexture {
  44753. /**
  44754. * Constructs a new node-based sampled cube texture.
  44755. *
  44756. * @param {string} name - The textures's name.
  44757. * @param {TextureNode} textureNode - The texture node.
  44758. * @param {UniformGroupNode} groupNode - The uniform group node.
  44759. * @param {?string} [access=null] - The access type.
  44760. */
  44761. constructor( name, textureNode, groupNode, access = null ) {
  44762. super( name, textureNode, groupNode, access );
  44763. /**
  44764. * This flag can be used for type testing.
  44765. *
  44766. * @type {boolean}
  44767. * @readonly
  44768. * @default true
  44769. */
  44770. this.isSampledCubeTexture = true;
  44771. }
  44772. }
  44773. /**
  44774. * A special form of sampled 3D texture binding type.
  44775. * It's texture value is managed by a node object.
  44776. *
  44777. * @private
  44778. * @augments NodeSampledTexture
  44779. */
  44780. class NodeSampledTexture3D extends NodeSampledTexture {
  44781. /**
  44782. * Constructs a new node-based sampled 3D texture.
  44783. *
  44784. * @param {string} name - The textures's name.
  44785. * @param {TextureNode} textureNode - The texture node.
  44786. * @param {UniformGroupNode} groupNode - The uniform group node.
  44787. * @param {?string} [access=null] - The access type.
  44788. */
  44789. constructor( name, textureNode, groupNode, access = null ) {
  44790. super( name, textureNode, groupNode, access );
  44791. /**
  44792. * This flag can be used for type testing.
  44793. *
  44794. * @type {boolean}
  44795. * @readonly
  44796. * @default true
  44797. */
  44798. this.isSampledTexture3D = true;
  44799. }
  44800. }
  44801. const glslPolyfills = {
  44802. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' ),
  44803. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }' )
  44804. };
  44805. const glslMethods = {
  44806. textureDimensions: 'textureSize',
  44807. equals: 'equal',
  44808. bitcast_float_int: 'floatBitsToInt',
  44809. bitcast_int_float: 'intBitsToFloat',
  44810. bitcast_uint_float: 'uintBitsToFloat',
  44811. bitcast_float_uint: 'floatBitsToUint',
  44812. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  44813. bitcast_int_uint: 'tsl_bitcast_int_to_uint',
  44814. floatpack_snorm_2x16: 'packSnorm2x16',
  44815. floatpack_unorm_2x16: 'packUnorm2x16',
  44816. floatpack_float16_2x16: 'packHalf2x16',
  44817. floatunpack_snorm_2x16: 'unpackSnorm2x16',
  44818. floatunpack_unorm_2x16: 'unpackUnorm2x16',
  44819. floatunpack_float16_2x16: 'unpackHalf2x16'
  44820. };
  44821. const precisionLib = {
  44822. low: 'lowp',
  44823. medium: 'mediump',
  44824. high: 'highp'
  44825. };
  44826. const supports$1 = {
  44827. swizzleAssign: true,
  44828. storageBuffer: false
  44829. };
  44830. const interpolationTypeMap = {
  44831. perspective: 'smooth',
  44832. linear: 'noperspective'
  44833. };
  44834. const interpolationModeMap = {
  44835. 'centroid': 'centroid'
  44836. };
  44837. const defaultPrecisions = `
  44838. precision highp float;
  44839. precision highp int;
  44840. precision highp sampler2D;
  44841. precision highp sampler3D;
  44842. precision highp samplerCube;
  44843. precision highp sampler2DArray;
  44844. precision highp usampler2D;
  44845. precision highp usampler3D;
  44846. precision highp usamplerCube;
  44847. precision highp usampler2DArray;
  44848. precision highp isampler2D;
  44849. precision highp isampler3D;
  44850. precision highp isamplerCube;
  44851. precision highp isampler2DArray;
  44852. precision highp sampler2DShadow;
  44853. precision highp sampler2DArrayShadow;
  44854. precision highp samplerCubeShadow;
  44855. `;
  44856. /**
  44857. * A node builder targeting GLSL.
  44858. *
  44859. * This module generates GLSL shader code from node materials and also
  44860. * generates the respective bindings and vertex buffer definitions. These
  44861. * data are later used by the renderer to create render and compute pipelines
  44862. * for render objects.
  44863. *
  44864. * @augments NodeBuilder
  44865. */
  44866. class GLSLNodeBuilder extends NodeBuilder {
  44867. /**
  44868. * Constructs a new GLSL node builder renderer.
  44869. *
  44870. * @param {Object3D} object - The 3D object.
  44871. * @param {Renderer} renderer - The renderer.
  44872. */
  44873. constructor( object, renderer ) {
  44874. super( object, renderer, new GLSLNodeParser() );
  44875. /**
  44876. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  44877. * another dictionary which manages UBOs per group ('render','frame','object').
  44878. *
  44879. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  44880. */
  44881. this.uniformGroups = {};
  44882. /**
  44883. * An array that holds objects defining the varying and attribute data in
  44884. * context of Transform Feedback.
  44885. *
  44886. * @type {Array<Object<string,AttributeNode|string>>}
  44887. */
  44888. this.transforms = [];
  44889. /**
  44890. * A dictionary that holds for each shader stage a Map of used extensions.
  44891. *
  44892. * @type {Object<string,Map<string,Object>>}
  44893. */
  44894. this.extensions = {};
  44895. /**
  44896. * A dictionary that holds for each shader stage an Array of used builtins.
  44897. *
  44898. * @type {Object<string,Array<string>>}
  44899. */
  44900. this.builtins = { vertex: [], fragment: [], compute: [] };
  44901. }
  44902. /**
  44903. * Checks if the given texture requires a manual conversion to the working color space.
  44904. *
  44905. * @param {Texture} texture - The texture to check.
  44906. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  44907. */
  44908. needsToWorkingColorSpace( texture ) {
  44909. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  44910. }
  44911. /**
  44912. * Includes the given method name into the current
  44913. * function node.
  44914. *
  44915. * @private
  44916. * @param {string} name - The method name to include.
  44917. * @return {CodeNode} The respective code node.
  44918. */
  44919. _include( name ) {
  44920. const codeNode = glslPolyfills[ name ];
  44921. codeNode.build( this );
  44922. this.addInclude( codeNode );
  44923. return codeNode;
  44924. }
  44925. /**
  44926. * Returns the native shader method name for a given generic name.
  44927. *
  44928. * @param {string} method - The method name to resolve.
  44929. * @return {string} The resolved GLSL method name.
  44930. */
  44931. getMethod( method ) {
  44932. if ( glslPolyfills[ method ] !== undefined ) {
  44933. this._include( method );
  44934. }
  44935. return glslMethods[ method ] || method;
  44936. }
  44937. /**
  44938. * Returns the bitcast method name for a given input and outputType.
  44939. *
  44940. * @param {string} type - The output type to bitcast to.
  44941. * @param {string} inputType - The input type of the.
  44942. * @return {string} The resolved WGSL bitcast invocation.
  44943. */
  44944. getBitcastMethod( type, inputType ) {
  44945. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  44946. }
  44947. /**
  44948. * Returns the float packing method name for a given numeric encoding.
  44949. *
  44950. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  44951. * @returns {string} The resolved GLSL float packing method name.
  44952. */
  44953. getFloatPackingMethod( encoding ) {
  44954. return this.getMethod( `floatpack_${ encoding }_2x16` );
  44955. }
  44956. /**
  44957. * Returns the float unpacking method name for a given numeric encoding.
  44958. *
  44959. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  44960. * @returns {string} The resolved GLSL float unpacking method name.
  44961. */
  44962. getFloatUnpackingMethod( encoding ) {
  44963. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  44964. }
  44965. /**
  44966. * Returns the native snippet for a ternary operation.
  44967. *
  44968. * @param {string} condSnippet - The condition determining which expression gets resolved.
  44969. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  44970. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  44971. * @return {string} The resolved method name.
  44972. */
  44973. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  44974. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  44975. }
  44976. /**
  44977. * Returns the output struct name. Not relevant for GLSL.
  44978. *
  44979. * @return {string}
  44980. */
  44981. getOutputStructName() {
  44982. return '';
  44983. }
  44984. /**
  44985. * Builds the given shader node.
  44986. *
  44987. * @param {ShaderNodeInternal} shaderNode - The shader node.
  44988. * @return {string} The GLSL function code.
  44989. */
  44990. buildFunctionCode( shaderNode ) {
  44991. const layout = shaderNode.layout;
  44992. const flowData = this.flowShaderNode( shaderNode );
  44993. const parameters = [];
  44994. for ( const input of layout.inputs ) {
  44995. parameters.push( this.getType( input.type ) + ' ' + input.name );
  44996. }
  44997. //
  44998. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  44999. ${ flowData.vars }
  45000. ${ flowData.code }
  45001. return ${ flowData.result };
  45002. }`;
  45003. //
  45004. return code;
  45005. }
  45006. /**
  45007. * Setups the Pixel Buffer Object (PBO) for the given storage
  45008. * buffer node.
  45009. *
  45010. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  45011. */
  45012. setupPBO( storageBufferNode ) {
  45013. const attribute = storageBufferNode.value;
  45014. if ( attribute.pbo === undefined ) {
  45015. const originalArray = attribute.array;
  45016. const numElements = attribute.count * attribute.itemSize;
  45017. const { itemSize } = attribute;
  45018. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  45019. let format = isInteger ? RedIntegerFormat : RedFormat;
  45020. if ( itemSize === 2 ) {
  45021. format = isInteger ? RGIntegerFormat : RGFormat;
  45022. } else if ( itemSize === 3 ) {
  45023. format = isInteger ? RGBIntegerFormat : RGBFormat;
  45024. } else if ( itemSize === 4 ) {
  45025. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  45026. }
  45027. const typeMap = {
  45028. Float32Array: FloatType,
  45029. Uint8Array: UnsignedByteType,
  45030. Uint16Array: UnsignedShortType,
  45031. Uint32Array: UnsignedIntType,
  45032. Int8Array: ByteType,
  45033. Int16Array: ShortType,
  45034. Int32Array: IntType,
  45035. Uint8ClampedArray: UnsignedByteType,
  45036. };
  45037. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  45038. let height = Math.ceil( ( numElements / itemSize ) / width );
  45039. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  45040. const newSize = width * height * itemSize;
  45041. const newArray = new originalArray.constructor( newSize );
  45042. newArray.set( originalArray, 0 );
  45043. attribute.array = newArray;
  45044. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  45045. pboTexture.needsUpdate = true;
  45046. pboTexture.isPBOTexture = true;
  45047. const pbo = new TextureNode( pboTexture, null, null );
  45048. pbo.setPrecision( 'high' );
  45049. attribute.pboNode = pbo;
  45050. attribute.pbo = pbo.value;
  45051. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  45052. }
  45053. }
  45054. /**
  45055. * Returns a GLSL snippet that represents the property name of the given node.
  45056. *
  45057. * @param {Node} node - The node.
  45058. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45059. * @return {string} The property name.
  45060. */
  45061. getPropertyName( node, shaderStage = this.shaderStage ) {
  45062. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  45063. return node.name;
  45064. }
  45065. return super.getPropertyName( node, shaderStage );
  45066. }
  45067. /**
  45068. * Setups the Pixel Buffer Object (PBO) for the given storage
  45069. * buffer node.
  45070. *
  45071. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  45072. * @return {string} The property name.
  45073. */
  45074. generatePBO( storageArrayElementNode ) {
  45075. const { node, indexNode } = storageArrayElementNode;
  45076. const attribute = node.value;
  45077. if ( this.renderer.backend.has( attribute ) ) {
  45078. const attributeData = this.renderer.backend.get( attribute );
  45079. attributeData.pbo = attribute.pbo;
  45080. }
  45081. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  45082. const textureName = this.getPropertyName( nodeUniform );
  45083. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  45084. const indexSnippet = indexNode.build( this, 'uint' );
  45085. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  45086. let propertyName = elementNodeData.propertyName;
  45087. if ( propertyName === undefined ) {
  45088. // property element
  45089. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  45090. propertyName = this.getPropertyName( nodeVar );
  45091. // property size
  45092. const bufferNodeData = this.getDataFromNode( node );
  45093. let propertySizeName = bufferNodeData.propertySizeName;
  45094. if ( propertySizeName === undefined ) {
  45095. propertySizeName = propertyName + 'Size';
  45096. this.getVarFromNode( node, propertySizeName, 'uint' );
  45097. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  45098. bufferNodeData.propertySizeName = propertySizeName;
  45099. }
  45100. //
  45101. const { itemSize } = attribute;
  45102. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  45103. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  45104. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  45105. //
  45106. let prefix = 'vec4';
  45107. if ( attribute.pbo.type === UnsignedIntType ) {
  45108. prefix = 'uvec4';
  45109. } else if ( attribute.pbo.type === IntType ) {
  45110. prefix = 'ivec4';
  45111. }
  45112. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  45113. elementNodeData.propertyName = propertyName;
  45114. }
  45115. return propertyName;
  45116. }
  45117. /**
  45118. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  45119. *
  45120. * @param {?Texture} texture - The texture.
  45121. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45122. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45123. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45124. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  45125. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45126. * @return {string} The GLSL snippet.
  45127. */
  45128. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  45129. if ( levelSnippet === null ) levelSnippet = '0';
  45130. let snippet;
  45131. if ( depthSnippet ) {
  45132. if ( offsetSnippet ) {
  45133. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  45134. } else {
  45135. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  45136. }
  45137. } else {
  45138. if ( offsetSnippet ) {
  45139. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  45140. } else {
  45141. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  45142. }
  45143. }
  45144. if ( texture !== null && texture.isDepthTexture ) {
  45145. snippet += '.x';
  45146. }
  45147. return snippet;
  45148. }
  45149. /**
  45150. * Generates the GLSL snippet for sampling/loading the given texture.
  45151. *
  45152. * @param {Texture} texture - The texture.
  45153. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45154. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45155. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  45156. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45157. * @return {string} The GLSL snippet.
  45158. */
  45159. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  45160. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  45161. if ( texture.isDepthTexture ) {
  45162. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  45163. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  45164. }
  45165. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  45166. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  45167. }
  45168. /**
  45169. * Generates the GLSL snippet when sampling textures with explicit mip level.
  45170. *
  45171. * @param {Texture} texture - The texture.
  45172. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45173. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45174. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45175. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  45176. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45177. * @return {string} The GLSL snippet.
  45178. */
  45179. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  45180. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  45181. if ( offsetSnippet ) {
  45182. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  45183. }
  45184. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  45185. }
  45186. /**
  45187. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  45188. *
  45189. * @param {Texture} texture - The texture.
  45190. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45191. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45192. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  45193. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  45194. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45195. * @return {string} The GLSL snippet.
  45196. */
  45197. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet ) {
  45198. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  45199. if ( offsetSnippet ) {
  45200. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  45201. }
  45202. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  45203. }
  45204. /**
  45205. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  45206. *
  45207. * @param {Texture} texture - The texture.
  45208. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45209. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45210. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  45211. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  45212. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45213. * @return {string} The GLSL snippet.
  45214. */
  45215. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet ) {
  45216. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  45217. if ( offsetSnippet ) {
  45218. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  45219. }
  45220. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  45221. }
  45222. /**
  45223. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  45224. * against a reference value.
  45225. *
  45226. * @param {Texture} texture - The texture.
  45227. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45228. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  45229. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  45230. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  45231. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  45232. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45233. * @return {string} The GLSL snippet.
  45234. */
  45235. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  45236. if ( shaderStage === 'fragment' ) {
  45237. // Cube shadow maps use vec4(direction, compareValue)
  45238. if ( texture.isCubeTexture ) {
  45239. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ compareSnippet } ) )`;
  45240. }
  45241. if ( depthSnippet ) {
  45242. if ( offsetSnippet ) {
  45243. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  45244. }
  45245. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  45246. }
  45247. if ( offsetSnippet ) {
  45248. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  45249. }
  45250. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  45251. } else {
  45252. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  45253. }
  45254. }
  45255. /**
  45256. * Returns the variables of the given shader stage as a GLSL string.
  45257. *
  45258. * @param {string} shaderStage - The shader stage.
  45259. * @return {string} The GLSL snippet that defines the variables.
  45260. */
  45261. getVars( shaderStage ) {
  45262. const snippets = [];
  45263. const vars = this.vars[ shaderStage ];
  45264. if ( vars !== undefined ) {
  45265. for ( const variable of vars ) {
  45266. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  45267. }
  45268. }
  45269. return snippets.join( '\n\t' );
  45270. }
  45271. /**
  45272. * Returns the uniforms of the given shader stage as a GLSL string.
  45273. *
  45274. * @param {string} shaderStage - The shader stage.
  45275. * @return {string} The GLSL snippet that defines the uniforms.
  45276. */
  45277. getUniforms( shaderStage ) {
  45278. const uniforms = this.uniforms[ shaderStage ];
  45279. const bindingSnippets = [];
  45280. const uniformGroups = {};
  45281. for ( const uniform of uniforms ) {
  45282. let snippet = null;
  45283. let group = false;
  45284. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  45285. const texture = uniform.node.value;
  45286. let typePrefix = '';
  45287. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  45288. if ( texture.type === UnsignedIntType ) {
  45289. typePrefix = 'u';
  45290. } else if ( texture.type === IntType ) {
  45291. typePrefix = 'i';
  45292. }
  45293. }
  45294. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  45295. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  45296. } else if ( texture.compareFunction ) {
  45297. if ( texture.isArrayTexture === true ) {
  45298. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  45299. } else {
  45300. snippet = `sampler2DShadow ${ uniform.name };`;
  45301. }
  45302. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  45303. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  45304. } else {
  45305. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  45306. }
  45307. } else if ( uniform.type === 'cubeTexture' ) {
  45308. snippet = `samplerCube ${ uniform.name };`;
  45309. } else if ( uniform.type === 'cubeDepthTexture' ) {
  45310. const texture = uniform.node.value;
  45311. if ( texture.compareFunction ) {
  45312. snippet = `samplerCubeShadow ${ uniform.name };`;
  45313. } else {
  45314. snippet = `samplerCube ${ uniform.name };`;
  45315. }
  45316. } else if ( uniform.type === 'buffer' ) {
  45317. const bufferNode = uniform.node;
  45318. const bufferType = this.getType( bufferNode.bufferType );
  45319. const bufferCount = bufferNode.bufferCount;
  45320. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  45321. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  45322. } else {
  45323. const groupName = uniform.groupNode.name;
  45324. // Check if this group has already been processed
  45325. if ( uniformGroups[ groupName ] === undefined ) {
  45326. // Get the shared uniform group that contains uniforms from all stages
  45327. const sharedUniformGroup = this.uniformGroups[ groupName ];
  45328. if ( sharedUniformGroup !== undefined ) {
  45329. // Generate snippets for ALL uniforms in this shared group
  45330. const snippets = [];
  45331. for ( const sharedUniform of sharedUniformGroup.uniforms ) {
  45332. const type = sharedUniform.getType();
  45333. const vectorType = this.getVectorType( type );
  45334. const precision = sharedUniform.nodeUniform.node.precision;
  45335. let uniformSnippet = `${ vectorType } ${ sharedUniform.name };`;
  45336. if ( precision !== null ) {
  45337. uniformSnippet = precisionLib[ precision ] + ' ' + uniformSnippet;
  45338. }
  45339. snippets.push( '\t' + uniformSnippet );
  45340. }
  45341. uniformGroups[ groupName ] = snippets;
  45342. }
  45343. }
  45344. group = true;
  45345. }
  45346. if ( ! group ) {
  45347. const precision = uniform.node.precision;
  45348. if ( precision !== null ) {
  45349. snippet = precisionLib[ precision ] + ' ' + snippet;
  45350. }
  45351. snippet = 'uniform ' + snippet;
  45352. bindingSnippets.push( snippet );
  45353. }
  45354. }
  45355. let output = '';
  45356. for ( const name in uniformGroups ) {
  45357. const groupSnippets = uniformGroups[ name ];
  45358. output += this._getGLSLUniformStruct( name, groupSnippets.join( '\n' ) ) + '\n';
  45359. }
  45360. output += bindingSnippets.join( '\n' );
  45361. return output;
  45362. }
  45363. /**
  45364. * Returns the type for a given buffer attribute.
  45365. *
  45366. * @param {BufferAttribute} attribute - The buffer attribute.
  45367. * @return {string} The type.
  45368. */
  45369. getTypeFromAttribute( attribute ) {
  45370. let nodeType = super.getTypeFromAttribute( attribute );
  45371. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  45372. let dataAttribute = attribute;
  45373. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  45374. const array = dataAttribute.array;
  45375. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  45376. nodeType = nodeType.slice( 1 );
  45377. }
  45378. }
  45379. return nodeType;
  45380. }
  45381. /**
  45382. * Returns the shader attributes of the given shader stage as a GLSL string.
  45383. *
  45384. * @param {string} shaderStage - The shader stage.
  45385. * @return {string} The GLSL snippet that defines the shader attributes.
  45386. */
  45387. getAttributes( shaderStage ) {
  45388. let snippet = '';
  45389. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  45390. const attributes = this.getAttributesArray();
  45391. let location = 0;
  45392. for ( const attribute of attributes ) {
  45393. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  45394. }
  45395. }
  45396. return snippet;
  45397. }
  45398. /**
  45399. * Returns the members of the given struct type node as a GLSL string.
  45400. *
  45401. * @param {StructTypeNode} struct - The struct type node.
  45402. * @return {string} The GLSL snippet that defines the struct members.
  45403. */
  45404. getStructMembers( struct ) {
  45405. const snippets = [];
  45406. for ( const member of struct.members ) {
  45407. snippets.push( `\t${ member.type } ${ member.name };` );
  45408. }
  45409. return snippets.join( '\n' );
  45410. }
  45411. /**
  45412. * Returns the structs of the given shader stage as a GLSL string.
  45413. *
  45414. * @param {string} shaderStage - The shader stage.
  45415. * @return {string} The GLSL snippet that defines the structs.
  45416. */
  45417. getStructs( shaderStage ) {
  45418. const snippets = [];
  45419. const structs = this.structs[ shaderStage ];
  45420. const outputSnippet = [];
  45421. for ( const struct of structs ) {
  45422. if ( struct.output ) {
  45423. for ( const member of struct.members ) {
  45424. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  45425. }
  45426. } else {
  45427. let snippet = 'struct ' + struct.name + ' {\n';
  45428. snippet += this.getStructMembers( struct );
  45429. snippet += '\n};\n';
  45430. snippets.push( snippet );
  45431. }
  45432. }
  45433. if ( outputSnippet.length === 0 ) {
  45434. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  45435. }
  45436. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  45437. }
  45438. /**
  45439. * Returns the varyings of the given shader stage as a GLSL string.
  45440. *
  45441. * @param {string} shaderStage - The shader stage.
  45442. * @return {string} The GLSL snippet that defines the varyings.
  45443. */
  45444. getVaryings( shaderStage ) {
  45445. let snippet = '';
  45446. const varyings = this.varyings;
  45447. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  45448. for ( const varying of varyings ) {
  45449. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  45450. const type = this.getType( varying.type );
  45451. if ( varying.needsInterpolation ) {
  45452. if ( varying.interpolationType ) {
  45453. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  45454. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  45455. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  45456. } else {
  45457. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  45458. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  45459. }
  45460. } else {
  45461. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  45462. }
  45463. }
  45464. } else if ( shaderStage === 'fragment' ) {
  45465. for ( const varying of varyings ) {
  45466. if ( varying.needsInterpolation ) {
  45467. const type = this.getType( varying.type );
  45468. if ( varying.interpolationType ) {
  45469. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  45470. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  45471. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  45472. } else {
  45473. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  45474. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  45475. }
  45476. }
  45477. }
  45478. }
  45479. for ( const builtin of this.builtins[ shaderStage ] ) {
  45480. snippet += `${builtin};\n`;
  45481. }
  45482. return snippet;
  45483. }
  45484. /**
  45485. * Returns the vertex index builtin.
  45486. *
  45487. * @return {string} The vertex index.
  45488. */
  45489. getVertexIndex() {
  45490. return 'uint( gl_VertexID )';
  45491. }
  45492. /**
  45493. * Contextually returns either the vertex stage instance index builtin
  45494. * or the linearized index of an compute invocation within a grid of workgroups.
  45495. *
  45496. * @return {string} The instance index.
  45497. */
  45498. getInstanceIndex() {
  45499. return 'uint( gl_InstanceID )';
  45500. }
  45501. /**
  45502. * Returns a builtin representing the index of an invocation within its workgroup.
  45503. *
  45504. * @return {string} The invocation local index.
  45505. */
  45506. getInvocationLocalIndex() {
  45507. const workgroupSize = this.object.workgroupSize;
  45508. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  45509. return `uint( gl_InstanceID ) % ${size}u`;
  45510. }
  45511. /**
  45512. * Returns a builtin representing the size of a subgroup within the current shader.
  45513. */
  45514. getSubgroupSize() {
  45515. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  45516. }
  45517. /**
  45518. * Returns a builtin representing the index of an invocation within its subgroup.
  45519. */
  45520. getInvocationSubgroupIndex() {
  45521. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  45522. }
  45523. /**
  45524. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  45525. */
  45526. getSubgroupIndex() {
  45527. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  45528. }
  45529. /**
  45530. * Returns the draw index builtin.
  45531. *
  45532. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  45533. */
  45534. getDrawIndex() {
  45535. const extensions = this.renderer.backend.extensions;
  45536. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  45537. return 'uint( gl_DrawID )';
  45538. } else {
  45539. return 'nodeUniformDrawId'; // fallback to uniform
  45540. }
  45541. }
  45542. /**
  45543. * Returns the front facing builtin.
  45544. *
  45545. * @return {string} The front facing builtin.
  45546. */
  45547. getFrontFacing() {
  45548. return 'gl_FrontFacing';
  45549. }
  45550. /**
  45551. * Returns the frag coord builtin.
  45552. *
  45553. * @return {string} The frag coord builtin.
  45554. */
  45555. getFragCoord() {
  45556. return 'gl_FragCoord.xy';
  45557. }
  45558. /**
  45559. * Returns the frag depth builtin.
  45560. *
  45561. * @return {string} The frag depth builtin.
  45562. */
  45563. getFragDepth() {
  45564. return 'gl_FragDepth';
  45565. }
  45566. /**
  45567. * Enables the given extension.
  45568. *
  45569. * @param {string} name - The extension name.
  45570. * @param {string} behavior - The extension behavior.
  45571. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  45572. */
  45573. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  45574. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  45575. if ( map.has( name ) === false ) {
  45576. map.set( name, {
  45577. name,
  45578. behavior
  45579. } );
  45580. }
  45581. }
  45582. /**
  45583. * Returns the enabled extensions of the given shader stage as a GLSL string.
  45584. *
  45585. * @param {string} shaderStage - The shader stage.
  45586. * @return {string} The GLSL snippet that defines the enabled extensions.
  45587. */
  45588. getExtensions( shaderStage ) {
  45589. const snippets = [];
  45590. if ( shaderStage === 'vertex' ) {
  45591. const ext = this.renderer.backend.extensions;
  45592. const isBatchedMesh = this.object.isBatchedMesh;
  45593. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  45594. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  45595. }
  45596. }
  45597. const extensions = this.extensions[ shaderStage ];
  45598. if ( extensions !== undefined ) {
  45599. for ( const { name, behavior } of extensions.values() ) {
  45600. snippets.push( `#extension ${name} : ${behavior}` );
  45601. }
  45602. }
  45603. return snippets.join( '\n' );
  45604. }
  45605. /**
  45606. * Returns the clip distances builtin.
  45607. *
  45608. * @return {string} The clip distances builtin.
  45609. */
  45610. getClipDistance() {
  45611. return 'gl_ClipDistance';
  45612. }
  45613. /**
  45614. * Whether the requested feature is available or not.
  45615. *
  45616. * @param {string} name - The requested feature.
  45617. * @return {boolean} Whether the requested feature is supported or not.
  45618. */
  45619. isAvailable( name ) {
  45620. let result = supports$1[ name ];
  45621. if ( result === undefined ) {
  45622. let extensionName;
  45623. result = false;
  45624. switch ( name ) {
  45625. case 'float32Filterable':
  45626. extensionName = 'OES_texture_float_linear';
  45627. break;
  45628. case 'clipDistance':
  45629. extensionName = 'WEBGL_clip_cull_distance';
  45630. break;
  45631. }
  45632. if ( extensionName !== undefined ) {
  45633. const extensions = this.renderer.backend.extensions;
  45634. if ( extensions.has( extensionName ) ) {
  45635. extensions.get( extensionName );
  45636. result = true;
  45637. }
  45638. }
  45639. supports$1[ name ] = result;
  45640. }
  45641. return result;
  45642. }
  45643. /**
  45644. * Whether to flip texture data along its vertical axis or not.
  45645. *
  45646. * @return {boolean} Returns always `true` in context of GLSL.
  45647. */
  45648. isFlipY() {
  45649. return true;
  45650. }
  45651. /**
  45652. * Enables hardware clipping.
  45653. *
  45654. * @param {string} planeCount - The clipping plane count.
  45655. */
  45656. enableHardwareClipping( planeCount ) {
  45657. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  45658. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  45659. }
  45660. /**
  45661. * Enables multiview.
  45662. */
  45663. enableMultiview() {
  45664. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  45665. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  45666. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  45667. }
  45668. /**
  45669. * Registers a transform in context of Transform Feedback.
  45670. *
  45671. * @param {string} varyingName - The varying name.
  45672. * @param {AttributeNode} attributeNode - The attribute node.
  45673. */
  45674. registerTransform( varyingName, attributeNode ) {
  45675. this.transforms.push( { varyingName, attributeNode } );
  45676. }
  45677. /**
  45678. * Returns the transforms of the given shader stage as a GLSL string.
  45679. *
  45680. * @param {string} shaderStage - The shader stage.
  45681. * @return {string} The GLSL snippet that defines the transforms.
  45682. */
  45683. getTransforms( /* shaderStage */ ) {
  45684. const transforms = this.transforms;
  45685. let snippet = '';
  45686. for ( let i = 0; i < transforms.length; i ++ ) {
  45687. const transform = transforms[ i ];
  45688. const attributeName = this.getPropertyName( transform.attributeNode );
  45689. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  45690. }
  45691. return snippet;
  45692. }
  45693. /**
  45694. * Returns a GLSL struct based on the given name and variables.
  45695. *
  45696. * @private
  45697. * @param {string} name - The struct name.
  45698. * @param {string} vars - The struct variables.
  45699. * @return {string} The GLSL snippet representing a struct.
  45700. */
  45701. _getGLSLUniformStruct( name, vars ) {
  45702. return `
  45703. layout( std140 ) uniform ${name} {
  45704. ${vars}
  45705. };`;
  45706. }
  45707. /**
  45708. * Returns a GLSL vertex shader based on the given shader data.
  45709. *
  45710. * @private
  45711. * @param {Object} shaderData - The shader data.
  45712. * @return {string} The vertex shader.
  45713. */
  45714. _getGLSLVertexCode( shaderData ) {
  45715. return `#version 300 es
  45716. ${ this.getSignature() }
  45717. // extensions
  45718. ${shaderData.extensions}
  45719. // precision
  45720. ${ defaultPrecisions }
  45721. // uniforms
  45722. ${shaderData.uniforms}
  45723. // varyings
  45724. ${shaderData.varyings}
  45725. // attributes
  45726. ${shaderData.attributes}
  45727. // codes
  45728. ${shaderData.codes}
  45729. void main() {
  45730. // vars
  45731. ${shaderData.vars}
  45732. // transforms
  45733. ${shaderData.transforms}
  45734. // flow
  45735. ${shaderData.flow}
  45736. gl_PointSize = 1.0;
  45737. }
  45738. `;
  45739. }
  45740. /**
  45741. * Returns a GLSL fragment shader based on the given shader data.
  45742. *
  45743. * @private
  45744. * @param {Object} shaderData - The shader data.
  45745. * @return {string} The vertex shader.
  45746. */
  45747. _getGLSLFragmentCode( shaderData ) {
  45748. return `#version 300 es
  45749. ${ this.getSignature() }
  45750. // extensions
  45751. ${shaderData.extensions}
  45752. // precision
  45753. ${ defaultPrecisions }
  45754. // structs
  45755. ${shaderData.structs}
  45756. // uniforms
  45757. ${shaderData.uniforms}
  45758. // varyings
  45759. ${shaderData.varyings}
  45760. // codes
  45761. ${shaderData.codes}
  45762. void main() {
  45763. // vars
  45764. ${shaderData.vars}
  45765. // flow
  45766. ${shaderData.flow}
  45767. }
  45768. `;
  45769. }
  45770. /**
  45771. * Controls the code build of the shader stages.
  45772. */
  45773. buildCode() {
  45774. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  45775. this.sortBindingGroups();
  45776. for ( const shaderStage in shadersData ) {
  45777. let flow = '// code\n\n';
  45778. flow += this.flowCode[ shaderStage ];
  45779. const flowNodes = this.flowNodes[ shaderStage ];
  45780. const mainNode = flowNodes[ flowNodes.length - 1 ];
  45781. for ( const node of flowNodes ) {
  45782. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  45783. const slotName = node.name;
  45784. if ( slotName ) {
  45785. if ( flow.length > 0 ) flow += '\n';
  45786. flow += `\t// flow -> ${ slotName }\n\t`;
  45787. }
  45788. flow += `${ flowSlotData.code }\n\t`;
  45789. if ( node === mainNode && shaderStage !== 'compute' ) {
  45790. flow += '// result\n\t';
  45791. if ( shaderStage === 'vertex' ) {
  45792. flow += 'gl_Position = ';
  45793. flow += `${ flowSlotData.result };`;
  45794. } else if ( shaderStage === 'fragment' ) {
  45795. if ( ! node.outputNode.isOutputStructNode ) {
  45796. flow += 'fragColor = ';
  45797. flow += `${ flowSlotData.result };`;
  45798. }
  45799. }
  45800. }
  45801. }
  45802. const stageData = shadersData[ shaderStage ];
  45803. stageData.extensions = this.getExtensions( shaderStage );
  45804. stageData.uniforms = this.getUniforms( shaderStage );
  45805. stageData.attributes = this.getAttributes( shaderStage );
  45806. stageData.varyings = this.getVaryings( shaderStage );
  45807. stageData.vars = this.getVars( shaderStage );
  45808. stageData.structs = this.getStructs( shaderStage );
  45809. stageData.codes = this.getCodes( shaderStage );
  45810. stageData.transforms = this.getTransforms( shaderStage );
  45811. stageData.flow = flow;
  45812. // fallbacks
  45813. if ( shaderStage === 'vertex' ) {
  45814. const ext = this.renderer.backend.extensions;
  45815. if ( this.object.isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) === false ) {
  45816. stageData.uniforms += '\nuniform uint nodeUniformDrawId;\n';
  45817. }
  45818. }
  45819. }
  45820. if ( this.material !== null ) {
  45821. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  45822. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  45823. } else {
  45824. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  45825. }
  45826. }
  45827. /**
  45828. * This method is one of the more important ones since it's responsible
  45829. * for generating a matching binding instance for the given uniform node.
  45830. *
  45831. * These bindings are later used in the renderer to create bind groups
  45832. * and layouts.
  45833. *
  45834. * @param {UniformNode} node - The uniform node.
  45835. * @param {string} type - The node data type.
  45836. * @param {string} shaderStage - The shader stage.
  45837. * @param {?string} [name=null] - An optional uniform name.
  45838. * @return {NodeUniform} The node uniform object.
  45839. */
  45840. getUniformFromNode( node, type, shaderStage, name = null ) {
  45841. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  45842. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  45843. let uniformGPU = nodeData.uniformGPU;
  45844. if ( uniformGPU === undefined ) {
  45845. const group = node.groupNode;
  45846. const groupName = group.name;
  45847. const bindings = this.getBindGroupArray( groupName, shaderStage );
  45848. if ( type === 'texture' ) {
  45849. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  45850. bindings.push( uniformGPU );
  45851. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  45852. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  45853. bindings.push( uniformGPU );
  45854. } else if ( type === 'texture3D' ) {
  45855. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  45856. bindings.push( uniformGPU );
  45857. } else if ( type === 'buffer' ) {
  45858. uniformNode.name = `buffer${ node.id }`;
  45859. const sharedData = this.getSharedDataFromNode( node );
  45860. let buffer = sharedData.buffer;
  45861. if ( buffer === undefined ) {
  45862. node.name = `NodeBuffer_${ node.id }`;
  45863. buffer = new NodeUniformBuffer( node, group );
  45864. buffer.name = node.name;
  45865. sharedData.buffer = buffer;
  45866. }
  45867. bindings.push( buffer );
  45868. uniformGPU = buffer;
  45869. } else {
  45870. let uniformsGroup = this.uniformGroups[ groupName ];
  45871. if ( uniformsGroup === undefined ) {
  45872. uniformsGroup = new NodeUniformsGroup( groupName, group );
  45873. this.uniformGroups[ groupName ] = uniformsGroup;
  45874. bindings.push( uniformsGroup );
  45875. } else {
  45876. // Add to bindings for this stage if not already present
  45877. if ( bindings.indexOf( uniformsGroup ) === -1 ) {
  45878. bindings.push( uniformsGroup );
  45879. }
  45880. }
  45881. uniformGPU = this.getNodeUniform( uniformNode, type );
  45882. // Only add uniform if not already present in the group (check by name to avoid duplicates across stages)
  45883. const uniformName = uniformGPU.name;
  45884. const alreadyExists = uniformsGroup.uniforms.some( u => u.name === uniformName );
  45885. if ( ! alreadyExists ) {
  45886. uniformsGroup.addUniform( uniformGPU );
  45887. }
  45888. }
  45889. nodeData.uniformGPU = uniformGPU;
  45890. }
  45891. return uniformNode;
  45892. }
  45893. }
  45894. let _vector2 = null;
  45895. let _color4 = null;
  45896. /**
  45897. * Most of the rendering related logic is implemented in the
  45898. * {@link Renderer} module and related management components.
  45899. * Sometimes it is required though to execute commands which are
  45900. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  45901. * This abstract base class defines an interface that encapsulates
  45902. * all backend-related logic. Derived classes for each backend must
  45903. * implement the interface.
  45904. *
  45905. * @abstract
  45906. * @private
  45907. */
  45908. class Backend {
  45909. /**
  45910. * Constructs a new backend.
  45911. *
  45912. * @param {Object} parameters - An object holding parameters for the backend.
  45913. */
  45914. constructor( parameters = {} ) {
  45915. /**
  45916. * The parameters of the backend.
  45917. *
  45918. * @type {Object}
  45919. */
  45920. this.parameters = Object.assign( {}, parameters );
  45921. /**
  45922. * This weak map holds backend-specific data of objects
  45923. * like textures, attributes or render targets.
  45924. *
  45925. * @type {WeakMap<Object, Object>}
  45926. */
  45927. this.data = new WeakMap();
  45928. /**
  45929. * A reference to the renderer.
  45930. *
  45931. * @type {?Renderer}
  45932. * @default null
  45933. */
  45934. this.renderer = null;
  45935. /**
  45936. * A reference to the canvas element the renderer is drawing to.
  45937. *
  45938. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  45939. * @default null
  45940. */
  45941. this.domElement = null;
  45942. /**
  45943. * A reference to the timestamp query pool.
  45944. *
  45945. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  45946. */
  45947. this.timestampQueryPool = {
  45948. [ TimestampQuery.RENDER ]: null,
  45949. [ TimestampQuery.COMPUTE ]: null
  45950. };
  45951. /**
  45952. * Whether to track timestamps with a Timestamp Query API or not.
  45953. *
  45954. * @type {boolean}
  45955. * @default false
  45956. */
  45957. this.trackTimestamp = ( parameters.trackTimestamp === true );
  45958. }
  45959. /**
  45960. * Initializes the backend so it is ready for usage. Concrete backends
  45961. * are supposed to implement their rendering context creation and related
  45962. * operations in this method.
  45963. *
  45964. * @async
  45965. * @param {Renderer} renderer - The renderer.
  45966. * @return {Promise} A Promise that resolves when the backend has been initialized.
  45967. */
  45968. async init( renderer ) {
  45969. this.renderer = renderer;
  45970. }
  45971. /**
  45972. * The coordinate system of the backend.
  45973. *
  45974. * @abstract
  45975. * @type {number}
  45976. * @readonly
  45977. */
  45978. get coordinateSystem() {}
  45979. // render context
  45980. /**
  45981. * This method is executed at the beginning of a render call and
  45982. * can be used by the backend to prepare the state for upcoming
  45983. * draw calls.
  45984. *
  45985. * @abstract
  45986. * @param {RenderContext} renderContext - The render context.
  45987. */
  45988. beginRender( /*renderContext*/ ) {}
  45989. /**
  45990. * This method is executed at the end of a render call and
  45991. * can be used by the backend to finalize work after draw
  45992. * calls.
  45993. *
  45994. * @abstract
  45995. * @param {RenderContext} renderContext - The render context.
  45996. */
  45997. finishRender( /*renderContext*/ ) {}
  45998. /**
  45999. * This method is executed at the beginning of a compute call and
  46000. * can be used by the backend to prepare the state for upcoming
  46001. * compute tasks.
  46002. *
  46003. * @abstract
  46004. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46005. */
  46006. beginCompute( /*computeGroup*/ ) {}
  46007. /**
  46008. * This method is executed at the end of a compute call and
  46009. * can be used by the backend to finalize work after compute
  46010. * tasks.
  46011. *
  46012. * @abstract
  46013. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46014. */
  46015. finishCompute( /*computeGroup*/ ) {}
  46016. // render object
  46017. /**
  46018. * Executes a draw command for the given render object.
  46019. *
  46020. * @abstract
  46021. * @param {RenderObject} renderObject - The render object to draw.
  46022. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  46023. */
  46024. draw( /*renderObject, info*/ ) { }
  46025. // compute node
  46026. /**
  46027. * Executes a compute command for the given compute node.
  46028. *
  46029. * @abstract
  46030. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  46031. * @param {Node} computeNode - The compute node.
  46032. * @param {Array<BindGroup>} bindings - The bindings.
  46033. * @param {ComputePipeline} computePipeline - The compute pipeline.
  46034. */
  46035. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  46036. // program
  46037. /**
  46038. * Creates a shader program from the given programmable stage.
  46039. *
  46040. * @abstract
  46041. * @param {ProgrammableStage} program - The programmable stage.
  46042. */
  46043. createProgram( /*program*/ ) { }
  46044. /**
  46045. * Destroys the shader program of the given programmable stage.
  46046. *
  46047. * @abstract
  46048. * @param {ProgrammableStage} program - The programmable stage.
  46049. */
  46050. destroyProgram( /*program*/ ) { }
  46051. // bindings
  46052. /**
  46053. * Creates bindings from the given bind group definition.
  46054. *
  46055. * @abstract
  46056. * @param {BindGroup} bindGroup - The bind group.
  46057. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46058. * @param {number} cacheIndex - The cache index.
  46059. * @param {number} version - The version.
  46060. */
  46061. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  46062. /**
  46063. * Updates the given bind group definition.
  46064. *
  46065. * @abstract
  46066. * @param {BindGroup} bindGroup - The bind group.
  46067. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46068. * @param {number} cacheIndex - The cache index.
  46069. * @param {number} version - The version.
  46070. */
  46071. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  46072. /**
  46073. * Updates a buffer binding.
  46074. *
  46075. * @abstract
  46076. * @param {Buffer} binding - The buffer binding to update.
  46077. */
  46078. updateBinding( /*binding*/ ) { }
  46079. // pipeline
  46080. /**
  46081. * Creates a render pipeline for the given render object.
  46082. *
  46083. * @abstract
  46084. * @param {RenderObject} renderObject - The render object.
  46085. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  46086. */
  46087. createRenderPipeline( /*renderObject, promises*/ ) { }
  46088. /**
  46089. * Creates a compute pipeline for the given compute node.
  46090. *
  46091. * @abstract
  46092. * @param {ComputePipeline} computePipeline - The compute pipeline.
  46093. * @param {Array<BindGroup>} bindings - The bindings.
  46094. */
  46095. createComputePipeline( /*computePipeline, bindings*/ ) { }
  46096. // cache key
  46097. /**
  46098. * Returns `true` if the render pipeline requires an update.
  46099. *
  46100. * @abstract
  46101. * @param {RenderObject} renderObject - The render object.
  46102. * @return {boolean} Whether the render pipeline requires an update or not.
  46103. */
  46104. needsRenderUpdate( /*renderObject*/ ) { }
  46105. /**
  46106. * Returns a cache key that is used to identify render pipelines.
  46107. *
  46108. * @abstract
  46109. * @param {RenderObject} renderObject - The render object.
  46110. * @return {string} The cache key.
  46111. */
  46112. getRenderCacheKey( /*renderObject*/ ) { }
  46113. // node builder
  46114. /**
  46115. * Returns a node builder for the given render object.
  46116. *
  46117. * @abstract
  46118. * @param {RenderObject} renderObject - The render object.
  46119. * @param {Renderer} renderer - The renderer.
  46120. * @return {NodeBuilder} The node builder.
  46121. */
  46122. createNodeBuilder( /*renderObject, renderer*/ ) { }
  46123. // textures
  46124. /**
  46125. * Updates a GPU sampler for the given texture.
  46126. *
  46127. * @abstract
  46128. * @param {Texture} texture - The texture to update the sampler for.
  46129. * @return {string} The current sampler key.
  46130. */
  46131. updateSampler( /*texture*/ ) { }
  46132. /**
  46133. * Creates a default texture for the given texture that can be used
  46134. * as a placeholder until the actual texture is ready for usage.
  46135. *
  46136. * @abstract
  46137. * @param {Texture} texture - The texture to create a default texture for.
  46138. */
  46139. createDefaultTexture( /*texture*/ ) { }
  46140. /**
  46141. * Defines a texture on the GPU for the given texture object.
  46142. *
  46143. * @abstract
  46144. * @param {Texture} texture - The texture.
  46145. * @param {Object} [options={}] - Optional configuration parameter.
  46146. */
  46147. createTexture( /*texture, options={}*/ ) { }
  46148. /**
  46149. * Uploads the updated texture data to the GPU.
  46150. *
  46151. * @abstract
  46152. * @param {Texture} texture - The texture.
  46153. * @param {Object} [options={}] - Optional configuration parameter.
  46154. */
  46155. updateTexture( /*texture, options = {}*/ ) { }
  46156. /**
  46157. * Generates mipmaps for the given texture.
  46158. *
  46159. * @abstract
  46160. * @param {Texture} texture - The texture.
  46161. */
  46162. generateMipmaps( /*texture*/ ) { }
  46163. /**
  46164. * Destroys the GPU data for the given texture object.
  46165. *
  46166. * @abstract
  46167. * @param {Texture} texture - The texture.
  46168. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  46169. */
  46170. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  46171. /**
  46172. * Returns texture data as a typed array.
  46173. *
  46174. * @abstract
  46175. * @async
  46176. * @param {Texture} texture - The texture to copy.
  46177. * @param {number} x - The x coordinate of the copy origin.
  46178. * @param {number} y - The y coordinate of the copy origin.
  46179. * @param {number} width - The width of the copy.
  46180. * @param {number} height - The height of the copy.
  46181. * @param {number} faceIndex - The face index.
  46182. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46183. */
  46184. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  46185. /**
  46186. * Copies data of the given source texture to the given destination texture.
  46187. *
  46188. * @abstract
  46189. * @param {Texture} srcTexture - The source texture.
  46190. * @param {Texture} dstTexture - The destination texture.
  46191. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  46192. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  46193. * @param {number} [srcLevel=0] - The source mip level to copy from.
  46194. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  46195. */
  46196. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  46197. /**
  46198. * Copies the current bound framebuffer to the given texture.
  46199. *
  46200. * @abstract
  46201. * @param {Texture} texture - The destination texture.
  46202. * @param {RenderContext} renderContext - The render context.
  46203. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  46204. */
  46205. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  46206. // attributes
  46207. /**
  46208. * Creates the GPU buffer of a shader attribute.
  46209. *
  46210. * @abstract
  46211. * @param {BufferAttribute} attribute - The buffer attribute.
  46212. */
  46213. createAttribute( /*attribute*/ ) { }
  46214. /**
  46215. * Creates the GPU buffer of an indexed shader attribute.
  46216. *
  46217. * @abstract
  46218. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  46219. */
  46220. createIndexAttribute( /*attribute*/ ) { }
  46221. /**
  46222. * Creates the GPU buffer of a storage attribute.
  46223. *
  46224. * @abstract
  46225. * @param {BufferAttribute} attribute - The buffer attribute.
  46226. */
  46227. createStorageAttribute( /*attribute*/ ) { }
  46228. /**
  46229. * Updates the GPU buffer of a shader attribute.
  46230. *
  46231. * @abstract
  46232. * @param {BufferAttribute} attribute - The buffer attribute to update.
  46233. */
  46234. updateAttribute( /*attribute*/ ) { }
  46235. /**
  46236. * Destroys the GPU buffer of a shader attribute.
  46237. *
  46238. * @abstract
  46239. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  46240. */
  46241. destroyAttribute( /*attribute*/ ) { }
  46242. // canvas
  46243. /**
  46244. * Returns the backend's rendering context.
  46245. *
  46246. * @abstract
  46247. * @return {Object} The rendering context.
  46248. */
  46249. getContext() { }
  46250. /**
  46251. * Backends can use this method if they have to run
  46252. * logic when the renderer gets resized.
  46253. *
  46254. * @abstract
  46255. */
  46256. updateSize() { }
  46257. /**
  46258. * Updates the viewport with the values from the given render context.
  46259. *
  46260. * @abstract
  46261. * @param {RenderContext} renderContext - The render context.
  46262. */
  46263. updateViewport( /*renderContext*/ ) {}
  46264. // utils
  46265. /**
  46266. * Updates a unique identifier for the given render context that can be used
  46267. * to allocate resources like occlusion queries or timestamp queries.
  46268. *
  46269. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  46270. */
  46271. updateTimeStampUID( abstractRenderContext ) {
  46272. const contextData = this.get( abstractRenderContext );
  46273. const frame = this.renderer.info.frame;
  46274. let prefix;
  46275. if ( abstractRenderContext.isComputeNode === true ) {
  46276. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  46277. } else {
  46278. prefix = 'r:' + this.renderer.info.render.frameCalls;
  46279. }
  46280. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  46281. }
  46282. /**
  46283. * Returns a unique identifier for the given render context that can be used
  46284. * to allocate resources like occlusion queries or timestamp queries.
  46285. *
  46286. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  46287. * @return {string} The unique identifier.
  46288. */
  46289. getTimestampUID( abstractRenderContext ) {
  46290. return this.get( abstractRenderContext ).timestampUID;
  46291. }
  46292. /**
  46293. * Returns all timestamp frames for the given type.
  46294. *
  46295. * @param {string} type - The type of the time stamp.
  46296. * @return {Array<number>} The timestamp frames.
  46297. */
  46298. getTimestampFrames( type ) {
  46299. const queryPool = this.timestampQueryPool[ type ];
  46300. return queryPool ? queryPool.getTimestampFrames() : [];
  46301. }
  46302. /**
  46303. * Returns the query pool for the given uid.
  46304. *
  46305. * @param {string} uid - The unique identifier.
  46306. * @return {TimestampQueryPool} The query pool.
  46307. */
  46308. _getQueryPool( uid ) {
  46309. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  46310. const queryPool = this.timestampQueryPool[ type ];
  46311. return queryPool;
  46312. }
  46313. /**
  46314. * Returns the timestamp for the given uid.
  46315. *
  46316. * @param {string} uid - The unique identifier.
  46317. * @return {number} The timestamp.
  46318. */
  46319. getTimestamp( uid ) {
  46320. const queryPool = this._getQueryPool( uid );
  46321. return queryPool.getTimestamp( uid );
  46322. }
  46323. /**
  46324. * Returns `true` if a timestamp for the given uid is available.
  46325. *
  46326. * @param {string} uid - The unique identifier.
  46327. * @return {boolean} Whether the timestamp is available or not.
  46328. */
  46329. hasTimestamp( uid ) {
  46330. const queryPool = this._getQueryPool( uid );
  46331. return queryPool.hasTimestamp( uid );
  46332. }
  46333. /**
  46334. * Returns `true` if the given 3D object is fully occluded by other
  46335. * 3D objects in the scene. Backends must implement this method by using
  46336. * a Occlusion Query API.
  46337. *
  46338. * @abstract
  46339. * @param {RenderContext} renderContext - The render context.
  46340. * @param {Object3D} object - The 3D object to test.
  46341. * @return {boolean} Whether the 3D object is fully occluded or not.
  46342. */
  46343. isOccluded( /*renderContext, object*/ ) {}
  46344. /**
  46345. * Resolves the time stamp for the given render context and type.
  46346. *
  46347. * @async
  46348. * @abstract
  46349. * @param {string} [type='render'] - The type of the time stamp.
  46350. * @return {Promise<number>} A Promise that resolves with the time stamp.
  46351. */
  46352. async resolveTimestampsAsync( type = 'render' ) {
  46353. if ( ! this.trackTimestamp ) {
  46354. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  46355. return;
  46356. }
  46357. const queryPool = this.timestampQueryPool[ type ];
  46358. if ( ! queryPool ) {
  46359. return;
  46360. }
  46361. const duration = await queryPool.resolveQueriesAsync();
  46362. this.renderer.info[ type ].timestamp = duration;
  46363. return duration;
  46364. }
  46365. /**
  46366. * This method performs a readback operation by moving buffer data from
  46367. * a storage buffer attribute from the GPU to the CPU.
  46368. *
  46369. * @async
  46370. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46371. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46372. */
  46373. async getArrayBufferAsync( /* attribute */ ) {}
  46374. /**
  46375. * Checks if the given feature is supported by the backend.
  46376. *
  46377. * @async
  46378. * @abstract
  46379. * @param {string} name - The feature's name.
  46380. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  46381. */
  46382. async hasFeatureAsync( /*name*/ ) { }
  46383. /**
  46384. * Checks if the given feature is supported by the backend.
  46385. *
  46386. * @abstract
  46387. * @param {string} name - The feature's name.
  46388. * @return {boolean} Whether the feature is supported or not.
  46389. */
  46390. hasFeature( /*name*/ ) {}
  46391. /**
  46392. * Returns the drawing buffer size.
  46393. *
  46394. * @return {Vector2} The drawing buffer size.
  46395. */
  46396. getDrawingBufferSize() {
  46397. _vector2 = _vector2 || new Vector2();
  46398. return this.renderer.getDrawingBufferSize( _vector2 );
  46399. }
  46400. /**
  46401. * Defines the scissor test.
  46402. *
  46403. * @abstract
  46404. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  46405. */
  46406. setScissorTest( /*boolean*/ ) { }
  46407. /**
  46408. * Returns the clear color and alpha into a single
  46409. * color object.
  46410. *
  46411. * @return {Color4} The clear color.
  46412. */
  46413. getClearColor() {
  46414. const renderer = this.renderer;
  46415. _color4 = _color4 || new Color4();
  46416. renderer.getClearColor( _color4 );
  46417. _color4.getRGB( _color4 );
  46418. return _color4;
  46419. }
  46420. /**
  46421. * Returns the DOM element. If no DOM element exists, the backend
  46422. * creates a new one.
  46423. *
  46424. * @return {HTMLCanvasElement} The DOM element.
  46425. */
  46426. getDomElement() {
  46427. let domElement = this.domElement;
  46428. if ( domElement === null ) {
  46429. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  46430. // OffscreenCanvas does not have setAttribute, see #22811
  46431. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  46432. this.domElement = domElement;
  46433. }
  46434. return domElement;
  46435. }
  46436. /**
  46437. * Checks if the backend has the given compatibility.
  46438. *
  46439. * @abstract
  46440. * @param {string} name - The compatibility.
  46441. * @return {boolean} Whether the backend has the given compatibility or not.
  46442. */
  46443. hasCompatibility( /*name*/ ) {
  46444. return false;
  46445. }
  46446. /**
  46447. * Initializes the render target defined in the given render context.
  46448. *
  46449. * @abstract
  46450. * @param {RenderContext} renderContext - The render context.
  46451. */
  46452. initRenderTarget( /*renderContext*/ ) {}
  46453. /**
  46454. * Sets a dictionary for the given object into the
  46455. * internal data structure.
  46456. *
  46457. * @param {Object} object - The object.
  46458. * @param {Object} value - The dictionary to set.
  46459. */
  46460. set( object, value ) {
  46461. this.data.set( object, value );
  46462. }
  46463. /**
  46464. * Returns the dictionary for the given object.
  46465. *
  46466. * @param {Object} object - The object.
  46467. * @return {Object} The object's dictionary.
  46468. */
  46469. get( object ) {
  46470. let map = this.data.get( object );
  46471. if ( map === undefined ) {
  46472. map = {};
  46473. this.data.set( object, map );
  46474. }
  46475. return map;
  46476. }
  46477. /**
  46478. * Checks if the given object has a dictionary
  46479. * with data defined.
  46480. *
  46481. * @param {Object} object - The object.
  46482. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  46483. */
  46484. has( object ) {
  46485. return this.data.has( object );
  46486. }
  46487. /**
  46488. * Deletes an object from the internal data structure.
  46489. *
  46490. * @param {Object} object - The object to delete.
  46491. */
  46492. delete( object ) {
  46493. this.data.delete( object );
  46494. }
  46495. /**
  46496. * Delete GPU data associated with a bind group.
  46497. *
  46498. * @abstract
  46499. * @param {BindGroup} bindGroup - The bind group.
  46500. */
  46501. deleteBindGroupData( /*bindGroup*/ ) { }
  46502. /**
  46503. * Frees internal resources.
  46504. *
  46505. * @abstract
  46506. */
  46507. dispose() { }
  46508. }
  46509. let _id$1 = 0;
  46510. /**
  46511. * This module is internally used in context of compute shaders.
  46512. * This type of shader is not natively supported in WebGL 2 and
  46513. * thus implemented via Transform Feedback. `DualAttributeData`
  46514. * manages the related data.
  46515. *
  46516. * @private
  46517. */
  46518. class DualAttributeData {
  46519. constructor( attributeData, dualBuffer ) {
  46520. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  46521. this.type = attributeData.type;
  46522. this.bufferType = attributeData.bufferType;
  46523. this.pbo = attributeData.pbo;
  46524. this.byteLength = attributeData.byteLength;
  46525. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  46526. this.version = attributeData.version;
  46527. this.isInteger = attributeData.isInteger;
  46528. this.activeBufferIndex = 0;
  46529. this.baseId = attributeData.id;
  46530. }
  46531. get id() {
  46532. return `${ this.baseId }|${ this.activeBufferIndex }`;
  46533. }
  46534. get bufferGPU() {
  46535. return this.buffers[ this.activeBufferIndex ];
  46536. }
  46537. get transformBuffer() {
  46538. return this.buffers[ this.activeBufferIndex ^ 1 ];
  46539. }
  46540. switchBuffers() {
  46541. this.activeBufferIndex ^= 1;
  46542. }
  46543. }
  46544. /**
  46545. * A WebGL 2 backend utility module for managing shader attributes.
  46546. *
  46547. * @private
  46548. */
  46549. class WebGLAttributeUtils {
  46550. /**
  46551. * Constructs a new utility object.
  46552. *
  46553. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46554. */
  46555. constructor( backend ) {
  46556. /**
  46557. * A reference to the WebGL 2 backend.
  46558. *
  46559. * @type {WebGLBackend}
  46560. */
  46561. this.backend = backend;
  46562. }
  46563. /**
  46564. * Creates the GPU buffer for the given buffer attribute.
  46565. *
  46566. * @param {BufferAttribute} attribute - The buffer attribute.
  46567. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  46568. */
  46569. createAttribute( attribute, bufferType ) {
  46570. const backend = this.backend;
  46571. const { gl } = backend;
  46572. const array = attribute.array;
  46573. const usage = attribute.usage || gl.STATIC_DRAW;
  46574. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  46575. const bufferData = backend.get( bufferAttribute );
  46576. let bufferGPU = bufferData.bufferGPU;
  46577. if ( bufferGPU === undefined ) {
  46578. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  46579. bufferData.bufferGPU = bufferGPU;
  46580. bufferData.bufferType = bufferType;
  46581. bufferData.version = bufferAttribute.version;
  46582. }
  46583. //attribute.onUploadCallback();
  46584. let type;
  46585. if ( array instanceof Float32Array ) {
  46586. type = gl.FLOAT;
  46587. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  46588. type = gl.HALF_FLOAT;
  46589. } else if ( array instanceof Uint16Array ) {
  46590. if ( attribute.isFloat16BufferAttribute ) {
  46591. type = gl.HALF_FLOAT;
  46592. } else {
  46593. type = gl.UNSIGNED_SHORT;
  46594. }
  46595. } else if ( array instanceof Int16Array ) {
  46596. type = gl.SHORT;
  46597. } else if ( array instanceof Uint32Array ) {
  46598. type = gl.UNSIGNED_INT;
  46599. } else if ( array instanceof Int32Array ) {
  46600. type = gl.INT;
  46601. } else if ( array instanceof Int8Array ) {
  46602. type = gl.BYTE;
  46603. } else if ( array instanceof Uint8Array ) {
  46604. type = gl.UNSIGNED_BYTE;
  46605. } else if ( array instanceof Uint8ClampedArray ) {
  46606. type = gl.UNSIGNED_BYTE;
  46607. } else {
  46608. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  46609. }
  46610. let attributeData = {
  46611. bufferGPU,
  46612. bufferType,
  46613. type,
  46614. byteLength: array.byteLength,
  46615. bytesPerElement: array.BYTES_PER_ELEMENT,
  46616. version: attribute.version,
  46617. pbo: attribute.pbo,
  46618. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  46619. id: _id$1 ++
  46620. };
  46621. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  46622. // create buffer for transform feedback use
  46623. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  46624. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  46625. }
  46626. backend.set( attribute, attributeData );
  46627. }
  46628. /**
  46629. * Updates the GPU buffer of the given buffer attribute.
  46630. *
  46631. * @param {BufferAttribute} attribute - The buffer attribute.
  46632. */
  46633. updateAttribute( attribute ) {
  46634. const backend = this.backend;
  46635. const { gl } = backend;
  46636. const array = attribute.array;
  46637. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  46638. const bufferData = backend.get( bufferAttribute );
  46639. const bufferType = bufferData.bufferType;
  46640. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  46641. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  46642. if ( updateRanges.length === 0 ) {
  46643. // Not using update ranges
  46644. gl.bufferSubData( bufferType, 0, array );
  46645. } else {
  46646. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  46647. const range = updateRanges[ i ];
  46648. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  46649. array, range.start, range.count );
  46650. }
  46651. bufferAttribute.clearUpdateRanges();
  46652. }
  46653. gl.bindBuffer( bufferType, null );
  46654. bufferData.version = bufferAttribute.version;
  46655. }
  46656. /**
  46657. * Destroys the GPU buffer of the given buffer attribute.
  46658. *
  46659. * @param {BufferAttribute} attribute - The buffer attribute.
  46660. */
  46661. destroyAttribute( attribute ) {
  46662. const backend = this.backend;
  46663. const { gl } = backend;
  46664. if ( attribute.isInterleavedBufferAttribute ) {
  46665. backend.delete( attribute.data );
  46666. }
  46667. const attributeData = backend.get( attribute );
  46668. gl.deleteBuffer( attributeData.bufferGPU );
  46669. backend.delete( attribute );
  46670. }
  46671. /**
  46672. * This method performs a readback operation by moving buffer data from
  46673. * a storage buffer attribute from the GPU to the CPU.
  46674. *
  46675. * @async
  46676. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46677. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46678. */
  46679. async getArrayBufferAsync( attribute ) {
  46680. const backend = this.backend;
  46681. const { gl } = backend;
  46682. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  46683. const { bufferGPU } = backend.get( bufferAttribute );
  46684. const array = attribute.array;
  46685. const byteLength = array.byteLength;
  46686. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  46687. const writeBuffer = gl.createBuffer();
  46688. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  46689. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  46690. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  46691. await backend.utils._clientWaitAsync();
  46692. const dstBuffer = new attribute.array.constructor( array.length );
  46693. // Ensure the buffer is bound before reading
  46694. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  46695. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  46696. gl.deleteBuffer( writeBuffer );
  46697. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  46698. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  46699. return dstBuffer.buffer;
  46700. }
  46701. /**
  46702. * Creates a WebGL buffer with the given data.
  46703. *
  46704. * @private
  46705. * @param {WebGL2RenderingContext} gl - The rendering context.
  46706. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  46707. * @param {TypedArray} array - The array of the buffer attribute.
  46708. * @param {GLenum} usage - The usage.
  46709. * @return {WebGLBuffer} The WebGL buffer.
  46710. */
  46711. _createBuffer( gl, bufferType, array, usage ) {
  46712. const bufferGPU = gl.createBuffer();
  46713. gl.bindBuffer( bufferType, bufferGPU );
  46714. gl.bufferData( bufferType, array, usage );
  46715. gl.bindBuffer( bufferType, null );
  46716. return bufferGPU;
  46717. }
  46718. }
  46719. let equationToGL, factorToGL;
  46720. /**
  46721. * A WebGL 2 backend utility module for managing the WebGL state.
  46722. *
  46723. * The major goal of this module is to reduce the number of state changes
  46724. * by caching the WEbGL state with a series of variables. In this way, the
  46725. * renderer only executes state change commands when necessary which
  46726. * improves the overall performance.
  46727. *
  46728. * @private
  46729. */
  46730. class WebGLState {
  46731. /**
  46732. * Constructs a new utility object.
  46733. *
  46734. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46735. */
  46736. constructor( backend ) {
  46737. /**
  46738. * A reference to the WebGL 2 backend.
  46739. *
  46740. * @type {WebGLBackend}
  46741. */
  46742. this.backend = backend;
  46743. /**
  46744. * A reference to the rendering context.
  46745. *
  46746. * @type {WebGL2RenderingContext}
  46747. */
  46748. this.gl = this.backend.gl;
  46749. // Below properties are intended to cache
  46750. // the WebGL state and are not explicitly
  46751. // documented for convenience reasons.
  46752. this.enabled = {};
  46753. this.parameters = {};
  46754. this.currentFlipSided = null;
  46755. this.currentCullFace = null;
  46756. this.currentProgram = null;
  46757. this.currentBlendingEnabled = false;
  46758. this.currentBlending = null;
  46759. this.currentBlendSrc = null;
  46760. this.currentBlendDst = null;
  46761. this.currentBlendSrcAlpha = null;
  46762. this.currentBlendDstAlpha = null;
  46763. this.currentPremultipledAlpha = null;
  46764. this.currentPolygonOffsetFactor = null;
  46765. this.currentPolygonOffsetUnits = null;
  46766. this.currentColorMask = null;
  46767. this.currentDepthReversed = false;
  46768. this.currentDepthFunc = null;
  46769. this.currentDepthMask = null;
  46770. this.currentStencilFunc = null;
  46771. this.currentStencilRef = null;
  46772. this.currentStencilFuncMask = null;
  46773. this.currentStencilFail = null;
  46774. this.currentStencilZFail = null;
  46775. this.currentStencilZPass = null;
  46776. this.currentStencilMask = null;
  46777. this.currentLineWidth = null;
  46778. this.currentClippingPlanes = 0;
  46779. this.currentVAO = null;
  46780. this.currentIndex = null;
  46781. this.currentBoundFramebuffers = {};
  46782. this.currentDrawbuffers = new WeakMap();
  46783. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  46784. this.currentTextureSlot = null;
  46785. this.currentBoundTextures = {};
  46786. this.currentBoundBufferBases = {};
  46787. this._init();
  46788. }
  46789. /**
  46790. * Inits the state of the utility.
  46791. *
  46792. * @private
  46793. */
  46794. _init() {
  46795. const gl = this.gl;
  46796. // Store only WebGL constants here.
  46797. equationToGL = {
  46798. [ AddEquation ]: gl.FUNC_ADD,
  46799. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  46800. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  46801. };
  46802. factorToGL = {
  46803. [ ZeroFactor ]: gl.ZERO,
  46804. [ OneFactor ]: gl.ONE,
  46805. [ SrcColorFactor ]: gl.SRC_COLOR,
  46806. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  46807. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  46808. [ DstColorFactor ]: gl.DST_COLOR,
  46809. [ DstAlphaFactor ]: gl.DST_ALPHA,
  46810. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  46811. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  46812. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  46813. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  46814. };
  46815. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  46816. const viewportParam = gl.getParameter( gl.VIEWPORT );
  46817. this.currentScissor = new Vector4().fromArray( scissorParam );
  46818. this.currentViewport = new Vector4().fromArray( viewportParam );
  46819. this._tempVec4 = new Vector4();
  46820. }
  46821. /**
  46822. * Enables the given WebGL capability.
  46823. *
  46824. * This method caches the capability state so
  46825. * `gl.enable()` is only called when necessary.
  46826. *
  46827. * @param {GLenum} id - The capability to enable.
  46828. */
  46829. enable( id ) {
  46830. const { enabled } = this;
  46831. if ( enabled[ id ] !== true ) {
  46832. this.gl.enable( id );
  46833. enabled[ id ] = true;
  46834. }
  46835. }
  46836. /**
  46837. * Disables the given WebGL capability.
  46838. *
  46839. * This method caches the capability state so
  46840. * `gl.disable()` is only called when necessary.
  46841. *
  46842. * @param {GLenum} id - The capability to enable.
  46843. */
  46844. disable( id ) {
  46845. const { enabled } = this;
  46846. if ( enabled[ id ] !== false ) {
  46847. this.gl.disable( id );
  46848. enabled[ id ] = false;
  46849. }
  46850. }
  46851. /**
  46852. * Specifies whether polygons are front- or back-facing
  46853. * by setting the winding orientation.
  46854. *
  46855. * This method caches the state so `gl.frontFace()` is only
  46856. * called when necessary.
  46857. *
  46858. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  46859. */
  46860. setFlipSided( flipSided ) {
  46861. if ( this.currentFlipSided !== flipSided ) {
  46862. const { gl } = this;
  46863. if ( flipSided ) {
  46864. gl.frontFace( gl.CW );
  46865. } else {
  46866. gl.frontFace( gl.CCW );
  46867. }
  46868. this.currentFlipSided = flipSided;
  46869. }
  46870. }
  46871. /**
  46872. * Specifies whether or not front- and/or back-facing
  46873. * polygons can be culled.
  46874. *
  46875. * This method caches the state so `gl.cullFace()` is only
  46876. * called when necessary.
  46877. *
  46878. * @param {number} cullFace - Defines which polygons are candidates for culling.
  46879. */
  46880. setCullFace( cullFace ) {
  46881. const { gl } = this;
  46882. if ( cullFace !== CullFaceNone ) {
  46883. this.enable( gl.CULL_FACE );
  46884. if ( cullFace !== this.currentCullFace ) {
  46885. if ( cullFace === CullFaceBack ) {
  46886. gl.cullFace( gl.BACK );
  46887. } else if ( cullFace === CullFaceFront ) {
  46888. gl.cullFace( gl.FRONT );
  46889. } else {
  46890. gl.cullFace( gl.FRONT_AND_BACK );
  46891. }
  46892. }
  46893. } else {
  46894. this.disable( gl.CULL_FACE );
  46895. }
  46896. this.currentCullFace = cullFace;
  46897. }
  46898. /**
  46899. * Specifies the width of line primitives.
  46900. *
  46901. * This method caches the state so `gl.lineWidth()` is only
  46902. * called when necessary.
  46903. *
  46904. * @param {number} width - The line width.
  46905. */
  46906. setLineWidth( width ) {
  46907. const { currentLineWidth, gl } = this;
  46908. if ( width !== currentLineWidth ) {
  46909. gl.lineWidth( width );
  46910. this.currentLineWidth = width;
  46911. }
  46912. }
  46913. setMRTBlending( textures, mrt, material ) {
  46914. const gl = this.gl;
  46915. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  46916. if ( ! drawBuffersIndexedExt ) {
  46917. warnOnce( 'WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.' );
  46918. return;
  46919. }
  46920. for ( let i = 0; i < textures.length; i ++ ) {
  46921. const texture = textures[ i ];
  46922. let blending = null;
  46923. if ( mrt !== null ) {
  46924. const blendMode = mrt.getBlendMode( texture.name );
  46925. if ( blendMode.blending === MaterialBlending ) {
  46926. // use material blending
  46927. blending = material;
  46928. } else if ( blendMode.blending !== NoBlending ) {
  46929. blending = blendMode;
  46930. }
  46931. } else {
  46932. // use material blending
  46933. blending = material;
  46934. }
  46935. if ( blending !== null ) {
  46936. this._setMRTBlendingIndex( i, blending );
  46937. } else {
  46938. // use opaque blending (no blending)
  46939. drawBuffersIndexedExt.blendFuncSeparateiOES( i, gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  46940. }
  46941. }
  46942. }
  46943. /**
  46944. * Applies blending configuration for a specific draw buffer index.
  46945. *
  46946. * @private
  46947. * @param {number} index - The draw buffer index.
  46948. * @param {Object} blending - The blending configuration (material or BlendMode).
  46949. */
  46950. _setMRTBlendingIndex( index, blending ) {
  46951. const { gl } = this;
  46952. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  46953. const blendingType = blending.blending;
  46954. const blendSrc = blending.blendSrc;
  46955. const blendDst = blending.blendDst;
  46956. const blendEquation = blending.blendEquation;
  46957. const premultipliedAlpha = blending.premultipliedAlpha;
  46958. if ( blendingType === CustomBlending ) {
  46959. const blendSrcAlpha = blending.blendSrcAlpha !== null ? blending.blendSrcAlpha : blendSrc;
  46960. const blendDstAlpha = blending.blendDstAlpha !== null ? blending.blendDstAlpha : blendDst;
  46961. const blendEquationAlpha = blending.blendEquationAlpha !== null ? blending.blendEquationAlpha : blendEquation;
  46962. drawBuffersIndexedExt.blendEquationSeparateiOES( index, equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  46963. drawBuffersIndexedExt.blendFuncSeparateiOES( index, factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  46964. } else {
  46965. drawBuffersIndexedExt.blendEquationSeparateiOES( index, gl.FUNC_ADD, gl.FUNC_ADD );
  46966. if ( premultipliedAlpha ) {
  46967. switch ( blendingType ) {
  46968. case NormalBlending:
  46969. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46970. break;
  46971. case AdditiveBlending:
  46972. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  46973. break;
  46974. case SubtractiveBlending:
  46975. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  46976. break;
  46977. case MultiplyBlending:
  46978. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  46979. break;
  46980. default:
  46981. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46982. break;
  46983. }
  46984. } else {
  46985. switch ( blendingType ) {
  46986. case NormalBlending:
  46987. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46988. break;
  46989. case AdditiveBlending:
  46990. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  46991. break;
  46992. case SubtractiveBlending:
  46993. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  46994. break;
  46995. case MultiplyBlending:
  46996. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  46997. break;
  46998. default:
  46999. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  47000. break;
  47001. }
  47002. }
  47003. }
  47004. }
  47005. /**
  47006. * Defines the blending.
  47007. *
  47008. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  47009. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  47010. *
  47011. * @param {number} blending - The blending type.
  47012. * @param {number} blendEquation - The blending equation.
  47013. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  47014. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  47015. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  47016. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  47017. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  47018. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  47019. */
  47020. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  47021. const { gl } = this;
  47022. if ( blending === NoBlending ) {
  47023. if ( this.currentBlendingEnabled === true ) {
  47024. this.disable( gl.BLEND );
  47025. this.currentBlendingEnabled = false;
  47026. }
  47027. return;
  47028. }
  47029. if ( this.currentBlendingEnabled === false ) {
  47030. this.enable( gl.BLEND );
  47031. this.currentBlendingEnabled = true;
  47032. }
  47033. if ( blending !== CustomBlending ) {
  47034. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  47035. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  47036. gl.blendEquation( gl.FUNC_ADD );
  47037. this.currentBlendEquation = AddEquation;
  47038. this.currentBlendEquationAlpha = AddEquation;
  47039. }
  47040. if ( premultipliedAlpha ) {
  47041. switch ( blending ) {
  47042. case NormalBlending:
  47043. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  47044. break;
  47045. case AdditiveBlending:
  47046. gl.blendFunc( gl.ONE, gl.ONE );
  47047. break;
  47048. case SubtractiveBlending:
  47049. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  47050. break;
  47051. case MultiplyBlending:
  47052. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  47053. break;
  47054. default:
  47055. error( 'WebGLState: Invalid blending: ', blending );
  47056. break;
  47057. }
  47058. } else {
  47059. switch ( blending ) {
  47060. case NormalBlending:
  47061. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  47062. break;
  47063. case AdditiveBlending:
  47064. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  47065. break;
  47066. case SubtractiveBlending:
  47067. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  47068. break;
  47069. case MultiplyBlending:
  47070. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  47071. break;
  47072. default:
  47073. error( 'WebGLState: Invalid blending: ', blending );
  47074. break;
  47075. }
  47076. }
  47077. this.currentBlendSrc = null;
  47078. this.currentBlendDst = null;
  47079. this.currentBlendSrcAlpha = null;
  47080. this.currentBlendDstAlpha = null;
  47081. this.currentBlending = blending;
  47082. this.currentPremultipledAlpha = premultipliedAlpha;
  47083. }
  47084. return;
  47085. }
  47086. // custom blending
  47087. blendEquationAlpha = blendEquationAlpha || blendEquation;
  47088. blendSrcAlpha = blendSrcAlpha || blendSrc;
  47089. blendDstAlpha = blendDstAlpha || blendDst;
  47090. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  47091. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  47092. this.currentBlendEquation = blendEquation;
  47093. this.currentBlendEquationAlpha = blendEquationAlpha;
  47094. }
  47095. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  47096. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  47097. this.currentBlendSrc = blendSrc;
  47098. this.currentBlendDst = blendDst;
  47099. this.currentBlendSrcAlpha = blendSrcAlpha;
  47100. this.currentBlendDstAlpha = blendDstAlpha;
  47101. }
  47102. this.currentBlending = blending;
  47103. this.currentPremultipledAlpha = false;
  47104. }
  47105. /**
  47106. * Specifies whether colors can be written when rendering
  47107. * into a framebuffer or not.
  47108. *
  47109. * This method caches the state so `gl.colorMask()` is only
  47110. * called when necessary.
  47111. *
  47112. * @param {boolean} colorMask - The color mask.
  47113. */
  47114. setColorMask( colorMask ) {
  47115. if ( this.currentColorMask !== colorMask ) {
  47116. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  47117. this.currentColorMask = colorMask;
  47118. }
  47119. }
  47120. /**
  47121. * Specifies whether the depth test is enabled or not.
  47122. *
  47123. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  47124. */
  47125. setDepthTest( depthTest ) {
  47126. const { gl } = this;
  47127. if ( depthTest ) {
  47128. this.enable( gl.DEPTH_TEST );
  47129. } else {
  47130. this.disable( gl.DEPTH_TEST );
  47131. }
  47132. }
  47133. /**
  47134. * Configures the WebGL state to use a reversed depth buffer.
  47135. *
  47136. * @param {boolean} reversed - Whether the depth buffer is reversed or not.
  47137. */
  47138. setReversedDepth( reversed ) {
  47139. if ( this.currentDepthReversed !== reversed ) {
  47140. const ext = this.backend.extensions.get( 'EXT_clip_control' );
  47141. if ( reversed ) {
  47142. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  47143. } else {
  47144. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  47145. }
  47146. this.currentDepthReversed = reversed;
  47147. }
  47148. }
  47149. /**
  47150. * Specifies whether depth values can be written when rendering
  47151. * into a framebuffer or not.
  47152. *
  47153. * This method caches the state so `gl.depthMask()` is only
  47154. * called when necessary.
  47155. *
  47156. * @param {boolean} depthMask - The depth mask.
  47157. */
  47158. setDepthMask( depthMask ) {
  47159. if ( this.currentDepthMask !== depthMask ) {
  47160. this.gl.depthMask( depthMask );
  47161. this.currentDepthMask = depthMask;
  47162. }
  47163. }
  47164. /**
  47165. * Specifies the depth compare function.
  47166. *
  47167. * This method caches the state so `gl.depthFunc()` is only
  47168. * called when necessary.
  47169. *
  47170. * @param {number} depthFunc - The depth compare function.
  47171. */
  47172. setDepthFunc( depthFunc ) {
  47173. if ( this.currentDepthReversed ) depthFunc = ReversedDepthFuncs[ depthFunc ];
  47174. if ( this.currentDepthFunc !== depthFunc ) {
  47175. const { gl } = this;
  47176. switch ( depthFunc ) {
  47177. case NeverDepth:
  47178. gl.depthFunc( gl.NEVER );
  47179. break;
  47180. case AlwaysDepth:
  47181. gl.depthFunc( gl.ALWAYS );
  47182. break;
  47183. case LessDepth:
  47184. gl.depthFunc( gl.LESS );
  47185. break;
  47186. case LessEqualDepth:
  47187. gl.depthFunc( gl.LEQUAL );
  47188. break;
  47189. case EqualDepth:
  47190. gl.depthFunc( gl.EQUAL );
  47191. break;
  47192. case GreaterEqualDepth:
  47193. gl.depthFunc( gl.GEQUAL );
  47194. break;
  47195. case GreaterDepth:
  47196. gl.depthFunc( gl.GREATER );
  47197. break;
  47198. case NotEqualDepth:
  47199. gl.depthFunc( gl.NOTEQUAL );
  47200. break;
  47201. default:
  47202. gl.depthFunc( gl.LEQUAL );
  47203. }
  47204. this.currentDepthFunc = depthFunc;
  47205. }
  47206. }
  47207. /**
  47208. * Specifies the scissor box.
  47209. *
  47210. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  47211. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  47212. * @param {number} width - The width of the viewport.
  47213. * @param {number} height - The height of the viewport.
  47214. *
  47215. */
  47216. scissor( x, y, width, height ) {
  47217. const scissor = this._tempVec4.set( x, y, width, height );
  47218. if ( this.currentScissor.equals( scissor ) === false ) {
  47219. const { gl } = this;
  47220. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  47221. this.currentScissor.copy( scissor );
  47222. }
  47223. }
  47224. /**
  47225. * Specifies the viewport.
  47226. *
  47227. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  47228. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  47229. * @param {number} width - The width of the viewport.
  47230. * @param {number} height - The height of the viewport.
  47231. *
  47232. */
  47233. viewport( x, y, width, height ) {
  47234. const viewport = this._tempVec4.set( x, y, width, height );
  47235. if ( this.currentViewport.equals( viewport ) === false ) {
  47236. const { gl } = this;
  47237. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  47238. this.currentViewport.copy( viewport );
  47239. }
  47240. }
  47241. /**
  47242. * Defines the scissor test.
  47243. *
  47244. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  47245. */
  47246. setScissorTest( boolean ) {
  47247. const gl = this.gl;
  47248. if ( boolean ) {
  47249. this.enable( gl.SCISSOR_TEST );
  47250. } else {
  47251. this.disable( gl.SCISSOR_TEST );
  47252. }
  47253. }
  47254. /**
  47255. * Specifies whether the stencil test is enabled or not.
  47256. *
  47257. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  47258. */
  47259. setStencilTest( stencilTest ) {
  47260. const { gl } = this;
  47261. if ( stencilTest ) {
  47262. this.enable( gl.STENCIL_TEST );
  47263. } else {
  47264. this.disable( gl.STENCIL_TEST );
  47265. }
  47266. }
  47267. /**
  47268. * Specifies whether stencil values can be written when rendering
  47269. * into a framebuffer or not.
  47270. *
  47271. * This method caches the state so `gl.stencilMask()` is only
  47272. * called when necessary.
  47273. *
  47274. * @param {boolean} stencilMask - The stencil mask.
  47275. */
  47276. setStencilMask( stencilMask ) {
  47277. if ( this.currentStencilMask !== stencilMask ) {
  47278. this.gl.stencilMask( stencilMask );
  47279. this.currentStencilMask = stencilMask;
  47280. }
  47281. }
  47282. /**
  47283. * Specifies whether the stencil test functions.
  47284. *
  47285. * This method caches the state so `gl.stencilFunc()` is only
  47286. * called when necessary.
  47287. *
  47288. * @param {number} stencilFunc - The stencil compare function.
  47289. * @param {number} stencilRef - The reference value for the stencil test.
  47290. * @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.
  47291. */
  47292. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  47293. if ( this.currentStencilFunc !== stencilFunc ||
  47294. this.currentStencilRef !== stencilRef ||
  47295. this.currentStencilFuncMask !== stencilMask ) {
  47296. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  47297. this.currentStencilFunc = stencilFunc;
  47298. this.currentStencilRef = stencilRef;
  47299. this.currentStencilFuncMask = stencilMask;
  47300. }
  47301. }
  47302. /**
  47303. * Specifies whether the stencil test operation.
  47304. *
  47305. * This method caches the state so `gl.stencilOp()` is only
  47306. * called when necessary.
  47307. *
  47308. * @param {number} stencilFail - The function to use when the stencil test fails.
  47309. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  47310. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  47311. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  47312. */
  47313. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  47314. if ( this.currentStencilFail !== stencilFail ||
  47315. this.currentStencilZFail !== stencilZFail ||
  47316. this.currentStencilZPass !== stencilZPass ) {
  47317. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  47318. this.currentStencilFail = stencilFail;
  47319. this.currentStencilZFail = stencilZFail;
  47320. this.currentStencilZPass = stencilZPass;
  47321. }
  47322. }
  47323. /**
  47324. * Configures the WebGL state for the given material.
  47325. *
  47326. * @param {Material} material - The material to configure the state for.
  47327. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  47328. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  47329. */
  47330. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  47331. const { gl } = this;
  47332. material.side === DoubleSide
  47333. ? this.disable( gl.CULL_FACE )
  47334. : this.enable( gl.CULL_FACE );
  47335. let flipSided = ( material.side === BackSide );
  47336. if ( frontFaceCW ) flipSided = ! flipSided;
  47337. this.setFlipSided( flipSided );
  47338. ( material.blending === NormalBlending && material.transparent === false )
  47339. ? this.setBlending( NoBlending )
  47340. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  47341. this.setDepthFunc( material.depthFunc );
  47342. this.setDepthTest( material.depthTest );
  47343. this.setDepthMask( material.depthWrite );
  47344. this.setColorMask( material.colorWrite );
  47345. const stencilWrite = material.stencilWrite;
  47346. this.setStencilTest( stencilWrite );
  47347. if ( stencilWrite ) {
  47348. this.setStencilMask( material.stencilWriteMask );
  47349. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  47350. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  47351. }
  47352. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  47353. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  47354. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  47355. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  47356. if ( hardwareClippingPlanes > 0 ) {
  47357. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  47358. const CLIP_DISTANCE0_WEBGL = 0x3000;
  47359. for ( let i = 0; i < 8; i ++ ) {
  47360. if ( i < hardwareClippingPlanes ) {
  47361. this.enable( CLIP_DISTANCE0_WEBGL + i );
  47362. } else {
  47363. this.disable( CLIP_DISTANCE0_WEBGL + i );
  47364. }
  47365. }
  47366. }
  47367. }
  47368. }
  47369. /**
  47370. * Specifies the polygon offset.
  47371. *
  47372. * This method caches the state so `gl.polygonOffset()` is only
  47373. * called when necessary.
  47374. *
  47375. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  47376. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  47377. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  47378. */
  47379. setPolygonOffset( polygonOffset, factor, units ) {
  47380. const { gl } = this;
  47381. if ( polygonOffset ) {
  47382. this.enable( gl.POLYGON_OFFSET_FILL );
  47383. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  47384. gl.polygonOffset( factor, units );
  47385. this.currentPolygonOffsetFactor = factor;
  47386. this.currentPolygonOffsetUnits = units;
  47387. }
  47388. } else {
  47389. this.disable( gl.POLYGON_OFFSET_FILL );
  47390. }
  47391. }
  47392. /**
  47393. * Defines the usage of the given WebGL program.
  47394. *
  47395. * This method caches the state so `gl.useProgram()` is only
  47396. * called when necessary.
  47397. *
  47398. * @param {WebGLProgram} program - The WebGL program to use.
  47399. * @return {boolean} Whether a program change has been executed or not.
  47400. */
  47401. useProgram( program ) {
  47402. if ( this.currentProgram !== program ) {
  47403. this.gl.useProgram( program );
  47404. this.currentProgram = program;
  47405. return true;
  47406. }
  47407. return false;
  47408. }
  47409. /**
  47410. * Sets the vertex state by binding the given VAO and element buffer.
  47411. *
  47412. * @param {WebGLVertexArrayObject} vao - The VAO.
  47413. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  47414. * @return {boolean} Whether a vertex state has been changed or not.
  47415. */
  47416. setVertexState( vao, indexBuffer = null ) {
  47417. const gl = this.gl;
  47418. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  47419. gl.bindVertexArray( vao );
  47420. if ( indexBuffer !== null ) {
  47421. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  47422. }
  47423. this.currentVAO = vao;
  47424. this.currentIndex = indexBuffer;
  47425. return true;
  47426. }
  47427. return false;
  47428. }
  47429. /**
  47430. * Resets the vertex array state by resetting the VAO and element buffer.
  47431. */
  47432. resetVertexState() {
  47433. const gl = this.gl;
  47434. gl.bindVertexArray( null );
  47435. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  47436. this.currentVAO = null;
  47437. this.currentIndex = null;
  47438. }
  47439. // framebuffer
  47440. /**
  47441. * Binds the given framebuffer.
  47442. *
  47443. * This method caches the state so `gl.bindFramebuffer()` is only
  47444. * called when necessary.
  47445. *
  47446. * @param {number} target - The binding point (target).
  47447. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  47448. * @return {boolean} Whether a bind has been executed or not.
  47449. */
  47450. bindFramebuffer( target, framebuffer ) {
  47451. const { gl, currentBoundFramebuffers } = this;
  47452. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  47453. gl.bindFramebuffer( target, framebuffer );
  47454. currentBoundFramebuffers[ target ] = framebuffer;
  47455. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  47456. if ( target === gl.DRAW_FRAMEBUFFER ) {
  47457. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  47458. }
  47459. if ( target === gl.FRAMEBUFFER ) {
  47460. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  47461. }
  47462. return true;
  47463. }
  47464. return false;
  47465. }
  47466. /**
  47467. * Defines draw buffers to which fragment colors are written into.
  47468. * Configures the MRT setup of custom framebuffers.
  47469. *
  47470. * This method caches the state so `gl.drawBuffers()` is only
  47471. * called when necessary.
  47472. *
  47473. * @param {RenderContext} renderContext - The render context.
  47474. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  47475. */
  47476. drawBuffers( renderContext, framebuffer ) {
  47477. const { gl } = this;
  47478. let drawBuffers = [];
  47479. let needsUpdate = false;
  47480. if ( renderContext.textures !== null ) {
  47481. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  47482. if ( drawBuffers === undefined ) {
  47483. drawBuffers = [];
  47484. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  47485. }
  47486. const textures = renderContext.textures;
  47487. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  47488. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  47489. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  47490. }
  47491. drawBuffers.length = textures.length;
  47492. needsUpdate = true;
  47493. }
  47494. } else {
  47495. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  47496. drawBuffers[ 0 ] = gl.BACK;
  47497. needsUpdate = true;
  47498. }
  47499. }
  47500. if ( needsUpdate ) {
  47501. gl.drawBuffers( drawBuffers );
  47502. }
  47503. }
  47504. // texture
  47505. /**
  47506. * Makes the given texture unit active.
  47507. *
  47508. * This method caches the state so `gl.activeTexture()` is only
  47509. * called when necessary.
  47510. *
  47511. * @param {number} webglSlot - The texture unit to make active.
  47512. */
  47513. activeTexture( webglSlot ) {
  47514. const { gl, currentTextureSlot, maxTextures } = this;
  47515. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  47516. if ( currentTextureSlot !== webglSlot ) {
  47517. gl.activeTexture( webglSlot );
  47518. this.currentTextureSlot = webglSlot;
  47519. }
  47520. }
  47521. /**
  47522. * Binds the given WebGL texture to a target.
  47523. *
  47524. * This method caches the state so `gl.bindTexture()` is only
  47525. * called when necessary.
  47526. *
  47527. * @param {number} webglType - The binding point (target).
  47528. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  47529. * @param {number} webglSlot - The texture.
  47530. */
  47531. bindTexture( webglType, webglTexture, webglSlot ) {
  47532. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  47533. if ( webglSlot === undefined ) {
  47534. if ( currentTextureSlot === null ) {
  47535. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  47536. } else {
  47537. webglSlot = currentTextureSlot;
  47538. }
  47539. }
  47540. let boundTexture = currentBoundTextures[ webglSlot ];
  47541. if ( boundTexture === undefined ) {
  47542. boundTexture = { type: undefined, texture: undefined };
  47543. currentBoundTextures[ webglSlot ] = boundTexture;
  47544. }
  47545. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  47546. if ( currentTextureSlot !== webglSlot ) {
  47547. gl.activeTexture( webglSlot );
  47548. this.currentTextureSlot = webglSlot;
  47549. }
  47550. gl.bindTexture( webglType, webglTexture );
  47551. boundTexture.type = webglType;
  47552. boundTexture.texture = webglTexture;
  47553. }
  47554. }
  47555. /**
  47556. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  47557. *
  47558. * This method caches the state so `gl.bindBufferBase()` is only
  47559. * called when necessary.
  47560. *
  47561. * @param {number} target - The target for the bind operation.
  47562. * @param {number} index - The index of the target.
  47563. * @param {WebGLBuffer} buffer - The WebGL buffer.
  47564. * @return {boolean} Whether a bind has been executed or not.
  47565. */
  47566. bindBufferBase( target, index, buffer ) {
  47567. const { gl } = this;
  47568. const key = `${target}-${index}`;
  47569. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  47570. gl.bindBufferBase( target, index, buffer );
  47571. this.currentBoundBufferBases[ key ] = buffer;
  47572. return true;
  47573. }
  47574. return false;
  47575. }
  47576. /**
  47577. * Unbinds the current bound texture.
  47578. *
  47579. * This method caches the state so `gl.bindTexture()` is only
  47580. * called when necessary.
  47581. */
  47582. unbindTexture() {
  47583. const { gl, currentTextureSlot, currentBoundTextures } = this;
  47584. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  47585. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  47586. gl.bindTexture( boundTexture.type, null );
  47587. boundTexture.type = undefined;
  47588. boundTexture.texture = undefined;
  47589. }
  47590. }
  47591. /**
  47592. * Returns the value for the given parameter.
  47593. *
  47594. * @param {number} name - The paramter to get the value for.
  47595. * @return {any} The value for the given parameter.
  47596. */
  47597. getParameter( name ) {
  47598. const { gl, parameters } = this;
  47599. if ( parameters[ name ] !== undefined ) {
  47600. return parameters[ name ];
  47601. } else {
  47602. return gl.getParameter( name );
  47603. }
  47604. }
  47605. /**
  47606. * Specifies a pixel storage mode.
  47607. *
  47608. * @param {number} name - The parameter to set.
  47609. * @param {any} value - A value to set the parameter to.
  47610. */
  47611. pixelStorei( name, value ) {
  47612. const { gl, parameters } = this;
  47613. if ( parameters[ name ] !== value ) {
  47614. gl.pixelStorei( name, value );
  47615. parameters[ name ] = value;
  47616. }
  47617. }
  47618. }
  47619. /**
  47620. * A WebGL 2 backend utility module with common helpers.
  47621. *
  47622. * @private
  47623. */
  47624. class WebGLUtils {
  47625. /**
  47626. * Constructs a new utility object.
  47627. *
  47628. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47629. */
  47630. constructor( backend ) {
  47631. /**
  47632. * A reference to the WebGL 2 backend.
  47633. *
  47634. * @type {WebGLBackend}
  47635. */
  47636. this.backend = backend;
  47637. /**
  47638. * A reference to the rendering context.
  47639. *
  47640. * @type {WebGL2RenderingContext}
  47641. */
  47642. this.gl = this.backend.gl;
  47643. /**
  47644. * A reference to a backend module holding extension-related
  47645. * utility functions.
  47646. *
  47647. * @type {WebGLExtensions}
  47648. */
  47649. this.extensions = backend.extensions;
  47650. }
  47651. /**
  47652. * Converts the given three.js constant into a WebGL constant.
  47653. * The method currently supports the conversion of texture formats
  47654. * and types.
  47655. *
  47656. * @param {number} p - The three.js constant.
  47657. * @param {string} [colorSpace=NoColorSpace] - The color space.
  47658. * @return {?number} The corresponding WebGL constant.
  47659. */
  47660. convert( p, colorSpace = NoColorSpace ) {
  47661. const { gl, extensions } = this;
  47662. let extension;
  47663. const transfer = ColorManagement.getTransfer( colorSpace );
  47664. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  47665. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  47666. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  47667. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  47668. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  47669. if ( p === ByteType ) return gl.BYTE;
  47670. if ( p === ShortType ) return gl.SHORT;
  47671. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  47672. if ( p === IntType ) return gl.INT;
  47673. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  47674. if ( p === FloatType ) return gl.FLOAT;
  47675. if ( p === HalfFloatType ) {
  47676. return gl.HALF_FLOAT;
  47677. }
  47678. if ( p === AlphaFormat ) return gl.ALPHA;
  47679. if ( p === RGBFormat ) return gl.RGB;
  47680. if ( p === RGBAFormat ) return gl.RGBA;
  47681. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  47682. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  47683. // WebGL2 formats.
  47684. if ( p === RedFormat ) return gl.RED;
  47685. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  47686. if ( p === RGFormat ) return gl.RG;
  47687. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  47688. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  47689. // S3TC
  47690. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  47691. if ( transfer === SRGBTransfer ) {
  47692. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  47693. if ( extension !== null ) {
  47694. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  47695. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  47696. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  47697. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  47698. } else {
  47699. return null;
  47700. }
  47701. } else {
  47702. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  47703. if ( extension !== null ) {
  47704. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  47705. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  47706. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  47707. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  47708. } else {
  47709. return null;
  47710. }
  47711. }
  47712. }
  47713. // PVRTC
  47714. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  47715. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  47716. if ( extension !== null ) {
  47717. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  47718. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  47719. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  47720. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  47721. } else {
  47722. return null;
  47723. }
  47724. }
  47725. // ETC
  47726. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format || p === R11_EAC_Format || p === SIGNED_R11_EAC_Format || p === RG11_EAC_Format || p === SIGNED_RG11_EAC_Format ) {
  47727. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  47728. if ( extension !== null ) {
  47729. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  47730. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  47731. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  47732. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  47733. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  47734. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  47735. } else {
  47736. return null;
  47737. }
  47738. }
  47739. // ASTC
  47740. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  47741. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  47742. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  47743. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  47744. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  47745. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  47746. if ( extension !== null ) {
  47747. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  47748. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  47749. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  47750. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  47751. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  47752. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  47753. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  47754. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  47755. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  47756. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  47757. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  47758. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  47759. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  47760. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  47761. } else {
  47762. return null;
  47763. }
  47764. }
  47765. // BPTC
  47766. if ( p === RGBA_BPTC_Format ) {
  47767. extension = extensions.get( 'EXT_texture_compression_bptc' );
  47768. if ( extension !== null ) {
  47769. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  47770. } else {
  47771. return null;
  47772. }
  47773. }
  47774. // RGTC
  47775. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  47776. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  47777. if ( extension !== null ) {
  47778. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  47779. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  47780. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  47781. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  47782. } else {
  47783. return null;
  47784. }
  47785. }
  47786. //
  47787. if ( p === UnsignedInt248Type ) {
  47788. return gl.UNSIGNED_INT_24_8;
  47789. }
  47790. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  47791. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  47792. }
  47793. /**
  47794. * This method can be used to synchronize the CPU with the GPU by waiting until
  47795. * ongoing GPU commands have been completed.
  47796. *
  47797. * @private
  47798. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  47799. */
  47800. _clientWaitAsync() {
  47801. const { gl } = this;
  47802. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  47803. gl.flush();
  47804. return new Promise( ( resolve, reject ) => {
  47805. function test() {
  47806. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  47807. if ( res === gl.WAIT_FAILED ) {
  47808. gl.deleteSync( sync );
  47809. reject();
  47810. return;
  47811. }
  47812. if ( res === gl.TIMEOUT_EXPIRED ) {
  47813. requestAnimationFrame( test );
  47814. return;
  47815. }
  47816. gl.deleteSync( sync );
  47817. resolve();
  47818. }
  47819. test();
  47820. } );
  47821. }
  47822. }
  47823. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  47824. /**
  47825. * A WebGL 2 backend utility module for managing textures.
  47826. *
  47827. * @private
  47828. */
  47829. class WebGLTextureUtils {
  47830. /**
  47831. * Constructs a new utility object.
  47832. *
  47833. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47834. */
  47835. constructor( backend ) {
  47836. /**
  47837. * A reference to the WebGL 2 backend.
  47838. *
  47839. * @type {WebGLBackend}
  47840. */
  47841. this.backend = backend;
  47842. /**
  47843. * A reference to the rendering context.
  47844. *
  47845. * @type {WebGL2RenderingContext}
  47846. */
  47847. this.gl = backend.gl;
  47848. /**
  47849. * A reference to a backend module holding extension-related
  47850. * utility functions.
  47851. *
  47852. * @type {WebGLExtensions}
  47853. */
  47854. this.extensions = backend.extensions;
  47855. /**
  47856. * A dictionary for managing default textures. The key
  47857. * is the binding point (target), the value the WEbGL texture object.
  47858. *
  47859. * @type {Object<GLenum,WebGLTexture>}
  47860. */
  47861. this.defaultTextures = {};
  47862. /**
  47863. * A scratch framebuffer used for attaching the source texture in
  47864. * {@link copyTextureToTexture}.
  47865. *
  47866. * @private
  47867. * @type {?WebGLFramebuffer}
  47868. */
  47869. this._srcFramebuffer = null;
  47870. /**
  47871. * A scratch framebuffer used for attaching the destination texture in
  47872. * {@link copyTextureToTexture}.
  47873. *
  47874. * @private
  47875. * @type {?WebGLFramebuffer}
  47876. */
  47877. this._dstFramebuffer = null;
  47878. if ( initialized === false ) {
  47879. this._init();
  47880. initialized = true;
  47881. }
  47882. }
  47883. /**
  47884. * Inits the state of the utility.
  47885. *
  47886. * @private
  47887. */
  47888. _init() {
  47889. const gl = this.gl;
  47890. // Store only WebGL constants here.
  47891. wrappingToGL = {
  47892. [ RepeatWrapping ]: gl.REPEAT,
  47893. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  47894. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  47895. };
  47896. filterToGL = {
  47897. [ NearestFilter ]: gl.NEAREST,
  47898. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  47899. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  47900. [ LinearFilter ]: gl.LINEAR,
  47901. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  47902. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  47903. };
  47904. compareToGL = {
  47905. [ NeverCompare ]: gl.NEVER,
  47906. [ AlwaysCompare ]: gl.ALWAYS,
  47907. [ LessCompare ]: gl.LESS,
  47908. [ LessEqualCompare ]: gl.LEQUAL,
  47909. [ EqualCompare ]: gl.EQUAL,
  47910. [ GreaterEqualCompare ]: gl.GEQUAL,
  47911. [ GreaterCompare ]: gl.GREATER,
  47912. [ NotEqualCompare ]: gl.NOTEQUAL
  47913. };
  47914. }
  47915. /**
  47916. * Returns the native texture type for the given texture.
  47917. *
  47918. * @param {Texture} texture - The texture.
  47919. * @return {GLenum} The native texture type.
  47920. */
  47921. getGLTextureType( texture ) {
  47922. const { gl } = this;
  47923. let glTextureType;
  47924. if ( texture.isCubeTexture === true ) {
  47925. glTextureType = gl.TEXTURE_CUBE_MAP;
  47926. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  47927. glTextureType = gl.TEXTURE_2D_ARRAY;
  47928. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  47929. glTextureType = gl.TEXTURE_3D;
  47930. } else {
  47931. glTextureType = gl.TEXTURE_2D;
  47932. }
  47933. return glTextureType;
  47934. }
  47935. /**
  47936. * Returns the native texture type for the given texture.
  47937. *
  47938. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  47939. * @param {GLenum} glFormat - The WebGL format.
  47940. * @param {GLenum} glType - The WebGL type.
  47941. * @param {string} colorSpace - The texture's color space.
  47942. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  47943. * @return {GLenum} The internal format.
  47944. */
  47945. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  47946. const { gl, extensions } = this;
  47947. if ( internalFormatName !== null ) {
  47948. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  47949. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  47950. }
  47951. let internalFormat = glFormat;
  47952. if ( glFormat === gl.RED ) {
  47953. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  47954. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  47955. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  47956. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  47957. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  47958. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  47959. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  47960. if ( glType === gl.INT ) internalFormat = gl.R32I;
  47961. }
  47962. if ( glFormat === gl.RED_INTEGER ) {
  47963. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  47964. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  47965. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  47966. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  47967. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  47968. if ( glType === gl.INT ) internalFormat = gl.R32I;
  47969. }
  47970. if ( glFormat === gl.RG ) {
  47971. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  47972. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  47973. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  47974. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  47975. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  47976. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  47977. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  47978. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  47979. }
  47980. if ( glFormat === gl.RG_INTEGER ) {
  47981. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  47982. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  47983. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  47984. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  47985. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  47986. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  47987. }
  47988. if ( glFormat === gl.RGB ) {
  47989. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47990. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  47991. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  47992. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  47993. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  47994. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  47995. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  47996. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  47997. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  47998. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  47999. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  48000. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  48001. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  48002. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  48003. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  48004. }
  48005. if ( glFormat === gl.RGB_INTEGER ) {
  48006. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  48007. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  48008. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  48009. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  48010. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  48011. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  48012. }
  48013. if ( glFormat === gl.RGBA ) {
  48014. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  48015. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  48016. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  48017. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  48018. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  48019. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  48020. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  48021. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  48022. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  48023. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  48024. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  48025. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  48026. }
  48027. if ( glFormat === gl.RGBA_INTEGER ) {
  48028. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  48029. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  48030. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  48031. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  48032. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  48033. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  48034. }
  48035. if ( glFormat === gl.DEPTH_COMPONENT ) {
  48036. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  48037. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  48038. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  48039. }
  48040. if ( glFormat === gl.DEPTH_STENCIL ) {
  48041. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  48042. }
  48043. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  48044. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  48045. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  48046. extensions.get( 'EXT_color_buffer_float' );
  48047. }
  48048. return internalFormat;
  48049. }
  48050. /**
  48051. * Sets the texture parameters for the given texture.
  48052. *
  48053. * @param {GLenum} textureType - The texture type.
  48054. * @param {Texture} texture - The texture.
  48055. */
  48056. setTextureParameters( textureType, texture ) {
  48057. const { gl, extensions, backend } = this;
  48058. const { state } = this.backend;
  48059. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  48060. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  48061. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  48062. state.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  48063. state.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  48064. state.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  48065. state.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  48066. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  48067. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  48068. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  48069. // WebGL 2 does not support wrapping for depth 2D array textures
  48070. if ( ! texture.isArrayTexture ) {
  48071. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  48072. }
  48073. }
  48074. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  48075. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  48076. // follow WebGPU backend mapping for texture filtering
  48077. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  48078. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  48079. if ( texture.compareFunction ) {
  48080. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  48081. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  48082. }
  48083. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  48084. if ( texture.magFilter === NearestFilter ) return;
  48085. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  48086. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  48087. if ( texture.anisotropy > 1 ) {
  48088. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  48089. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.capabilities.getMaxAnisotropy() ) );
  48090. }
  48091. }
  48092. }
  48093. /**
  48094. * Creates a default texture for the given texture that can be used
  48095. * as a placeholder until the actual texture is ready for usage.
  48096. *
  48097. * @param {Texture} texture - The texture to create a default texture for.
  48098. */
  48099. createDefaultTexture( texture ) {
  48100. const { gl, backend, defaultTextures } = this;
  48101. const glTextureType = this.getGLTextureType( texture );
  48102. let textureGPU = defaultTextures[ glTextureType ];
  48103. if ( textureGPU === undefined ) {
  48104. textureGPU = gl.createTexture();
  48105. backend.state.bindTexture( glTextureType, textureGPU );
  48106. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  48107. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  48108. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48109. defaultTextures[ glTextureType ] = textureGPU;
  48110. }
  48111. backend.set( texture, {
  48112. textureGPU,
  48113. glTextureType
  48114. } );
  48115. }
  48116. /**
  48117. * Defines a texture on the GPU for the given texture object.
  48118. *
  48119. * @param {Texture} texture - The texture.
  48120. * @param {Object} [options={}] - Optional configuration parameter.
  48121. * @return {undefined}
  48122. */
  48123. createTexture( texture, options ) {
  48124. const { gl, backend } = this;
  48125. const { levels, width, height, depth } = options;
  48126. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  48127. const glType = backend.utils.convert( texture.type );
  48128. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  48129. const textureGPU = gl.createTexture();
  48130. const glTextureType = this.getGLTextureType( texture );
  48131. backend.state.bindTexture( glTextureType, textureGPU );
  48132. this.setTextureParameters( glTextureType, texture );
  48133. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  48134. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  48135. } else if ( texture.isData3DTexture ) {
  48136. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  48137. } else if ( ! texture.isVideoTexture ) {
  48138. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  48139. }
  48140. backend.set( texture, {
  48141. textureGPU,
  48142. glTextureType,
  48143. glFormat,
  48144. glType,
  48145. glInternalFormat
  48146. } );
  48147. }
  48148. /**
  48149. * Uploads texture buffer data to the GPU memory.
  48150. *
  48151. * @param {WebGLBuffer} buffer - The buffer data.
  48152. * @param {Texture} texture - The texture,
  48153. */
  48154. copyBufferToTexture( buffer, texture ) {
  48155. const { gl, backend } = this;
  48156. const { state } = backend;
  48157. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  48158. const { width, height } = texture.source.data;
  48159. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  48160. backend.state.bindTexture( glTextureType, textureGPU );
  48161. state.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  48162. state.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  48163. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  48164. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  48165. backend.state.unbindTexture();
  48166. // debug
  48167. // const framebuffer = gl.createFramebuffer();
  48168. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  48169. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  48170. // const readout = new Float32Array( width * height * 4 );
  48171. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  48172. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  48173. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  48174. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, null );
  48175. // log( readout );
  48176. }
  48177. /**
  48178. * Uploads the updated texture data to the GPU.
  48179. *
  48180. * @param {Texture} texture - The texture.
  48181. * @param {Object} [options={}] - Optional configuration parameter.
  48182. */
  48183. updateTexture( texture, options ) {
  48184. const { gl } = this;
  48185. const { width, height } = options;
  48186. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  48187. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  48188. return;
  48189. this.backend.state.bindTexture( glTextureType, textureGPU );
  48190. this.setTextureParameters( glTextureType, texture );
  48191. if ( texture.isCompressedTexture ) {
  48192. const mipmaps = texture.mipmaps;
  48193. const image = options.image;
  48194. for ( let i = 0; i < mipmaps.length; i ++ ) {
  48195. const mipmap = mipmaps[ i ];
  48196. if ( texture.isCompressedArrayTexture ) {
  48197. if ( texture.format !== gl.RGBA ) {
  48198. if ( glFormat !== null ) {
  48199. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  48200. } else {
  48201. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  48202. }
  48203. } else {
  48204. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  48205. }
  48206. } else {
  48207. if ( glFormat !== null ) {
  48208. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  48209. } else {
  48210. warn( 'WebGLBackend: Unsupported compressed texture format' );
  48211. }
  48212. }
  48213. }
  48214. } else if ( texture.isCubeTexture ) {
  48215. const images = options.images;
  48216. const mipmaps = texture.mipmaps;
  48217. for ( let i = 0; i < 6; i ++ ) {
  48218. const image = getImage( images[ i ] );
  48219. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  48220. for ( let j = 0; j < mipmaps.length; j ++ ) {
  48221. const mipmap = mipmaps[ j ];
  48222. const image = getImage( mipmap.images[ i ] );
  48223. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  48224. }
  48225. }
  48226. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  48227. const image = options.image;
  48228. if ( texture.layerUpdates.size > 0 ) {
  48229. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  48230. for ( const layerIndex of texture.layerUpdates ) {
  48231. const layerData = image.data.subarray(
  48232. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  48233. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  48234. );
  48235. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  48236. }
  48237. texture.clearLayerUpdates();
  48238. } else {
  48239. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  48240. }
  48241. } else if ( texture.isData3DTexture ) {
  48242. const image = options.image;
  48243. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  48244. } else if ( texture.isVideoTexture ) {
  48245. texture.update();
  48246. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  48247. } else {
  48248. const mipmaps = texture.mipmaps;
  48249. if ( mipmaps.length > 0 ) {
  48250. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48251. const mipmap = mipmaps[ i ];
  48252. const image = getImage( mipmap );
  48253. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  48254. }
  48255. } else {
  48256. const image = getImage( options.image );
  48257. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  48258. }
  48259. }
  48260. }
  48261. /**
  48262. * Generates mipmaps for the given texture.
  48263. *
  48264. * @param {Texture} texture - The texture.
  48265. */
  48266. generateMipmaps( texture ) {
  48267. const { gl, backend } = this;
  48268. const { textureGPU, glTextureType } = backend.get( texture );
  48269. backend.state.bindTexture( glTextureType, textureGPU );
  48270. gl.generateMipmap( glTextureType );
  48271. }
  48272. /**
  48273. * Deallocates the render buffers of the given render target.
  48274. *
  48275. * @param {RenderTarget} renderTarget - The render target.
  48276. */
  48277. deallocateRenderBuffers( renderTarget ) {
  48278. const { gl, backend } = this;
  48279. // remove framebuffer reference
  48280. if ( renderTarget ) {
  48281. const renderContextData = backend.get( renderTarget );
  48282. renderContextData.renderBufferStorageSetup = undefined;
  48283. if ( renderContextData.framebuffers ) {
  48284. for ( const cacheKey in renderContextData.framebuffers ) {
  48285. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  48286. }
  48287. delete renderContextData.framebuffers;
  48288. }
  48289. if ( renderContextData.depthRenderbuffer ) {
  48290. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  48291. delete renderContextData.depthRenderbuffer;
  48292. }
  48293. if ( renderContextData.stencilRenderbuffer ) {
  48294. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  48295. delete renderContextData.stencilRenderbuffer;
  48296. }
  48297. if ( renderContextData.msaaFrameBuffer ) {
  48298. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  48299. delete renderContextData.msaaFrameBuffer;
  48300. }
  48301. if ( renderContextData.msaaRenderbuffers ) {
  48302. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  48303. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  48304. }
  48305. delete renderContextData.msaaRenderbuffers;
  48306. }
  48307. }
  48308. }
  48309. /**
  48310. * Destroys the GPU data for the given texture object.
  48311. *
  48312. * @param {Texture} texture - The texture.
  48313. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  48314. */
  48315. destroyTexture( texture, isDefaultTexture = false ) {
  48316. const { gl, backend } = this;
  48317. const { textureGPU, renderTarget } = backend.get( texture );
  48318. this.deallocateRenderBuffers( renderTarget );
  48319. if ( isDefaultTexture === false ) {
  48320. gl.deleteTexture( textureGPU );
  48321. }
  48322. backend.delete( texture );
  48323. }
  48324. /**
  48325. * Copies data of the given source texture to the given destination texture.
  48326. *
  48327. * @param {Texture} srcTexture - The source texture.
  48328. * @param {Texture} dstTexture - The destination texture.
  48329. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  48330. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  48331. * @param {number} [srcLevel=0] - The source mip level to copy from.
  48332. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  48333. */
  48334. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  48335. const { gl, backend } = this;
  48336. const { state } = this.backend;
  48337. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  48338. state.bindTexture( glTextureType, dstTextureGPU );
  48339. // gather the necessary dimensions to copy
  48340. let width, height, depth, minX, minY, minZ;
  48341. let dstX, dstY, dstZ;
  48342. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  48343. if ( srcRegion !== null ) {
  48344. width = srcRegion.max.x - srcRegion.min.x;
  48345. height = srcRegion.max.y - srcRegion.min.y;
  48346. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  48347. minX = srcRegion.min.x;
  48348. minY = srcRegion.min.y;
  48349. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  48350. } else {
  48351. const levelScale = Math.pow( 2, - srcLevel );
  48352. width = Math.floor( image.width * levelScale );
  48353. height = Math.floor( image.height * levelScale );
  48354. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  48355. depth = image.depth;
  48356. } else if ( srcTexture.isData3DTexture ) {
  48357. depth = Math.floor( image.depth * levelScale );
  48358. } else {
  48359. depth = 1;
  48360. }
  48361. minX = 0;
  48362. minY = 0;
  48363. minZ = 0;
  48364. }
  48365. if ( dstPosition !== null ) {
  48366. dstX = dstPosition.x;
  48367. dstY = dstPosition.y;
  48368. dstZ = dstPosition.z;
  48369. } else {
  48370. dstX = 0;
  48371. dstY = 0;
  48372. dstZ = 0;
  48373. }
  48374. state.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  48375. state.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  48376. state.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  48377. // used for copying data from cpu
  48378. const currentUnpackRowLen = state.getParameter( gl.UNPACK_ROW_LENGTH );
  48379. const currentUnpackImageHeight = state.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  48380. const currentUnpackSkipPixels = state.getParameter( gl.UNPACK_SKIP_PIXELS );
  48381. const currentUnpackSkipRows = state.getParameter( gl.UNPACK_SKIP_ROWS );
  48382. const currentUnpackSkipImages = state.getParameter( gl.UNPACK_SKIP_IMAGES );
  48383. state.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  48384. state.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  48385. state.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  48386. state.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  48387. state.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  48388. // set up the src texture
  48389. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  48390. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  48391. if ( srcTexture.isDepthTexture ) {
  48392. const srcTextureData = backend.get( srcTexture );
  48393. const dstTextureData = backend.get( dstTexture );
  48394. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  48395. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  48396. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  48397. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  48398. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  48399. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  48400. for ( let i = 0; i < depth; i ++ ) {
  48401. // if the source or destination are a 3d target then a layer needs to be bound
  48402. if ( isSrc3D ) {
  48403. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  48404. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  48405. }
  48406. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  48407. }
  48408. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  48409. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  48410. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  48411. // get the appropriate frame buffers
  48412. const srcTextureData = backend.get( srcTexture );
  48413. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  48414. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  48415. // bind the frame buffer targets
  48416. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  48417. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  48418. for ( let i = 0; i < depth; i ++ ) {
  48419. // assign the correct layers and mip maps to the frame buffers
  48420. if ( isSrc3D ) {
  48421. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  48422. } else {
  48423. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  48424. }
  48425. if ( isDst3D ) {
  48426. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  48427. } else {
  48428. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  48429. }
  48430. // copy the data using the fastest function that can achieve the copy
  48431. if ( srcLevel !== 0 ) {
  48432. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  48433. } else if ( isDst3D ) {
  48434. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  48435. } else {
  48436. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  48437. }
  48438. }
  48439. // unbind read, draw buffers
  48440. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  48441. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  48442. } else {
  48443. if ( isDst3D ) {
  48444. // copy data into the 3d texture
  48445. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  48446. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  48447. } else if ( dstTexture.isCompressedArrayTexture ) {
  48448. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  48449. } else {
  48450. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  48451. }
  48452. } else {
  48453. // copy data into the 2d texture
  48454. if ( srcTexture.isDataTexture ) {
  48455. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  48456. } else if ( srcTexture.isCompressedTexture ) {
  48457. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  48458. } else {
  48459. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  48460. }
  48461. }
  48462. }
  48463. // reset values
  48464. state.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  48465. state.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  48466. state.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  48467. state.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  48468. state.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  48469. // Generate mipmaps only when copying level 0
  48470. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  48471. gl.generateMipmap( glTextureType );
  48472. }
  48473. state.unbindTexture();
  48474. }
  48475. /**
  48476. * Copies the current bound framebuffer to the given texture.
  48477. *
  48478. * @param {Texture} texture - The destination texture.
  48479. * @param {RenderContext} renderContext - The render context.
  48480. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  48481. */
  48482. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  48483. const { gl } = this;
  48484. const { state } = this.backend;
  48485. const { textureGPU } = this.backend.get( texture );
  48486. const { x, y, z: width, w: height } = rectangle;
  48487. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  48488. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  48489. if ( requireDrawFrameBuffer ) {
  48490. const partial = ( x !== 0 || y !== 0 );
  48491. let mask;
  48492. let attachment;
  48493. if ( texture.isDepthTexture === true ) {
  48494. mask = gl.DEPTH_BUFFER_BIT;
  48495. attachment = gl.DEPTH_ATTACHMENT;
  48496. if ( renderContext.stencil ) {
  48497. mask |= gl.STENCIL_BUFFER_BIT;
  48498. }
  48499. } else {
  48500. mask = gl.COLOR_BUFFER_BIT;
  48501. attachment = gl.COLOR_ATTACHMENT0;
  48502. }
  48503. if ( partial ) {
  48504. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  48505. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  48506. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48507. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48508. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  48509. const flippedY = srcHeight - y - height;
  48510. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  48511. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  48512. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  48513. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  48514. state.unbindTexture();
  48515. } else {
  48516. const fb = gl.createFramebuffer();
  48517. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48518. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  48519. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  48520. gl.deleteFramebuffer( fb );
  48521. }
  48522. } else {
  48523. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  48524. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  48525. state.unbindTexture();
  48526. }
  48527. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  48528. this.backend._setFramebuffer( renderContext );
  48529. }
  48530. /**
  48531. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  48532. *
  48533. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  48534. * @param {RenderContext} renderContext - The render context.
  48535. * @param {number} samples - The MSAA sample count.
  48536. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  48537. */
  48538. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  48539. const { gl } = this;
  48540. const renderTarget = renderContext.renderTarget;
  48541. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  48542. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  48543. if ( depthBuffer && ! stencilBuffer ) {
  48544. let glInternalFormat = gl.DEPTH_COMPONENT24;
  48545. if ( useMultisampledRTT === true ) {
  48546. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48547. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  48548. } else if ( samples > 0 ) {
  48549. if ( depthTexture && depthTexture.isDepthTexture ) {
  48550. if ( depthTexture.type === gl.FLOAT ) {
  48551. glInternalFormat = gl.DEPTH_COMPONENT32F;
  48552. }
  48553. }
  48554. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  48555. } else {
  48556. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  48557. }
  48558. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  48559. } else if ( depthBuffer && stencilBuffer ) {
  48560. if ( samples > 0 ) {
  48561. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  48562. } else {
  48563. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  48564. }
  48565. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  48566. }
  48567. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  48568. }
  48569. /**
  48570. * Returns texture data as a typed array.
  48571. *
  48572. * @async
  48573. * @param {Texture} texture - The texture to copy.
  48574. * @param {number} x - The x coordinate of the copy origin.
  48575. * @param {number} y - The y coordinate of the copy origin.
  48576. * @param {number} width - The width of the copy.
  48577. * @param {number} height - The height of the copy.
  48578. * @param {number} faceIndex - The face index.
  48579. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  48580. */
  48581. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  48582. const { backend, gl } = this;
  48583. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  48584. const fb = gl.createFramebuffer();
  48585. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  48586. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  48587. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  48588. const typedArrayType = this._getTypedArrayType( glType );
  48589. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  48590. const elementCount = width * height;
  48591. const byteLength = elementCount * bytesPerTexel;
  48592. const buffer = gl.createBuffer();
  48593. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  48594. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  48595. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  48596. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  48597. await backend.utils._clientWaitAsync();
  48598. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  48599. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  48600. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  48601. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  48602. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  48603. gl.deleteFramebuffer( fb );
  48604. return dstBuffer;
  48605. }
  48606. /**
  48607. * Returns the corresponding typed array type for the given WebGL data type.
  48608. *
  48609. * @private
  48610. * @param {GLenum} glType - The WebGL data type.
  48611. * @return {TypedArray.constructor} The typed array type.
  48612. */
  48613. _getTypedArrayType( glType ) {
  48614. const { gl } = this;
  48615. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  48616. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  48617. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  48618. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  48619. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  48620. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  48621. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  48622. if ( glType === gl.FLOAT ) return Float32Array;
  48623. throw new Error( `Unsupported WebGL type: ${glType}` );
  48624. }
  48625. /**
  48626. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  48627. *
  48628. * @private
  48629. * @param {GLenum} glType - The WebGL data type.
  48630. * @param {GLenum} glFormat - The WebGL texture format.
  48631. * @return {number} The bytes-per-texel.
  48632. */
  48633. _getBytesPerTexel( glType, glFormat ) {
  48634. const { gl } = this;
  48635. let bytesPerComponent = 0;
  48636. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  48637. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  48638. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  48639. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  48640. glType === gl.UNSIGNED_SHORT ||
  48641. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  48642. if ( glType === gl.UNSIGNED_INT ||
  48643. glType === gl.FLOAT ) bytesPerComponent = 4;
  48644. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  48645. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  48646. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  48647. }
  48648. /**
  48649. * Frees the internal resources.
  48650. */
  48651. dispose() {
  48652. const { gl } = this;
  48653. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  48654. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  48655. }
  48656. }
  48657. function getImage( source ) {
  48658. if ( source.isDataTexture ) {
  48659. return source.image.data;
  48660. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  48661. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  48662. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  48663. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  48664. return source;
  48665. }
  48666. return source.data;
  48667. }
  48668. /**
  48669. * A WebGL 2 backend utility module for managing extensions.
  48670. *
  48671. * @private
  48672. */
  48673. class WebGLExtensions {
  48674. /**
  48675. * Constructs a new utility object.
  48676. *
  48677. * @param {WebGLBackend} backend - The WebGL 2 backend.
  48678. */
  48679. constructor( backend ) {
  48680. /**
  48681. * A reference to the WebGL 2 backend.
  48682. *
  48683. * @type {WebGLBackend}
  48684. */
  48685. this.backend = backend;
  48686. /**
  48687. * A reference to the rendering context.
  48688. *
  48689. * @type {WebGL2RenderingContext}
  48690. */
  48691. this.gl = this.backend.gl;
  48692. /**
  48693. * A list with all the supported WebGL extensions.
  48694. *
  48695. * @type {Array<string>}
  48696. */
  48697. this.availableExtensions = this.gl.getSupportedExtensions();
  48698. /**
  48699. * A dictionary with requested WebGL extensions.
  48700. * The key is the name of the extension, the value
  48701. * the requested extension object.
  48702. *
  48703. * @type {Object<string,Object>}
  48704. */
  48705. this.extensions = {};
  48706. }
  48707. /**
  48708. * Returns the extension object for the given extension name.
  48709. *
  48710. * @param {string} name - The extension name.
  48711. * @return {Object} The extension object.
  48712. */
  48713. get( name ) {
  48714. let extension = this.extensions[ name ];
  48715. if ( extension === undefined ) {
  48716. extension = this.gl.getExtension( name );
  48717. this.extensions[ name ] = extension;
  48718. }
  48719. return extension;
  48720. }
  48721. /**
  48722. * Returns `true` if the requested extension is available.
  48723. *
  48724. * @param {string} name - The extension name.
  48725. * @return {boolean} Whether the given extension is available or not.
  48726. */
  48727. has( name ) {
  48728. return this.availableExtensions.includes( name );
  48729. }
  48730. }
  48731. /**
  48732. * A WebGL 2 backend utility module for managing the device's capabilities.
  48733. *
  48734. * @private
  48735. */
  48736. class WebGLCapabilities {
  48737. /**
  48738. * Constructs a new utility object.
  48739. *
  48740. * @param {WebGLBackend} backend - The WebGL 2 backend.
  48741. */
  48742. constructor( backend ) {
  48743. /**
  48744. * A reference to the WebGL 2 backend.
  48745. *
  48746. * @type {WebGLBackend}
  48747. */
  48748. this.backend = backend;
  48749. /**
  48750. * This value holds the cached max anisotropy value.
  48751. *
  48752. * @type {?number}
  48753. * @default null
  48754. */
  48755. this.maxAnisotropy = null;
  48756. /**
  48757. * This value holds the cached max uniform block size value.
  48758. *
  48759. * @type {?number}
  48760. * @default null
  48761. */
  48762. this.maxUniformBlockSize = null;
  48763. }
  48764. /**
  48765. * Returns the maximum anisotropy texture filtering value. This value
  48766. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  48767. * WebGL extension.
  48768. *
  48769. * @return {number} The maximum anisotropy texture filtering value.
  48770. */
  48771. getMaxAnisotropy() {
  48772. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  48773. const gl = this.backend.gl;
  48774. const extensions = this.backend.extensions;
  48775. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  48776. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  48777. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  48778. } else {
  48779. this.maxAnisotropy = 0;
  48780. }
  48781. return this.maxAnisotropy;
  48782. }
  48783. /**
  48784. * Returns the maximum number of bytes available for uniform buffers.
  48785. *
  48786. * @return {number} The maximum number of bytes available for uniform buffers.
  48787. */
  48788. getUniformBufferLimit() {
  48789. if ( this.maxUniformBlockSize !== null ) return this.maxUniformBlockSize;
  48790. const gl = this.backend.gl;
  48791. this.maxUniformBlockSize = gl.getParameter( gl.MAX_UNIFORM_BLOCK_SIZE );
  48792. return this.maxUniformBlockSize;
  48793. }
  48794. }
  48795. const GLFeatureName = {
  48796. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  48797. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  48798. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  48799. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  48800. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  48801. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  48802. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  48803. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  48804. 'OVR_multiview2': 'OVR_multiview2'
  48805. };
  48806. class WebGLBufferRenderer {
  48807. constructor( backend ) {
  48808. this.gl = backend.gl;
  48809. this.extensions = backend.extensions;
  48810. this.info = backend.renderer.info;
  48811. this.mode = null;
  48812. this.index = 0;
  48813. this.type = null;
  48814. this.object = null;
  48815. }
  48816. render( start, count ) {
  48817. const { gl, mode, object, type, info, index } = this;
  48818. if ( index !== 0 ) {
  48819. gl.drawElements( mode, count, type, start );
  48820. } else {
  48821. gl.drawArrays( mode, start, count );
  48822. }
  48823. info.update( object, count, 1 );
  48824. }
  48825. renderInstances( start, count, primcount ) {
  48826. const { gl, mode, type, index, object, info } = this;
  48827. if ( primcount === 0 ) return;
  48828. if ( index !== 0 ) {
  48829. gl.drawElementsInstanced( mode, count, type, start, primcount );
  48830. } else {
  48831. gl.drawArraysInstanced( mode, start, count, primcount );
  48832. }
  48833. info.update( object, count, primcount );
  48834. }
  48835. renderMultiDraw( starts, counts, drawCount ) {
  48836. const { extensions, mode, object, info } = this;
  48837. if ( drawCount === 0 ) return;
  48838. const extension = extensions.get( 'WEBGL_multi_draw' );
  48839. if ( extension === null ) {
  48840. for ( let i = 0; i < drawCount; i ++ ) {
  48841. this.render( starts[ i ], counts[ i ] );
  48842. }
  48843. } else {
  48844. if ( this.index !== 0 ) {
  48845. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  48846. } else {
  48847. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  48848. }
  48849. let elementCount = 0;
  48850. for ( let i = 0; i < drawCount; i ++ ) {
  48851. elementCount += counts[ i ];
  48852. }
  48853. info.update( object, elementCount, 1 );
  48854. }
  48855. }
  48856. //
  48857. }
  48858. /**
  48859. * Abstract base class of a timestamp query pool.
  48860. *
  48861. * @abstract
  48862. */
  48863. class TimestampQueryPool {
  48864. /**
  48865. * Creates a new timestamp query pool.
  48866. *
  48867. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  48868. */
  48869. constructor( maxQueries = 256 ) {
  48870. /**
  48871. * Whether to track timestamps or not.
  48872. *
  48873. * @type {boolean}
  48874. * @default true
  48875. */
  48876. this.trackTimestamp = true;
  48877. /**
  48878. * Maximum number of queries this pool can hold.
  48879. *
  48880. * @type {number}
  48881. * @default 256
  48882. */
  48883. this.maxQueries = maxQueries;
  48884. /**
  48885. * How many queries allocated so far.
  48886. *
  48887. * @type {number}
  48888. * @default 0
  48889. */
  48890. this.currentQueryIndex = 0;
  48891. /**
  48892. * Tracks offsets for different contexts.
  48893. *
  48894. * @type {Map<string, number>}
  48895. */
  48896. this.queryOffsets = new Map();
  48897. /**
  48898. * Whether the pool has been disposed or not.
  48899. *
  48900. * @type {boolean}
  48901. * @default false
  48902. */
  48903. this.isDisposed = false;
  48904. /**
  48905. * The total frame duration until the next update.
  48906. *
  48907. * @type {number}
  48908. * @default 0
  48909. */
  48910. this.lastValue = 0;
  48911. /**
  48912. * Stores all timestamp frames.
  48913. *
  48914. * @type {Array<number>}
  48915. */
  48916. this.frames = [];
  48917. /**
  48918. * This property is used to avoid multiple concurrent resolve operations.
  48919. * The WebGL backend uses it as a boolean flag. In context of WebGPU, it holds
  48920. * the promise of the current resolve operation.
  48921. *
  48922. * @type {boolean|Promise<number>}
  48923. * @default false
  48924. */
  48925. this.pendingResolve = false;
  48926. /**
  48927. * Stores the latest timestamp for each render context.
  48928. *
  48929. * @type {Map<string, number>}
  48930. */
  48931. this.timestamps = new Map();
  48932. }
  48933. /**
  48934. * Returns all timestamp frames.
  48935. *
  48936. * @return {Array<number>} The timestamp frames.
  48937. */
  48938. getTimestampFrames() {
  48939. return this.frames;
  48940. }
  48941. /**
  48942. * Returns the timestamp for a given render context.
  48943. *
  48944. * @param {string} uid - A unique identifier for the render context.
  48945. * @return {?number} The timestamp, or undefined if not available.
  48946. */
  48947. getTimestamp( uid ) {
  48948. let timestamp = this.timestamps.get( uid );
  48949. if ( timestamp === undefined ) {
  48950. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  48951. timestamp = 0;
  48952. }
  48953. return timestamp;
  48954. }
  48955. /**
  48956. * Returns whether a timestamp is available for a given render context.
  48957. *
  48958. * @param {string} uid - A unique identifier for the render context.
  48959. * @return {boolean} True if a timestamp is available, false otherwise.
  48960. */
  48961. hasTimestamp( uid ) {
  48962. return this.timestamps.has( uid );
  48963. }
  48964. /**
  48965. * Allocate queries for a specific uid.
  48966. *
  48967. * @abstract
  48968. * @param {string} uid - A unique identifier for the render context.
  48969. * @param {number} frameId - The current frame identifier.
  48970. * @returns {?number}
  48971. */
  48972. allocateQueriesForContext( /* uid, frameId */ ) {}
  48973. /**
  48974. * Resolve all timestamps and return data (or process them).
  48975. *
  48976. * @abstract
  48977. * @async
  48978. * @returns {Promise<number>|number} The resolved timestamp value.
  48979. */
  48980. async resolveQueriesAsync() {}
  48981. /**
  48982. * Dispose of the query pool.
  48983. *
  48984. * @abstract
  48985. */
  48986. dispose() {}
  48987. }
  48988. /**
  48989. * Manages a pool of WebGL timestamp queries for performance measurement.
  48990. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  48991. *
  48992. * @augments TimestampQueryPool
  48993. */
  48994. class WebGLTimestampQueryPool extends TimestampQueryPool {
  48995. /**
  48996. * Creates a new WebGL timestamp query pool.
  48997. *
  48998. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  48999. * @param {string} type - The type identifier for this query pool.
  49000. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  49001. */
  49002. constructor( gl, type, maxQueries = 2048 ) {
  49003. super( maxQueries );
  49004. this.gl = gl;
  49005. this.type = type;
  49006. // Check for timer query extensions
  49007. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  49008. gl.getExtension( 'EXT_disjoint_timer_query' );
  49009. if ( ! this.ext ) {
  49010. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  49011. this.trackTimestamp = false;
  49012. return;
  49013. }
  49014. // Create query objects
  49015. this.queries = [];
  49016. for ( let i = 0; i < this.maxQueries; i ++ ) {
  49017. this.queries.push( gl.createQuery() );
  49018. }
  49019. this.activeQuery = null;
  49020. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  49021. }
  49022. /**
  49023. * Allocates a pair of queries for a given render context.
  49024. *
  49025. * @param {string} uid - A unique identifier for the render context.
  49026. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  49027. */
  49028. allocateQueriesForContext( uid ) {
  49029. if ( ! this.trackTimestamp ) return null;
  49030. // Check if we have enough space for a new query pair
  49031. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  49032. warnOnce( `WebGLTimestampQueryPool [${ 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() } ).` );
  49033. return null;
  49034. }
  49035. const baseOffset = this.currentQueryIndex;
  49036. this.currentQueryIndex += 2;
  49037. // Initialize query states
  49038. this.queryStates.set( baseOffset, 'inactive' );
  49039. this.queryOffsets.set( uid, baseOffset );
  49040. return baseOffset;
  49041. }
  49042. /**
  49043. * Begins a timestamp query for the specified render context.
  49044. *
  49045. * @param {string} uid - A unique identifier for the render context.
  49046. */
  49047. beginQuery( uid ) {
  49048. if ( ! this.trackTimestamp || this.isDisposed ) {
  49049. return;
  49050. }
  49051. const baseOffset = this.queryOffsets.get( uid );
  49052. if ( baseOffset == null ) {
  49053. return;
  49054. }
  49055. // Don't start a new query if there's an active one
  49056. if ( this.activeQuery !== null ) {
  49057. return;
  49058. }
  49059. const query = this.queries[ baseOffset ];
  49060. if ( ! query ) {
  49061. return;
  49062. }
  49063. try {
  49064. // Only begin if query is inactive
  49065. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  49066. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  49067. this.activeQuery = baseOffset;
  49068. this.queryStates.set( baseOffset, 'started' );
  49069. }
  49070. } catch ( e ) {
  49071. error( 'Error in beginQuery:', e );
  49072. this.activeQuery = null;
  49073. this.queryStates.set( baseOffset, 'inactive' );
  49074. }
  49075. }
  49076. /**
  49077. * Ends the active timestamp query for the specified render context.
  49078. *
  49079. * @param {string} uid - A unique identifier for the render context.
  49080. */
  49081. endQuery( uid ) {
  49082. if ( ! this.trackTimestamp || this.isDisposed ) {
  49083. return;
  49084. }
  49085. const baseOffset = this.queryOffsets.get( uid );
  49086. if ( baseOffset == null ) {
  49087. return;
  49088. }
  49089. // Only end if this is the active query
  49090. if ( this.activeQuery !== baseOffset ) {
  49091. return;
  49092. }
  49093. try {
  49094. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  49095. this.queryStates.set( baseOffset, 'ended' );
  49096. this.activeQuery = null;
  49097. } catch ( e ) {
  49098. error( 'Error in endQuery:', e );
  49099. // Reset state on error
  49100. this.queryStates.set( baseOffset, 'inactive' );
  49101. this.activeQuery = null;
  49102. }
  49103. }
  49104. /**
  49105. * Asynchronously resolves all completed queries and returns the total duration.
  49106. *
  49107. * @async
  49108. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  49109. */
  49110. async resolveQueriesAsync() {
  49111. if ( ! this.trackTimestamp || this.pendingResolve ) {
  49112. return this.lastValue;
  49113. }
  49114. this.pendingResolve = true;
  49115. try {
  49116. // Wait for all ended queries to complete
  49117. const resolvePromises = new Map();
  49118. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  49119. const state = this.queryStates.get( baseOffset );
  49120. if ( state === 'ended' ) {
  49121. const query = this.queries[ baseOffset ];
  49122. resolvePromises.set( uid, this.resolveQuery( query ) );
  49123. }
  49124. }
  49125. if ( resolvePromises.size === 0 ) {
  49126. return this.lastValue;
  49127. }
  49128. //
  49129. const framesDuration = {};
  49130. const frames = [];
  49131. for ( const [ uid, promise ] of resolvePromises ) {
  49132. const match = uid.match( /^(.*):f(\d+)$/ );
  49133. const frame = parseInt( match[ 2 ] );
  49134. if ( frames.includes( frame ) === false ) {
  49135. frames.push( frame );
  49136. }
  49137. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  49138. const duration = await promise;
  49139. this.timestamps.set( uid, duration );
  49140. framesDuration[ frame ] += duration;
  49141. }
  49142. // Return the total duration of the last frame
  49143. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  49144. // Store the last valid result
  49145. this.lastValue = totalDuration;
  49146. this.frames = frames;
  49147. // Reset states
  49148. this.currentQueryIndex = 0;
  49149. this.queryOffsets.clear();
  49150. this.queryStates.clear();
  49151. this.activeQuery = null;
  49152. return totalDuration;
  49153. } catch ( e ) {
  49154. error( 'Error resolving queries:', e );
  49155. return this.lastValue;
  49156. } finally {
  49157. this.pendingResolve = false;
  49158. }
  49159. }
  49160. /**
  49161. * Resolves a single query, checking for completion and disjoint operation.
  49162. *
  49163. * @async
  49164. * @param {WebGLQuery} query - The query object to resolve.
  49165. * @returns {Promise<number>} The elapsed time in milliseconds.
  49166. */
  49167. async resolveQuery( query ) {
  49168. return new Promise( ( resolve ) => {
  49169. if ( this.isDisposed ) {
  49170. resolve( this.lastValue );
  49171. return;
  49172. }
  49173. let timeoutId;
  49174. let isResolved = false;
  49175. const cleanup = () => {
  49176. if ( timeoutId ) {
  49177. clearTimeout( timeoutId );
  49178. timeoutId = null;
  49179. }
  49180. };
  49181. const finalizeResolution = ( value ) => {
  49182. if ( ! isResolved ) {
  49183. isResolved = true;
  49184. cleanup();
  49185. resolve( value );
  49186. }
  49187. };
  49188. const checkQuery = () => {
  49189. if ( this.isDisposed ) {
  49190. finalizeResolution( this.lastValue );
  49191. return;
  49192. }
  49193. try {
  49194. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  49195. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  49196. if ( disjoint ) {
  49197. finalizeResolution( this.lastValue );
  49198. return;
  49199. }
  49200. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  49201. if ( ! available ) {
  49202. timeoutId = setTimeout( checkQuery, 1 );
  49203. return;
  49204. }
  49205. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  49206. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  49207. } catch ( e ) {
  49208. error( 'Error checking query:', e );
  49209. resolve( this.lastValue );
  49210. }
  49211. };
  49212. checkQuery();
  49213. } );
  49214. }
  49215. /**
  49216. * Releases all resources held by this query pool.
  49217. * This includes deleting all query objects and clearing internal state.
  49218. */
  49219. dispose() {
  49220. if ( this.isDisposed ) {
  49221. return;
  49222. }
  49223. this.isDisposed = true;
  49224. if ( ! this.trackTimestamp ) return;
  49225. for ( const query of this.queries ) {
  49226. this.gl.deleteQuery( query );
  49227. }
  49228. this.queries = [];
  49229. this.queryStates.clear();
  49230. this.queryOffsets.clear();
  49231. this.lastValue = 0;
  49232. this.activeQuery = null;
  49233. }
  49234. }
  49235. /**
  49236. * A backend implementation targeting WebGL 2.
  49237. *
  49238. * @private
  49239. * @augments Backend
  49240. */
  49241. class WebGLBackend extends Backend {
  49242. /**
  49243. * WebGLBackend options.
  49244. *
  49245. * @typedef {Object} WebGLBackend~Options
  49246. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  49247. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  49248. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  49249. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  49250. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  49251. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  49252. * @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.
  49253. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  49254. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  49255. */
  49256. /**
  49257. * Constructs a new WebGPU backend.
  49258. *
  49259. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  49260. */
  49261. constructor( parameters = {} ) {
  49262. super( parameters );
  49263. /**
  49264. * This flag can be used for type testing.
  49265. *
  49266. * @type {boolean}
  49267. * @readonly
  49268. * @default true
  49269. */
  49270. this.isWebGLBackend = true;
  49271. /**
  49272. * A reference to a backend module holding shader attribute-related
  49273. * utility functions.
  49274. *
  49275. * @type {?WebGLAttributeUtils}
  49276. * @default null
  49277. */
  49278. this.attributeUtils = null;
  49279. /**
  49280. * A reference to a backend module holding extension-related
  49281. * utility functions.
  49282. *
  49283. * @type {?WebGLExtensions}
  49284. * @default null
  49285. */
  49286. this.extensions = null;
  49287. /**
  49288. * A reference to a backend module holding capability-related
  49289. * utility functions.
  49290. *
  49291. * @type {?WebGLCapabilities}
  49292. * @default null
  49293. */
  49294. this.capabilities = null;
  49295. /**
  49296. * A reference to a backend module holding texture-related
  49297. * utility functions.
  49298. *
  49299. * @type {?WebGLTextureUtils}
  49300. * @default null
  49301. */
  49302. this.textureUtils = null;
  49303. /**
  49304. * A reference to a backend module holding renderer-related
  49305. * utility functions.
  49306. *
  49307. * @type {?WebGLBufferRenderer}
  49308. * @default null
  49309. */
  49310. this.bufferRenderer = null;
  49311. /**
  49312. * A reference to the rendering context.
  49313. *
  49314. * @type {?WebGL2RenderingContext}
  49315. * @default null
  49316. */
  49317. this.gl = null;
  49318. /**
  49319. * A reference to a backend module holding state-related
  49320. * utility functions.
  49321. *
  49322. * @type {?WebGLState}
  49323. * @default null
  49324. */
  49325. this.state = null;
  49326. /**
  49327. * A reference to a backend module holding common
  49328. * utility functions.
  49329. *
  49330. * @type {?WebGLUtils}
  49331. * @default null
  49332. */
  49333. this.utils = null;
  49334. /**
  49335. * Dictionary for caching VAOs.
  49336. *
  49337. * @type {Object<string,WebGLVertexArrayObject>}
  49338. */
  49339. this.vaoCache = {};
  49340. /**
  49341. * Dictionary for caching transform feedback objects.
  49342. *
  49343. * @type {Object<string,WebGLTransformFeedback>}
  49344. */
  49345. this.transformFeedbackCache = {};
  49346. /**
  49347. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  49348. * Only relevant when using compute shaders.
  49349. *
  49350. * @type {boolean}
  49351. * @default false
  49352. */
  49353. this.discard = false;
  49354. /**
  49355. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  49356. * device does not support the extension.
  49357. *
  49358. * @type {?EXTDisjointTimerQueryWebGL2}
  49359. * @default null
  49360. */
  49361. this.disjoint = null;
  49362. /**
  49363. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  49364. * device does not support the extension.
  49365. *
  49366. * @type {?KHRParallelShaderCompile}
  49367. * @default null
  49368. */
  49369. this.parallel = null;
  49370. /**
  49371. * A reference to the current render context.
  49372. *
  49373. * @private
  49374. * @type {RenderContext}
  49375. * @default null
  49376. */
  49377. this._currentContext = null;
  49378. /**
  49379. * A unique collection of bindings.
  49380. *
  49381. * @private
  49382. * @type {WeakSet<Array<BindGroup>>}
  49383. */
  49384. this._knownBindings = new WeakSet();
  49385. /**
  49386. * Whether the device supports framebuffers invalidation or not.
  49387. *
  49388. * @private
  49389. * @type {boolean}
  49390. */
  49391. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  49392. /**
  49393. * The target framebuffer when rendering with
  49394. * the WebXR device API.
  49395. *
  49396. * @private
  49397. * @type {?WebGLFramebuffer}
  49398. * @default null
  49399. */
  49400. this._xrFramebuffer = null;
  49401. }
  49402. /**
  49403. * Initializes the backend so it is ready for usage.
  49404. *
  49405. * @param {Renderer} renderer - The renderer.
  49406. */
  49407. init( renderer ) {
  49408. super.init( renderer );
  49409. //
  49410. const parameters = this.parameters;
  49411. const contextAttributes = {
  49412. antialias: renderer.currentSamples > 0,
  49413. alpha: true, // always true for performance reasons
  49414. depth: renderer.depth,
  49415. stencil: renderer.stencil
  49416. };
  49417. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  49418. function onContextLost( event ) {
  49419. event.preventDefault();
  49420. const contextLossInfo = {
  49421. api: 'WebGL',
  49422. message: event.statusMessage || 'Unknown reason',
  49423. reason: null,
  49424. originalEvent: event
  49425. };
  49426. renderer.onDeviceLost( contextLossInfo );
  49427. }
  49428. this._onContextLost = onContextLost;
  49429. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  49430. this.gl = glContext;
  49431. this.extensions = new WebGLExtensions( this );
  49432. this.capabilities = new WebGLCapabilities( this );
  49433. this.attributeUtils = new WebGLAttributeUtils( this );
  49434. this.textureUtils = new WebGLTextureUtils( this );
  49435. this.bufferRenderer = new WebGLBufferRenderer( this );
  49436. this.state = new WebGLState( this );
  49437. this.utils = new WebGLUtils( this );
  49438. this.extensions.get( 'EXT_color_buffer_float' );
  49439. this.extensions.get( 'WEBGL_clip_cull_distance' );
  49440. this.extensions.get( 'OES_texture_float_linear' );
  49441. this.extensions.get( 'EXT_color_buffer_half_float' );
  49442. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  49443. this.extensions.get( 'WEBGL_render_shared_exponent' );
  49444. this.extensions.get( 'WEBGL_multi_draw' );
  49445. this.extensions.get( 'OVR_multiview2' );
  49446. this.extensions.get( 'EXT_clip_control' );
  49447. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  49448. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  49449. this.drawBuffersIndexedExt = this.extensions.get( 'OES_draw_buffers_indexed' );
  49450. if ( parameters.reversedDepthBuffer ) {
  49451. if ( this.extensions.has( 'EXT_clip_control' ) ) {
  49452. renderer.reversedDepthBuffer = true;
  49453. } else {
  49454. warn( 'WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.' );
  49455. renderer.reversedDepthBuffer = false;
  49456. }
  49457. }
  49458. if ( renderer.reversedDepthBuffer ) {
  49459. this.state.setReversedDepth( true );
  49460. }
  49461. }
  49462. /**
  49463. * The coordinate system of the backend.
  49464. *
  49465. * @type {number}
  49466. * @readonly
  49467. */
  49468. get coordinateSystem() {
  49469. return WebGLCoordinateSystem;
  49470. }
  49471. /**
  49472. * This method performs a readback operation by moving buffer data from
  49473. * a storage buffer attribute from the GPU to the CPU.
  49474. *
  49475. * @async
  49476. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  49477. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  49478. */
  49479. async getArrayBufferAsync( attribute ) {
  49480. return await this.attributeUtils.getArrayBufferAsync( attribute );
  49481. }
  49482. /**
  49483. * Ensures the backend is XR compatible.
  49484. *
  49485. * @async
  49486. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  49487. */
  49488. async makeXRCompatible() {
  49489. const attributes = this.gl.getContextAttributes();
  49490. if ( attributes.xrCompatible !== true ) {
  49491. await this.gl.makeXRCompatible();
  49492. }
  49493. }
  49494. /**
  49495. * Sets the XR rendering destination.
  49496. *
  49497. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  49498. */
  49499. setXRTarget( xrFramebuffer ) {
  49500. this._xrFramebuffer = xrFramebuffer;
  49501. }
  49502. /**
  49503. * Configures the given XR render target with external textures.
  49504. *
  49505. * This method is only relevant when using the WebXR Layers API.
  49506. *
  49507. * @param {XRRenderTarget} renderTarget - The XR render target.
  49508. * @param {WebGLTexture} colorTexture - A native color texture.
  49509. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  49510. */
  49511. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  49512. const gl = this.gl;
  49513. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  49514. if ( depthTexture !== null ) {
  49515. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  49516. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  49517. // The multisample_render_to_texture extension doesn't work properly if there
  49518. // are midframe flushes and an external depth texture.
  49519. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  49520. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  49521. }
  49522. renderTarget._autoAllocateDepthBuffer = false;
  49523. }
  49524. }
  49525. /**
  49526. * Inits a time stamp query for the given render context.
  49527. *
  49528. * @param {string} type - The type of the timestamp query.
  49529. * @param {string} uid - A unique identifier for the timestamp query.
  49530. */
  49531. initTimestampQuery( type, uid ) {
  49532. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  49533. if ( ! this.timestampQueryPool[ type ] ) {
  49534. // TODO: Variable maxQueries?
  49535. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  49536. }
  49537. const timestampQueryPool = this.timestampQueryPool[ type ];
  49538. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  49539. if ( baseOffset !== null ) {
  49540. timestampQueryPool.beginQuery( uid );
  49541. }
  49542. }
  49543. // timestamp utils
  49544. /**
  49545. * Prepares the timestamp buffer.
  49546. *
  49547. * @param {string} type - The type of the timestamp query.
  49548. * @param {string} uid - A unique identifier for the timestamp query.
  49549. */
  49550. prepareTimestampBuffer( type, uid ) {
  49551. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  49552. const timestampQueryPool = this.timestampQueryPool[ type ];
  49553. timestampQueryPool.endQuery( uid );
  49554. }
  49555. /**
  49556. * Returns the backend's rendering context.
  49557. *
  49558. * @return {WebGL2RenderingContext} The rendering context.
  49559. */
  49560. getContext() {
  49561. return this.gl;
  49562. }
  49563. /**
  49564. * This method is executed at the beginning of a render call and prepares
  49565. * the WebGL state for upcoming render calls
  49566. *
  49567. * @param {RenderContext} renderContext - The render context.
  49568. */
  49569. beginRender( renderContext ) {
  49570. const { state } = this;
  49571. const renderContextData = this.get( renderContext );
  49572. //
  49573. if ( renderContext.viewport ) {
  49574. this.updateViewport( renderContext );
  49575. } else {
  49576. const { width, height } = this.getDrawingBufferSize();
  49577. state.viewport( 0, 0, width, height );
  49578. }
  49579. if ( renderContext.scissor ) {
  49580. this.updateScissor( renderContext );
  49581. } else {
  49582. const { width, height } = this.getDrawingBufferSize();
  49583. state.scissor( 0, 0, width, height );
  49584. }
  49585. //
  49586. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  49587. renderContextData.previousContext = this._currentContext;
  49588. this._currentContext = renderContext;
  49589. this._setFramebuffer( renderContext );
  49590. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  49591. const occlusionQueryCount = renderContext.occlusionQueryCount;
  49592. if ( occlusionQueryCount > 0 ) {
  49593. // Get a reference to the array of objects with queries. The renderContextData property
  49594. // can be changed by another render pass before the async reading of all previous queries complete
  49595. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  49596. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  49597. renderContextData.lastOcclusionObject = null;
  49598. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  49599. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  49600. renderContextData.occlusionQueryIndex = 0;
  49601. }
  49602. }
  49603. /**
  49604. * This method is executed at the end of a render call and finalizes work
  49605. * after draw calls.
  49606. *
  49607. * @param {RenderContext} renderContext - The render context.
  49608. */
  49609. finishRender( renderContext ) {
  49610. const { gl, state } = this;
  49611. const renderContextData = this.get( renderContext );
  49612. const previousContext = renderContextData.previousContext;
  49613. state.resetVertexState();
  49614. const occlusionQueryCount = renderContext.occlusionQueryCount;
  49615. if ( occlusionQueryCount > 0 ) {
  49616. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  49617. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  49618. }
  49619. this.resolveOccludedAsync( renderContext );
  49620. }
  49621. const textures = renderContext.textures;
  49622. if ( textures !== null ) {
  49623. for ( let i = 0; i < textures.length; i ++ ) {
  49624. const texture = textures[ i ];
  49625. if ( texture.generateMipmaps ) {
  49626. this.generateMipmaps( texture );
  49627. }
  49628. }
  49629. }
  49630. this._currentContext = previousContext;
  49631. this._resolveRenderTarget( renderContext );
  49632. if ( previousContext !== null ) {
  49633. this._setFramebuffer( previousContext );
  49634. if ( previousContext.viewport ) {
  49635. this.updateViewport( previousContext );
  49636. } else {
  49637. const { width, height } = this.getDrawingBufferSize();
  49638. state.viewport( 0, 0, width, height );
  49639. }
  49640. if ( previousContext.scissor ) {
  49641. this.updateScissor( previousContext );
  49642. } else {
  49643. const { width, height } = this.getDrawingBufferSize();
  49644. state.scissor( 0, 0, width, height );
  49645. }
  49646. }
  49647. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  49648. }
  49649. /**
  49650. * This method processes the result of occlusion queries and writes it
  49651. * into render context data.
  49652. *
  49653. * @async
  49654. * @param {RenderContext} renderContext - The render context.
  49655. */
  49656. resolveOccludedAsync( renderContext ) {
  49657. const renderContextData = this.get( renderContext );
  49658. // handle occlusion query results
  49659. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  49660. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  49661. const occluded = new WeakSet();
  49662. const { gl } = this;
  49663. renderContextData.currentOcclusionQueryObjects = null;
  49664. renderContextData.currentOcclusionQueries = null;
  49665. const check = () => {
  49666. let completed = 0;
  49667. // check all queries and requeue as appropriate
  49668. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  49669. const query = currentOcclusionQueries[ i ];
  49670. if ( query === null ) continue;
  49671. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  49672. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  49673. currentOcclusionQueries[ i ] = null;
  49674. gl.deleteQuery( query );
  49675. completed ++;
  49676. }
  49677. }
  49678. if ( completed < currentOcclusionQueries.length ) {
  49679. requestAnimationFrame( check );
  49680. } else {
  49681. renderContextData.occluded = occluded;
  49682. }
  49683. };
  49684. check();
  49685. }
  49686. }
  49687. /**
  49688. * Returns `true` if the given 3D object is fully occluded by other
  49689. * 3D objects in the scene.
  49690. *
  49691. * @param {RenderContext} renderContext - The render context.
  49692. * @param {Object3D} object - The 3D object to test.
  49693. * @return {boolean} Whether the 3D object is fully occluded or not.
  49694. */
  49695. isOccluded( renderContext, object ) {
  49696. const renderContextData = this.get( renderContext );
  49697. return renderContextData.occluded && renderContextData.occluded.has( object );
  49698. }
  49699. /**
  49700. * Updates the viewport with the values from the given render context.
  49701. *
  49702. * @param {RenderContext} renderContext - The render context.
  49703. */
  49704. updateViewport( renderContext ) {
  49705. const { state } = this;
  49706. const { x, y, width, height } = renderContext.viewportValue;
  49707. state.viewport( x, renderContext.height - height - y, width, height );
  49708. }
  49709. /**
  49710. * Updates the scissor with the values from the given render context.
  49711. *
  49712. * @param {RenderContext} renderContext - The render context.
  49713. */
  49714. updateScissor( renderContext ) {
  49715. const { state } = this;
  49716. const { x, y, width, height } = renderContext.scissorValue;
  49717. state.scissor( x, renderContext.height - height - y, width, height );
  49718. }
  49719. /**
  49720. * Defines the scissor test.
  49721. *
  49722. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  49723. */
  49724. setScissorTest( boolean ) {
  49725. const state = this.state;
  49726. state.setScissorTest( boolean );
  49727. }
  49728. /**
  49729. * Returns the clear color and alpha into a single
  49730. * color object.
  49731. *
  49732. * @return {Color4} The clear color.
  49733. */
  49734. getClearColor() {
  49735. const clearColor = super.getClearColor();
  49736. // Since the canvas is always created with alpha: true,
  49737. // WebGL must always premultiply the clear color.
  49738. clearColor.r *= clearColor.a;
  49739. clearColor.g *= clearColor.a;
  49740. clearColor.b *= clearColor.a;
  49741. return clearColor;
  49742. }
  49743. /**
  49744. * Performs a clear operation.
  49745. *
  49746. * @param {boolean} color - Whether the color buffer should be cleared or not.
  49747. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  49748. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  49749. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  49750. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  49751. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  49752. * or not. Only relevant for explicit clears.
  49753. */
  49754. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  49755. const { gl, renderer } = this;
  49756. if ( descriptor === null ) {
  49757. const clearColor = this.getClearColor();
  49758. descriptor = {
  49759. textures: null,
  49760. clearColorValue: clearColor
  49761. };
  49762. }
  49763. //
  49764. let clear = 0;
  49765. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  49766. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  49767. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  49768. if ( clear !== 0 ) {
  49769. let clearColor;
  49770. if ( descriptor.clearColorValue ) {
  49771. clearColor = descriptor.clearColorValue;
  49772. } else {
  49773. clearColor = this.getClearColor();
  49774. }
  49775. const clearDepth = renderer.getClearDepth();
  49776. const clearStencil = renderer.getClearStencil();
  49777. if ( depth ) this.state.setDepthMask( true );
  49778. if ( descriptor.textures === null ) {
  49779. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  49780. gl.clear( clear );
  49781. } else {
  49782. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  49783. if ( color ) {
  49784. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  49785. if ( i === 0 ) {
  49786. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  49787. } else {
  49788. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  49789. }
  49790. }
  49791. }
  49792. if ( depth && stencil ) {
  49793. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  49794. } else if ( depth ) {
  49795. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  49796. } else if ( stencil ) {
  49797. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  49798. }
  49799. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  49800. }
  49801. }
  49802. }
  49803. /**
  49804. * This method is executed at the beginning of a compute call and
  49805. * prepares the state for upcoming compute tasks.
  49806. *
  49807. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  49808. */
  49809. beginCompute( computeGroup ) {
  49810. const { state, gl } = this;
  49811. //
  49812. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  49813. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  49814. }
  49815. /**
  49816. * Executes a compute command for the given compute node.
  49817. *
  49818. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  49819. * @param {Node} computeNode - The compute node.
  49820. * @param {Array<BindGroup>} bindings - The bindings.
  49821. * @param {ComputePipeline} pipeline - The compute pipeline.
  49822. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  49823. */
  49824. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  49825. const { state, gl } = this;
  49826. if ( this.discard === false ) {
  49827. // required here to handle async behaviour of render.compute()
  49828. state.enable( gl.RASTERIZER_DISCARD );
  49829. this.discard = true;
  49830. }
  49831. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  49832. const vaoKey = this._getVaoKey( attributes );
  49833. const vaoGPU = this.vaoCache[ vaoKey ];
  49834. if ( vaoGPU === undefined ) {
  49835. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  49836. } else {
  49837. state.setVertexState( vaoGPU );
  49838. }
  49839. state.useProgram( programGPU );
  49840. this._bindUniforms( bindings );
  49841. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  49842. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  49843. gl.beginTransformFeedback( gl.POINTS );
  49844. count = ( count !== null ) ? count : computeNode.count;
  49845. if ( Array.isArray( count ) ) {
  49846. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  49847. count = count[ 0 ];
  49848. } else if ( count && typeof count === 'object' && count.isIndirectStorageBufferAttribute ) {
  49849. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute' );
  49850. count = computeNode.count;
  49851. }
  49852. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  49853. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  49854. } else {
  49855. gl.drawArrays( gl.POINTS, 0, count );
  49856. }
  49857. gl.endTransformFeedback();
  49858. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  49859. // switch active buffers
  49860. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  49861. const dualAttributeData = transformBuffers[ i ];
  49862. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  49863. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  49864. }
  49865. dualAttributeData.switchBuffers();
  49866. }
  49867. }
  49868. /**
  49869. * This method is executed at the end of a compute call and
  49870. * finalizes work after compute tasks.
  49871. *
  49872. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  49873. */
  49874. finishCompute( computeGroup ) {
  49875. const { state, gl } = this;
  49876. this.discard = false;
  49877. state.disable( gl.RASTERIZER_DISCARD );
  49878. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  49879. if ( this._currentContext ) {
  49880. this._setFramebuffer( this._currentContext );
  49881. }
  49882. }
  49883. /**
  49884. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  49885. *
  49886. * @param {RenderContext} renderContext - The render context.
  49887. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  49888. *
  49889. * @private
  49890. */
  49891. _isRenderCameraDepthArray( renderContext ) {
  49892. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  49893. }
  49894. /**
  49895. * Internal draw function.
  49896. *
  49897. * @private
  49898. * @param {Object3D} object - The object to render.
  49899. * @param {WebGLBufferRenderer} renderer - The internal renderer.
  49900. * @param {number} firstVertex - The first vertex to render.
  49901. * @param {number} vertexCount - The vertex count.
  49902. * @param {number} instanceCount - The intance count.
  49903. * @param {WebGLProgram} programGPU - The raw WebGL shader program.
  49904. */
  49905. _draw( object, renderer, firstVertex, vertexCount, instanceCount, programGPU ) {
  49906. if ( object.isBatchedMesh ) {
  49907. if ( this.hasFeature( 'WEBGL_multi_draw' ) === false ) {
  49908. const { gl } = this;
  49909. const drawIdLocation = gl.getUniformLocation( programGPU, 'nodeUniformDrawId' );
  49910. const starts = object._multiDrawStarts;
  49911. const counts = object._multiDrawCounts;
  49912. const drawCount = object._multiDrawCount;
  49913. for ( let i = 0; i < drawCount; i ++ ) {
  49914. gl.uniform1ui( drawIdLocation, i );
  49915. renderer.render( starts[ i ], counts[ i ] );
  49916. }
  49917. } else {
  49918. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  49919. }
  49920. } else if ( instanceCount > 1 ) {
  49921. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  49922. } else {
  49923. renderer.render( firstVertex, vertexCount );
  49924. }
  49925. }
  49926. /**
  49927. * Executes a draw command for the given render object.
  49928. *
  49929. * @param {RenderObject} renderObject - The render object to draw.
  49930. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  49931. */
  49932. draw( renderObject/*, info*/ ) {
  49933. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  49934. const { programGPU } = this.get( pipeline );
  49935. const { gl, state } = this;
  49936. const contextData = this.get( context );
  49937. const drawParams = renderObject.getDrawParameters();
  49938. if ( drawParams === null ) return;
  49939. //
  49940. this._bindUniforms( renderObject.getBindings() );
  49941. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  49942. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  49943. if ( context.mrt !== null && context.textures !== null ) {
  49944. state.setMRTBlending( context.textures, context.mrt, material );
  49945. }
  49946. state.useProgram( programGPU );
  49947. // vertex state
  49948. const attributes = renderObject.getAttributes();
  49949. const attributesData = this.get( attributes );
  49950. let vaoGPU = attributesData.vaoGPU;
  49951. if ( vaoGPU === undefined ) {
  49952. const vaoKey = this._getVaoKey( attributes );
  49953. vaoGPU = this.vaoCache[ vaoKey ];
  49954. if ( vaoGPU === undefined ) {
  49955. vaoGPU = this._createVao( attributes );
  49956. this.vaoCache[ vaoKey ] = vaoGPU;
  49957. attributesData.vaoGPU = vaoGPU;
  49958. }
  49959. }
  49960. const index = renderObject.getIndex();
  49961. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  49962. state.setVertexState( vaoGPU, indexGPU );
  49963. //
  49964. const lastObject = contextData.lastOcclusionObject;
  49965. if ( lastObject !== object && lastObject !== undefined ) {
  49966. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  49967. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  49968. contextData.occlusionQueryIndex ++;
  49969. }
  49970. if ( object.occlusionTest === true ) {
  49971. const query = gl.createQuery();
  49972. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  49973. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  49974. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  49975. }
  49976. contextData.lastOcclusionObject = object;
  49977. }
  49978. //
  49979. const renderer = this.bufferRenderer;
  49980. if ( object.isPoints ) renderer.mode = gl.POINTS;
  49981. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  49982. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  49983. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  49984. else {
  49985. if ( material.wireframe === true ) {
  49986. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  49987. renderer.mode = gl.LINES;
  49988. } else {
  49989. renderer.mode = gl.TRIANGLES;
  49990. }
  49991. }
  49992. //
  49993. const { vertexCount, instanceCount } = drawParams;
  49994. let { firstVertex } = drawParams;
  49995. renderer.object = object;
  49996. if ( index !== null ) {
  49997. firstVertex *= index.array.BYTES_PER_ELEMENT;
  49998. const indexData = this.get( index );
  49999. renderer.index = index.count;
  50000. renderer.type = indexData.type;
  50001. } else {
  50002. renderer.index = 0;
  50003. }
  50004. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  50005. const cameraData = this.get( renderObject.camera );
  50006. const cameras = renderObject.camera.cameras;
  50007. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  50008. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  50009. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  50010. const indexesGPU = [];
  50011. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50012. const bufferGPU = gl.createBuffer();
  50013. data[ 0 ] = i;
  50014. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  50015. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  50016. indexesGPU.push( bufferGPU );
  50017. }
  50018. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  50019. }
  50020. let cameraIndexBufferIndex = 0;
  50021. bindingsSearch: for ( const bindGroup of renderObject.getBindings() ) {
  50022. for ( const binding of bindGroup.bindings ) {
  50023. if ( binding === cameraIndex ) break bindingsSearch;
  50024. if ( binding.isUniformsGroup || binding.isUniformBuffer ) cameraIndexBufferIndex ++;
  50025. }
  50026. }
  50027. const pixelRatio = this.renderer.getPixelRatio();
  50028. const renderTarget = this._currentContext.renderTarget;
  50029. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  50030. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  50031. if ( isRenderCameraDepthArray ) {
  50032. // Clear the depth texture
  50033. const textureData = this.get( renderTarget.depthTexture );
  50034. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  50035. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  50036. const { stencilBuffer } = renderTarget;
  50037. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50038. this.renderer._activeCubeFace = i;
  50039. this._currentContext.activeCubeFace = i;
  50040. this._setFramebuffer( this._currentContext );
  50041. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  50042. }
  50043. this.renderer._activeCubeFace = prevActiveCubeFace;
  50044. this._currentContext.activeCubeFace = prevActiveCubeFace;
  50045. }
  50046. }
  50047. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50048. const subCamera = cameras[ i ];
  50049. if ( object.layers.test( subCamera.layers ) ) {
  50050. if ( isRenderCameraDepthArray ) {
  50051. // Update the active layer
  50052. this.renderer._activeCubeFace = i;
  50053. this._currentContext.activeCubeFace = i;
  50054. this._setFramebuffer( this._currentContext );
  50055. }
  50056. const vp = subCamera.viewport;
  50057. if ( vp !== undefined ) {
  50058. const x = vp.x * pixelRatio;
  50059. const y = vp.y * pixelRatio;
  50060. const width = vp.width * pixelRatio;
  50061. const height = vp.height * pixelRatio;
  50062. state.viewport(
  50063. Math.floor( x ),
  50064. Math.floor( renderObject.context.height - height - y ),
  50065. Math.floor( width ),
  50066. Math.floor( height )
  50067. );
  50068. }
  50069. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexBufferIndex, cameraData.indexesGPU[ i ] );
  50070. this._draw( object, renderer, firstVertex, vertexCount, instanceCount, programGPU );
  50071. }
  50072. this._currentContext.activeCubeFace = prevActiveCubeFace;
  50073. this.renderer._activeCubeFace = prevActiveCubeFace;
  50074. }
  50075. } else {
  50076. this._draw( object, renderer, firstVertex, vertexCount, instanceCount, programGPU );
  50077. }
  50078. }
  50079. /**
  50080. * Explain why always null is returned.
  50081. *
  50082. * @param {RenderObject} renderObject - The render object.
  50083. * @return {boolean} Whether the render pipeline requires an update or not.
  50084. */
  50085. needsRenderUpdate( /*renderObject*/ ) {
  50086. return false;
  50087. }
  50088. /**
  50089. * Explain why no cache key is computed.
  50090. *
  50091. * @param {RenderObject} renderObject - The render object.
  50092. * @return {string} The cache key.
  50093. */
  50094. getRenderCacheKey( /*renderObject*/ ) {
  50095. return '';
  50096. }
  50097. // textures
  50098. /**
  50099. * Creates a default texture for the given texture that can be used
  50100. * as a placeholder until the actual texture is ready for usage.
  50101. *
  50102. * @param {Texture} texture - The texture to create a default texture for.
  50103. */
  50104. createDefaultTexture( texture ) {
  50105. this.textureUtils.createDefaultTexture( texture );
  50106. }
  50107. /**
  50108. * Defines a texture on the GPU for the given texture object.
  50109. *
  50110. * @param {Texture} texture - The texture.
  50111. * @param {Object} [options={}] - Optional configuration parameter.
  50112. */
  50113. createTexture( texture, options ) {
  50114. this.textureUtils.createTexture( texture, options );
  50115. }
  50116. /**
  50117. * Uploads the updated texture data to the GPU.
  50118. *
  50119. * @param {Texture} texture - The texture.
  50120. * @param {Object} [options={}] - Optional configuration parameter.
  50121. */
  50122. updateTexture( texture, options ) {
  50123. this.textureUtils.updateTexture( texture, options );
  50124. }
  50125. /**
  50126. * Generates mipmaps for the given texture.
  50127. *
  50128. * @param {Texture} texture - The texture.
  50129. */
  50130. generateMipmaps( texture ) {
  50131. this.textureUtils.generateMipmaps( texture );
  50132. }
  50133. /**
  50134. * Destroys the GPU data for the given texture object.
  50135. *
  50136. * @param {Texture} texture - The texture.
  50137. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  50138. */
  50139. destroyTexture( texture, isDefaultTexture = false ) {
  50140. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  50141. }
  50142. /**
  50143. * Returns texture data as a typed array.
  50144. *
  50145. * @async
  50146. * @param {Texture} texture - The texture to copy.
  50147. * @param {number} x - The x coordinate of the copy origin.
  50148. * @param {number} y - The y coordinate of the copy origin.
  50149. * @param {number} width - The width of the copy.
  50150. * @param {number} height - The height of the copy.
  50151. * @param {number} faceIndex - The face index.
  50152. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  50153. */
  50154. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  50155. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  50156. }
  50157. /**
  50158. * This method does nothing since WebGL 2 has no concept of samplers.
  50159. *
  50160. * @param {Texture} texture - The texture to update the sampler for.
  50161. * @return {string} The current sampler key.
  50162. */
  50163. updateSampler( /*texture*/ ) {
  50164. return '';
  50165. }
  50166. // node builder
  50167. /**
  50168. * Returns a node builder for the given render object.
  50169. *
  50170. * @param {RenderObject} object - The render object.
  50171. * @param {Renderer} renderer - The renderer.
  50172. * @return {GLSLNodeBuilder} The node builder.
  50173. */
  50174. createNodeBuilder( object, renderer ) {
  50175. return new GLSLNodeBuilder( object, renderer );
  50176. }
  50177. // program
  50178. /**
  50179. * Creates a shader program from the given programmable stage.
  50180. *
  50181. * @param {ProgrammableStage} program - The programmable stage.
  50182. */
  50183. createProgram( program ) {
  50184. const gl = this.gl;
  50185. const { stage, code } = program;
  50186. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  50187. gl.shaderSource( shader, code );
  50188. gl.compileShader( shader );
  50189. this.set( program, {
  50190. shaderGPU: shader
  50191. } );
  50192. }
  50193. /**
  50194. * Destroys the shader program of the given programmable stage.
  50195. *
  50196. * @param {ProgrammableStage} program - The programmable stage.
  50197. */
  50198. destroyProgram( program ) {
  50199. this.delete( program );
  50200. }
  50201. /**
  50202. * Creates a render pipeline for the given render object.
  50203. *
  50204. * @param {RenderObject} renderObject - The render object.
  50205. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  50206. */
  50207. createRenderPipeline( renderObject, promises ) {
  50208. const gl = this.gl;
  50209. const pipeline = renderObject.pipeline;
  50210. // Program
  50211. const { fragmentProgram, vertexProgram } = pipeline;
  50212. const programGPU = gl.createProgram();
  50213. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  50214. const vertexShader = this.get( vertexProgram ).shaderGPU;
  50215. gl.attachShader( programGPU, fragmentShader );
  50216. gl.attachShader( programGPU, vertexShader );
  50217. gl.linkProgram( programGPU );
  50218. this.set( pipeline, {
  50219. programGPU,
  50220. fragmentShader,
  50221. vertexShader
  50222. } );
  50223. if ( promises !== null && this.parallel ) {
  50224. const p = new Promise( ( resolve /*, reject*/ ) => {
  50225. const parallel = this.parallel;
  50226. const checkStatus = () => {
  50227. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  50228. this._completeCompile( renderObject, pipeline );
  50229. resolve();
  50230. } else {
  50231. requestAnimationFrame( checkStatus );
  50232. }
  50233. };
  50234. checkStatus();
  50235. } );
  50236. promises.push( p );
  50237. return;
  50238. }
  50239. this._completeCompile( renderObject, pipeline );
  50240. }
  50241. /**
  50242. * Formats the source code of error messages.
  50243. *
  50244. * @private
  50245. * @param {string} string - The code.
  50246. * @param {number} errorLine - The error line.
  50247. * @return {string} The formatted code.
  50248. */
  50249. _handleSource( string, errorLine ) {
  50250. const lines = string.split( '\n' );
  50251. const lines2 = [];
  50252. const from = Math.max( errorLine - 6, 0 );
  50253. const to = Math.min( errorLine + 6, lines.length );
  50254. for ( let i = from; i < to; i ++ ) {
  50255. const line = i + 1;
  50256. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  50257. }
  50258. return lines2.join( '\n' );
  50259. }
  50260. /**
  50261. * Gets the shader compilation errors from the info log.
  50262. *
  50263. * @private
  50264. * @param {WebGL2RenderingContext} gl - The rendering context.
  50265. * @param {WebGLShader} shader - The WebGL shader object.
  50266. * @param {string} type - The shader type.
  50267. * @return {string} The shader errors.
  50268. */
  50269. _getShaderErrors( gl, shader, type ) {
  50270. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  50271. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  50272. const errors = shaderInfoLog.trim();
  50273. if ( status && errors === '' ) return '';
  50274. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  50275. if ( errorMatches ) {
  50276. const errorLine = parseInt( errorMatches[ 1 ] );
  50277. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  50278. } else {
  50279. return errors;
  50280. }
  50281. }
  50282. /**
  50283. * Logs shader compilation errors.
  50284. *
  50285. * @private
  50286. * @param {WebGLProgram} programGPU - The WebGL program.
  50287. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  50288. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  50289. */
  50290. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  50291. if ( this.renderer.debug.checkShaderErrors ) {
  50292. const gl = this.gl;
  50293. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  50294. const programLog = programInfoLog.trim();
  50295. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  50296. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  50297. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  50298. } else {
  50299. // default error reporting
  50300. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  50301. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  50302. error(
  50303. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  50304. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  50305. 'Program Info Log: ' + programLog + '\n' +
  50306. vertexErrors + '\n' +
  50307. fragmentErrors
  50308. );
  50309. }
  50310. } else if ( programLog !== '' ) {
  50311. warn( 'WebGLProgram: Program Info Log:', programLog );
  50312. }
  50313. }
  50314. }
  50315. /**
  50316. * Completes the shader program setup for the given render object.
  50317. *
  50318. * @private
  50319. * @param {RenderObject} renderObject - The render object.
  50320. * @param {RenderPipeline} pipeline - The render pipeline.
  50321. */
  50322. _completeCompile( renderObject, pipeline ) {
  50323. const { state, gl } = this;
  50324. const pipelineData = this.get( pipeline );
  50325. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  50326. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  50327. this._logProgramError( programGPU, fragmentShader, vertexShader );
  50328. }
  50329. state.useProgram( programGPU );
  50330. // Bindings
  50331. const bindings = renderObject.getBindings();
  50332. this._setupBindings( bindings, programGPU );
  50333. //
  50334. this.set( pipeline, {
  50335. programGPU,
  50336. pipeline: programGPU
  50337. } );
  50338. }
  50339. /**
  50340. * Creates a compute pipeline for the given compute node.
  50341. *
  50342. * @param {ComputePipeline} computePipeline - The compute pipeline.
  50343. * @param {Array<BindGroup>} bindings - The bindings.
  50344. */
  50345. createComputePipeline( computePipeline, bindings ) {
  50346. const { state, gl } = this;
  50347. // Program
  50348. const fragmentProgram = {
  50349. stage: 'fragment',
  50350. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  50351. };
  50352. this.createProgram( fragmentProgram );
  50353. const { computeProgram } = computePipeline;
  50354. const programGPU = gl.createProgram();
  50355. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  50356. const vertexShader = this.get( computeProgram ).shaderGPU;
  50357. const transforms = computeProgram.transforms;
  50358. const transformVaryingNames = [];
  50359. const transformAttributeNodes = [];
  50360. for ( let i = 0; i < transforms.length; i ++ ) {
  50361. const transform = transforms[ i ];
  50362. transformVaryingNames.push( transform.varyingName );
  50363. transformAttributeNodes.push( transform.attributeNode );
  50364. }
  50365. gl.attachShader( programGPU, fragmentShader );
  50366. gl.attachShader( programGPU, vertexShader );
  50367. gl.transformFeedbackVaryings(
  50368. programGPU,
  50369. transformVaryingNames,
  50370. gl.SEPARATE_ATTRIBS
  50371. );
  50372. gl.linkProgram( programGPU );
  50373. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  50374. this._logProgramError( programGPU, fragmentShader, vertexShader );
  50375. }
  50376. state.useProgram( programGPU );
  50377. // Bindings
  50378. this._setupBindings( bindings, programGPU );
  50379. const attributeNodes = computeProgram.attributes;
  50380. const attributes = [];
  50381. const transformBuffers = [];
  50382. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  50383. const attribute = attributeNodes[ i ].node.attribute;
  50384. attributes.push( attribute );
  50385. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  50386. }
  50387. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  50388. const attribute = transformAttributeNodes[ i ].attribute;
  50389. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  50390. const attributeData = this.get( attribute );
  50391. transformBuffers.push( attributeData );
  50392. }
  50393. //
  50394. this.set( computePipeline, {
  50395. programGPU,
  50396. transformBuffers,
  50397. attributes
  50398. } );
  50399. }
  50400. /**
  50401. * Creates bindings from the given bind group definition.
  50402. *
  50403. * @param {BindGroup} bindGroup - The bind group.
  50404. * @param {Array<BindGroup>} bindings - Array of bind groups.
  50405. * @param {number} cacheIndex - The cache index.
  50406. * @param {number} version - The version.
  50407. */
  50408. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  50409. if ( this._knownBindings.has( bindings ) === false ) {
  50410. this._knownBindings.add( bindings );
  50411. let uniformBuffers = 0;
  50412. let textures = 0;
  50413. for ( const bindGroup of bindings ) {
  50414. this.set( bindGroup, {
  50415. textures: textures,
  50416. uniformBuffers: uniformBuffers
  50417. } );
  50418. for ( const binding of bindGroup.bindings ) {
  50419. if ( binding.isUniformBuffer ) uniformBuffers ++;
  50420. if ( binding.isSampledTexture ) textures ++;
  50421. }
  50422. }
  50423. }
  50424. this.updateBindings( bindGroup, bindings );
  50425. }
  50426. /**
  50427. * Updates the given bind group definition.
  50428. *
  50429. * @param {BindGroup} bindGroup - The bind group.
  50430. * @param {Array<BindGroup>} bindings - Array of bind groups.
  50431. * @param {number} cacheIndex - The cache index.
  50432. * @param {number} version - The version.
  50433. */
  50434. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  50435. const { gl } = this;
  50436. for ( const binding of bindGroup.bindings ) {
  50437. const map = this.get( binding );
  50438. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  50439. const array = binding.buffer;
  50440. let { bufferGPU } = this.get( array );
  50441. if ( bufferGPU === undefined ) {
  50442. // create
  50443. bufferGPU = gl.createBuffer();
  50444. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  50445. gl.bufferData( gl.UNIFORM_BUFFER, array.byteLength, gl.DYNAMIC_DRAW );
  50446. this.set( array, { bufferGPU } );
  50447. } else {
  50448. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  50449. }
  50450. // update
  50451. const updateRanges = binding.updateRanges;
  50452. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  50453. if ( updateRanges.length === 0 ) {
  50454. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  50455. } else {
  50456. const isTyped = isTypedArray( array );
  50457. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  50458. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  50459. const range = updateRanges[ i ];
  50460. const dataOffset = range.start * byteOffsetFactor;
  50461. const size = range.count * byteOffsetFactor;
  50462. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  50463. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  50464. }
  50465. }
  50466. map.bufferGPU = bufferGPU;
  50467. this.set( binding, map );
  50468. } else if ( binding.isSampledTexture ) {
  50469. const { textureGPU, glTextureType } = this.get( binding.texture );
  50470. map.textureGPU = textureGPU;
  50471. map.glTextureType = glTextureType;
  50472. this.set( binding, map );
  50473. }
  50474. }
  50475. }
  50476. /**
  50477. * Updates a buffer binding.
  50478. *
  50479. * @param {Buffer} binding - The buffer binding to update.
  50480. */
  50481. updateBinding( binding ) {
  50482. const gl = this.gl;
  50483. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  50484. const bindingData = this.get( binding );
  50485. const bufferGPU = bindingData.bufferGPU;
  50486. const array = binding.buffer;
  50487. const updateRanges = binding.updateRanges;
  50488. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  50489. if ( updateRanges.length === 0 ) {
  50490. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  50491. } else {
  50492. const isTyped = isTypedArray( array );
  50493. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  50494. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  50495. const range = updateRanges[ i ];
  50496. const dataOffset = range.start * byteOffsetFactor;
  50497. const size = range.count * byteOffsetFactor;
  50498. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  50499. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  50500. }
  50501. }
  50502. }
  50503. }
  50504. // attributes
  50505. /**
  50506. * Creates the GPU buffer of an indexed shader attribute.
  50507. *
  50508. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  50509. */
  50510. createIndexAttribute( attribute ) {
  50511. const gl = this.gl;
  50512. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  50513. }
  50514. /**
  50515. * Creates the GPU buffer of a shader attribute.
  50516. *
  50517. * @param {BufferAttribute} attribute - The buffer attribute.
  50518. */
  50519. createAttribute( attribute ) {
  50520. if ( this.has( attribute ) ) return;
  50521. const gl = this.gl;
  50522. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  50523. }
  50524. /**
  50525. * Creates the GPU buffer of a storage attribute.
  50526. *
  50527. * @param {BufferAttribute} attribute - The buffer attribute.
  50528. */
  50529. createStorageAttribute( attribute ) {
  50530. if ( this.has( attribute ) ) return;
  50531. const gl = this.gl;
  50532. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  50533. }
  50534. /**
  50535. * Updates the GPU buffer of a shader attribute.
  50536. *
  50537. * @param {BufferAttribute} attribute - The buffer attribute to update.
  50538. */
  50539. updateAttribute( attribute ) {
  50540. this.attributeUtils.updateAttribute( attribute );
  50541. }
  50542. /**
  50543. * Destroys the GPU buffer of a shader attribute.
  50544. *
  50545. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  50546. */
  50547. destroyAttribute( attribute ) {
  50548. this.attributeUtils.destroyAttribute( attribute );
  50549. }
  50550. /**
  50551. * Checks if the given feature is supported by the backend.
  50552. *
  50553. * @param {string} name - The feature's name.
  50554. * @return {boolean} Whether the feature is supported or not.
  50555. */
  50556. hasFeature( name ) {
  50557. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  50558. const extensions = this.extensions;
  50559. for ( let i = 0; i < keysMatching.length; i ++ ) {
  50560. if ( extensions.has( keysMatching[ i ] ) ) return true;
  50561. }
  50562. return false;
  50563. }
  50564. /**
  50565. * Copies data of the given source texture to the given destination texture.
  50566. *
  50567. * @param {Texture} srcTexture - The source texture.
  50568. * @param {Texture} dstTexture - The destination texture.
  50569. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  50570. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  50571. * @param {number} [srcLevel=0] - The source mip level to copy from.
  50572. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  50573. */
  50574. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  50575. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  50576. }
  50577. /**
  50578. * Copies the current bound framebuffer to the given texture.
  50579. *
  50580. * @param {Texture} texture - The destination texture.
  50581. * @param {RenderContext} renderContext - The render context.
  50582. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  50583. */
  50584. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  50585. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  50586. }
  50587. /**
  50588. * Checks if the given compatibility is supported by the backend.
  50589. *
  50590. * @param {string} name - The compatibility name.
  50591. * @return {boolean} Whether the compatibility is supported or not.
  50592. */
  50593. hasCompatibility( name ) {
  50594. if ( name === Compatibility.TEXTURE_COMPARE ) return true;
  50595. return super.hasCompatibility( name );
  50596. }
  50597. /**
  50598. * Initializes the render target defined in the given render context.
  50599. *
  50600. * @param {RenderContext} renderContext - The render context.
  50601. */
  50602. initRenderTarget( renderContext ) {
  50603. const { gl, state } = this;
  50604. this._setFramebuffer( renderContext );
  50605. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  50606. }
  50607. /**
  50608. * Configures the active framebuffer from the given render context.
  50609. *
  50610. * @private
  50611. * @param {RenderContext} descriptor - The render context.
  50612. */
  50613. _setFramebuffer( descriptor ) {
  50614. const { gl, state } = this;
  50615. let currentFrameBuffer = null;
  50616. if ( descriptor.textures !== null ) {
  50617. const renderTarget = descriptor.renderTarget;
  50618. const renderTargetContextData = this.get( renderTarget );
  50619. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  50620. const isCube = renderTarget.isCubeRenderTarget === true;
  50621. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  50622. const isRenderTargetArray = renderTarget.depth > 1;
  50623. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  50624. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  50625. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  50626. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  50627. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  50628. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  50629. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  50630. const cacheKey = getCacheKey( descriptor );
  50631. let fb;
  50632. if ( isCube ) {
  50633. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  50634. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  50635. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  50636. fb = this._xrFramebuffer;
  50637. } else {
  50638. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  50639. fb = renderTargetContextData.framebuffers[ cacheKey ];
  50640. }
  50641. if ( fb === undefined ) {
  50642. fb = gl.createFramebuffer();
  50643. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  50644. const textures = descriptor.textures;
  50645. const depthInvalidationArray = [];
  50646. if ( isCube ) {
  50647. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  50648. const { textureGPU } = this.get( textures[ 0 ] );
  50649. const cubeFace = this.renderer._activeCubeFace;
  50650. const mipLevel = this.renderer._activeMipmapLevel;
  50651. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  50652. } else {
  50653. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  50654. for ( let i = 0; i < textures.length; i ++ ) {
  50655. const texture = textures[ i ];
  50656. const textureData = this.get( texture );
  50657. textureData.renderTarget = descriptor.renderTarget;
  50658. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  50659. const attachment = gl.COLOR_ATTACHMENT0 + i;
  50660. if ( renderTarget.multiview ) {
  50661. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  50662. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  50663. const layer = this.renderer._activeCubeFace;
  50664. const mipLevel = this.renderer._activeMipmapLevel;
  50665. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  50666. } else {
  50667. if ( useMultisampledRTT ) {
  50668. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  50669. } else {
  50670. const mipLevel = this.renderer._activeMipmapLevel;
  50671. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  50672. }
  50673. }
  50674. }
  50675. }
  50676. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  50677. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  50678. const renderbuffer = gl.createRenderbuffer();
  50679. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  50680. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  50681. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  50682. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  50683. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  50684. } else {
  50685. if ( descriptor.depthTexture !== null ) {
  50686. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  50687. const textureData = this.get( descriptor.depthTexture );
  50688. textureData.renderTarget = descriptor.renderTarget;
  50689. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  50690. if ( renderTarget.multiview ) {
  50691. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  50692. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  50693. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  50694. } else {
  50695. if ( descriptor.depthTexture.isArrayTexture ) {
  50696. const layer = this.renderer._activeCubeFace;
  50697. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  50698. } else if ( descriptor.depthTexture.isCubeTexture ) {
  50699. const cubeFace = this.renderer._activeCubeFace;
  50700. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureData.textureGPU, 0 );
  50701. } else {
  50702. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  50703. }
  50704. }
  50705. }
  50706. }
  50707. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  50708. } else {
  50709. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  50710. if ( isRenderCameraDepthArray ) {
  50711. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  50712. const layer = this.renderer._activeCubeFace;
  50713. const depthData = this.get( descriptor.depthTexture );
  50714. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  50715. gl.framebufferTextureLayer(
  50716. gl.FRAMEBUFFER,
  50717. depthStyle,
  50718. depthData.textureGPU,
  50719. 0,
  50720. layer
  50721. );
  50722. }
  50723. // rebind external XR textures
  50724. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  50725. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  50726. // rebind color
  50727. const textureData = this.get( descriptor.textures[ 0 ] );
  50728. if ( renderTarget.multiview ) {
  50729. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  50730. } else if ( useMultisampledRTT ) {
  50731. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  50732. } else {
  50733. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  50734. }
  50735. // rebind depth
  50736. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  50737. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  50738. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  50739. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  50740. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  50741. } else {
  50742. const textureData = this.get( descriptor.depthTexture );
  50743. if ( renderTarget.multiview ) {
  50744. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  50745. } else if ( useMultisampledRTT ) {
  50746. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  50747. } else {
  50748. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  50749. }
  50750. }
  50751. }
  50752. }
  50753. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  50754. if ( msaaFb === undefined ) {
  50755. const invalidationArray = [];
  50756. msaaFb = gl.createFramebuffer();
  50757. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  50758. const msaaRenderbuffers = [];
  50759. const textures = descriptor.textures;
  50760. for ( let i = 0; i < textures.length; i ++ ) {
  50761. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  50762. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50763. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  50764. const texture = descriptor.textures[ i ];
  50765. const textureData = this.get( texture );
  50766. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  50767. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50768. }
  50769. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  50770. renderTargetContextData.msaaFrameBuffer = msaaFb;
  50771. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  50772. if ( depthBuffer && depthRenderbuffer === undefined ) {
  50773. depthRenderbuffer = gl.createRenderbuffer();
  50774. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  50775. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  50776. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  50777. invalidationArray.push( depthStyle );
  50778. }
  50779. renderTargetContextData.invalidationArray = invalidationArray;
  50780. }
  50781. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  50782. } else {
  50783. currentFrameBuffer = fb;
  50784. }
  50785. state.drawBuffers( descriptor, fb );
  50786. }
  50787. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  50788. }
  50789. /**
  50790. * Computes the VAO key for the given index and attributes.
  50791. *
  50792. * @private
  50793. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  50794. * @return {string} The VAO key.
  50795. */
  50796. _getVaoKey( attributes ) {
  50797. let key = '';
  50798. for ( let i = 0; i < attributes.length; i ++ ) {
  50799. const attributeData = this.get( attributes[ i ] );
  50800. key += ':' + attributeData.id;
  50801. }
  50802. return key;
  50803. }
  50804. /**
  50805. * Creates a VAO from the index and attributes.
  50806. *
  50807. * @private
  50808. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  50809. * @return {Object} The VAO data.
  50810. */
  50811. _createVao( attributes ) {
  50812. const { gl } = this;
  50813. const vaoGPU = gl.createVertexArray();
  50814. gl.bindVertexArray( vaoGPU );
  50815. for ( let i = 0; i < attributes.length; i ++ ) {
  50816. const attribute = attributes[ i ];
  50817. const attributeData = this.get( attribute );
  50818. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  50819. gl.enableVertexAttribArray( i );
  50820. let stride, offset;
  50821. if ( attribute.isInterleavedBufferAttribute === true ) {
  50822. stride = attribute.data.stride * attributeData.bytesPerElement;
  50823. offset = attribute.offset * attributeData.bytesPerElement;
  50824. } else {
  50825. stride = 0;
  50826. offset = 0;
  50827. }
  50828. if ( attributeData.isInteger ) {
  50829. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  50830. } else {
  50831. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  50832. }
  50833. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  50834. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  50835. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  50836. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  50837. }
  50838. }
  50839. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  50840. return vaoGPU;
  50841. }
  50842. /**
  50843. * Creates a transform feedback from the given transform buffers.
  50844. *
  50845. * @private
  50846. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  50847. * @return {WebGLTransformFeedback} The transform feedback.
  50848. */
  50849. _getTransformFeedback( transformBuffers ) {
  50850. let key = '';
  50851. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  50852. key += ':' + transformBuffers[ i ].id;
  50853. }
  50854. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  50855. if ( transformFeedbackGPU !== undefined ) {
  50856. return transformFeedbackGPU;
  50857. }
  50858. const { gl } = this;
  50859. transformFeedbackGPU = gl.createTransformFeedback();
  50860. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  50861. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  50862. const attributeData = transformBuffers[ i ];
  50863. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  50864. }
  50865. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  50866. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  50867. return transformFeedbackGPU;
  50868. }
  50869. /**
  50870. * Setups the given bindings.
  50871. *
  50872. * @private
  50873. * @param {Array<BindGroup>} bindings - The bindings.
  50874. * @param {WebGLProgram} programGPU - The WebGL program.
  50875. */
  50876. _setupBindings( bindings, programGPU ) {
  50877. const gl = this.gl;
  50878. let uniformBuffers = 0;
  50879. let textures = 0;
  50880. for ( const bindGroup of bindings ) {
  50881. for ( const binding of bindGroup.bindings ) {
  50882. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  50883. const index = uniformBuffers ++;
  50884. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  50885. gl.uniformBlockBinding( programGPU, location, index );
  50886. } else if ( binding.isSampledTexture ) {
  50887. const index = textures ++;
  50888. const location = gl.getUniformLocation( programGPU, binding.name );
  50889. gl.uniform1i( location, index );
  50890. }
  50891. }
  50892. }
  50893. }
  50894. /**
  50895. * Binds the given uniforms.
  50896. *
  50897. * @private
  50898. * @param {Array<BindGroup>} bindings - The bindings.
  50899. */
  50900. _bindUniforms( bindings ) {
  50901. const { gl, state } = this;
  50902. let uniformBuffers = 0;
  50903. let textures = 0;
  50904. for ( const bindGroup of bindings ) {
  50905. for ( const binding of bindGroup.bindings ) {
  50906. const bindingData = this.get( binding );
  50907. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  50908. const index = uniformBuffers ++;
  50909. // TODO USE bindBufferRange to group multiple uniform buffers
  50910. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  50911. } else if ( binding.isSampledTexture ) {
  50912. const index = textures ++;
  50913. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  50914. }
  50915. }
  50916. }
  50917. }
  50918. /**
  50919. * The method ensures multisampled render targets are resolved.
  50920. *
  50921. * @private
  50922. * @param {RenderContext} renderContext - The render context.
  50923. */
  50924. _resolveRenderTarget( renderContext ) {
  50925. const { gl, state } = this;
  50926. const renderTarget = renderContext.renderTarget;
  50927. if ( renderContext.textures !== null && renderTarget ) {
  50928. const renderTargetContextData = this.get( renderTarget );
  50929. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  50930. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  50931. let mask = gl.COLOR_BUFFER_BIT;
  50932. if ( renderTarget.resolveDepthBuffer ) {
  50933. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  50934. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  50935. }
  50936. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  50937. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  50938. const textures = renderContext.textures;
  50939. const isMRT = textures.length > 1;
  50940. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  50941. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  50942. if ( isMRT ) {
  50943. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  50944. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  50945. for ( let i = 0; i < textures.length; i ++ ) {
  50946. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  50947. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  50948. }
  50949. }
  50950. for ( let i = 0; i < textures.length; i ++ ) {
  50951. if ( isMRT ) {
  50952. // configure attachment for resolve
  50953. const { textureGPU } = this.get( textures[ i ] );
  50954. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50955. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  50956. }
  50957. if ( renderContext.scissor ) {
  50958. const { x, y, width, height } = renderContext.scissorValue;
  50959. const viewY = renderContext.height - height - y;
  50960. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  50961. } else {
  50962. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  50963. }
  50964. }
  50965. if ( isMRT ) {
  50966. // restore attachments
  50967. for ( let i = 0; i < textures.length; i ++ ) {
  50968. const { textureGPU } = this.get( textures[ i ] );
  50969. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50970. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  50971. }
  50972. }
  50973. if ( this._supportsInvalidateFramebuffer === true ) {
  50974. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  50975. }
  50976. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  50977. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  50978. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  50979. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  50980. }
  50981. }
  50982. }
  50983. /**
  50984. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  50985. * should be used when MSAA is enabled.
  50986. *
  50987. * @private
  50988. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  50989. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  50990. */
  50991. _useMultisampledExtension( renderTarget ) {
  50992. if ( renderTarget.multiview === true ) {
  50993. return true;
  50994. }
  50995. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  50996. }
  50997. /**
  50998. * Frees internal resources.
  50999. */
  51000. dispose() {
  51001. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  51002. const extension = this.extensions.get( 'WEBGL_lose_context' );
  51003. if ( extension ) extension.loseContext();
  51004. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  51005. }
  51006. }
  51007. const GPUPrimitiveTopology = {
  51008. PointList: 'point-list',
  51009. LineList: 'line-list',
  51010. LineStrip: 'line-strip',
  51011. TriangleList: 'triangle-list'};
  51012. const GPUShaderStage = ( typeof self !== 'undefined' && self.GPUShaderStage ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  51013. const GPUCompareFunction = {
  51014. Never: 'never',
  51015. Less: 'less',
  51016. Equal: 'equal',
  51017. LessEqual: 'less-equal',
  51018. Greater: 'greater',
  51019. NotEqual: 'not-equal',
  51020. GreaterEqual: 'greater-equal',
  51021. Always: 'always'
  51022. };
  51023. const GPUStoreOp = {
  51024. Store: 'store'};
  51025. const GPULoadOp = {
  51026. Load: 'load',
  51027. Clear: 'clear'
  51028. };
  51029. const GPUFrontFace = {
  51030. CCW: 'ccw',
  51031. CW: 'cw'
  51032. };
  51033. const GPUCullMode = {
  51034. None: 'none',
  51035. Back: 'back'
  51036. };
  51037. const GPUIndexFormat = {
  51038. Uint16: 'uint16',
  51039. Uint32: 'uint32'
  51040. };
  51041. const GPUTextureFormat = {
  51042. // 8-bit formats
  51043. R8Unorm: 'r8unorm',
  51044. R8Snorm: 'r8snorm',
  51045. R8Uint: 'r8uint',
  51046. R8Sint: 'r8sint',
  51047. // 16-bit formats
  51048. R16Uint: 'r16uint',
  51049. R16Sint: 'r16sint',
  51050. R16Float: 'r16float',
  51051. RG8Unorm: 'rg8unorm',
  51052. RG8Snorm: 'rg8snorm',
  51053. RG8Uint: 'rg8uint',
  51054. RG8Sint: 'rg8sint',
  51055. // 32-bit formats
  51056. R32Uint: 'r32uint',
  51057. R32Sint: 'r32sint',
  51058. R32Float: 'r32float',
  51059. RG16Uint: 'rg16uint',
  51060. RG16Sint: 'rg16sint',
  51061. RG16Float: 'rg16float',
  51062. RGBA8Unorm: 'rgba8unorm',
  51063. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  51064. RGBA8Snorm: 'rgba8snorm',
  51065. RGBA8Uint: 'rgba8uint',
  51066. RGBA8Sint: 'rgba8sint',
  51067. BGRA8Unorm: 'bgra8unorm',
  51068. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  51069. // Packed 32-bit formats
  51070. RGB9E5UFloat: 'rgb9e5ufloat',
  51071. RGB10A2Unorm: 'rgb10a2unorm',
  51072. RG11B10UFloat: 'rg11b10ufloat',
  51073. // 64-bit formats
  51074. RG32Uint: 'rg32uint',
  51075. RG32Sint: 'rg32sint',
  51076. RG32Float: 'rg32float',
  51077. RGBA16Uint: 'rgba16uint',
  51078. RGBA16Sint: 'rgba16sint',
  51079. RGBA16Float: 'rgba16float',
  51080. // 128-bit formats
  51081. RGBA32Uint: 'rgba32uint',
  51082. RGBA32Sint: 'rgba32sint',
  51083. RGBA32Float: 'rgba32float',
  51084. Depth16Unorm: 'depth16unorm',
  51085. Depth24Plus: 'depth24plus',
  51086. Depth24PlusStencil8: 'depth24plus-stencil8',
  51087. Depth32Float: 'depth32float',
  51088. // 'depth32float-stencil8' extension
  51089. Depth32FloatStencil8: 'depth32float-stencil8',
  51090. // BC compressed formats usable if 'texture-compression-bc' is both
  51091. // supported by the device/user agent and enabled in requestDevice.
  51092. BC1RGBAUnorm: 'bc1-rgba-unorm',
  51093. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  51094. BC2RGBAUnorm: 'bc2-rgba-unorm',
  51095. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  51096. BC3RGBAUnorm: 'bc3-rgba-unorm',
  51097. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  51098. BC4RUnorm: 'bc4-r-unorm',
  51099. BC4RSnorm: 'bc4-r-snorm',
  51100. BC5RGUnorm: 'bc5-rg-unorm',
  51101. BC5RGSnorm: 'bc5-rg-snorm',
  51102. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  51103. BC6HRGBFloat: 'bc6h-rgb-float',
  51104. BC7RGBAUnorm: 'bc7-rgba-unorm',
  51105. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  51106. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  51107. // supported by the device/user agent and enabled in requestDevice.
  51108. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  51109. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  51110. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  51111. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  51112. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  51113. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  51114. EACR11Unorm: 'eac-r11unorm',
  51115. EACR11Snorm: 'eac-r11snorm',
  51116. EACRG11Unorm: 'eac-rg11unorm',
  51117. EACRG11Snorm: 'eac-rg11snorm',
  51118. // ASTC compressed formats usable if 'texture-compression-astc' is both
  51119. // supported by the device/user agent and enabled in requestDevice.
  51120. ASTC4x4Unorm: 'astc-4x4-unorm',
  51121. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  51122. ASTC5x4Unorm: 'astc-5x4-unorm',
  51123. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  51124. ASTC5x5Unorm: 'astc-5x5-unorm',
  51125. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  51126. ASTC6x5Unorm: 'astc-6x5-unorm',
  51127. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  51128. ASTC6x6Unorm: 'astc-6x6-unorm',
  51129. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  51130. ASTC8x5Unorm: 'astc-8x5-unorm',
  51131. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  51132. ASTC8x6Unorm: 'astc-8x6-unorm',
  51133. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  51134. ASTC8x8Unorm: 'astc-8x8-unorm',
  51135. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  51136. ASTC10x5Unorm: 'astc-10x5-unorm',
  51137. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  51138. ASTC10x6Unorm: 'astc-10x6-unorm',
  51139. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  51140. ASTC10x8Unorm: 'astc-10x8-unorm',
  51141. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  51142. ASTC10x10Unorm: 'astc-10x10-unorm',
  51143. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  51144. ASTC12x10Unorm: 'astc-12x10-unorm',
  51145. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  51146. ASTC12x12Unorm: 'astc-12x12-unorm',
  51147. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  51148. };
  51149. const GPUAddressMode = {
  51150. ClampToEdge: 'clamp-to-edge',
  51151. Repeat: 'repeat',
  51152. MirrorRepeat: 'mirror-repeat'
  51153. };
  51154. const GPUFilterMode = {
  51155. Linear: 'linear',
  51156. Nearest: 'nearest'
  51157. };
  51158. const GPUBlendFactor = {
  51159. Zero: 'zero',
  51160. One: 'one',
  51161. Src: 'src',
  51162. OneMinusSrc: 'one-minus-src',
  51163. SrcAlpha: 'src-alpha',
  51164. OneMinusSrcAlpha: 'one-minus-src-alpha',
  51165. Dst: 'dst',
  51166. OneMinusDst: 'one-minus-dst',
  51167. DstAlpha: 'dst-alpha',
  51168. OneMinusDstAlpha: 'one-minus-dst-alpha',
  51169. SrcAlphaSaturated: 'src-alpha-saturated',
  51170. Constant: 'constant',
  51171. OneMinusConstant: 'one-minus-constant'
  51172. };
  51173. const GPUBlendOperation = {
  51174. Add: 'add',
  51175. Subtract: 'subtract',
  51176. ReverseSubtract: 'reverse-subtract',
  51177. Min: 'min',
  51178. Max: 'max'
  51179. };
  51180. const GPUColorWriteFlags = {
  51181. None: 0,
  51182. All: 0xF
  51183. };
  51184. const GPUStencilOperation = {
  51185. Keep: 'keep',
  51186. Zero: 'zero',
  51187. Replace: 'replace',
  51188. Invert: 'invert',
  51189. IncrementClamp: 'increment-clamp',
  51190. DecrementClamp: 'decrement-clamp',
  51191. IncrementWrap: 'increment-wrap',
  51192. DecrementWrap: 'decrement-wrap'
  51193. };
  51194. const GPUBufferBindingType = {
  51195. Storage: 'storage',
  51196. ReadOnlyStorage: 'read-only-storage'
  51197. };
  51198. const GPUStorageTextureAccess = {
  51199. WriteOnly: 'write-only',
  51200. ReadOnly: 'read-only',
  51201. ReadWrite: 'read-write',
  51202. };
  51203. const GPUSamplerBindingType = {
  51204. NonFiltering: 'non-filtering',
  51205. Comparison: 'comparison'
  51206. };
  51207. const GPUTextureSampleType = {
  51208. Float: 'float',
  51209. UnfilterableFloat: 'unfilterable-float',
  51210. Depth: 'depth',
  51211. SInt: 'sint',
  51212. UInt: 'uint'
  51213. };
  51214. const GPUTextureDimension = {
  51215. TwoD: '2d',
  51216. ThreeD: '3d'
  51217. };
  51218. const GPUTextureViewDimension = {
  51219. TwoD: '2d',
  51220. TwoDArray: '2d-array',
  51221. Cube: 'cube',
  51222. ThreeD: '3d'
  51223. };
  51224. const GPUTextureAspect = {
  51225. All: 'all'};
  51226. const GPUInputStepMode = {
  51227. Vertex: 'vertex',
  51228. Instance: 'instance'
  51229. };
  51230. const GPUFeatureName = {
  51231. CoreFeaturesAndLimits: 'core-features-and-limits',
  51232. DepthClipControl: 'depth-clip-control',
  51233. Depth32FloatStencil8: 'depth32float-stencil8',
  51234. TextureCompressionBC: 'texture-compression-bc',
  51235. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  51236. TextureCompressionETC2: 'texture-compression-etc2',
  51237. TextureCompressionASTC: 'texture-compression-astc',
  51238. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  51239. TimestampQuery: 'timestamp-query',
  51240. IndirectFirstInstance: 'indirect-first-instance',
  51241. ShaderF16: 'shader-f16',
  51242. RG11B10UFloat: 'rg11b10ufloat-renderable',
  51243. BGRA8UNormStorage: 'bgra8unorm-storage',
  51244. Float32Filterable: 'float32-filterable',
  51245. Float32Blendable: 'float32-blendable',
  51246. ClipDistances: 'clip-distances',
  51247. DualSourceBlending: 'dual-source-blending',
  51248. Subgroups: 'subgroups',
  51249. TextureFormatsTier1: 'texture-formats-tier1',
  51250. TextureFormatsTier2: 'texture-formats-tier2'
  51251. };
  51252. const GPUFeatureMap = {
  51253. 'texture-compression-s3tc': 'texture-compression-bc',
  51254. 'texture-compression-etc1': 'texture-compression-etc2'
  51255. };
  51256. /**
  51257. * A special form of sampler binding type.
  51258. * It's texture value is managed by a node object.
  51259. *
  51260. * @private
  51261. * @augments Sampler
  51262. */
  51263. class NodeSampler extends Sampler {
  51264. /**
  51265. * Constructs a new node-based sampler.
  51266. *
  51267. * @param {string} name - The samplers's name.
  51268. * @param {TextureNode} textureNode - The texture node.
  51269. * @param {UniformGroupNode} groupNode - The uniform group node.
  51270. */
  51271. constructor( name, textureNode, groupNode ) {
  51272. super( name, textureNode ? textureNode.value : null );
  51273. /**
  51274. * The texture node.
  51275. *
  51276. * @type {TextureNode}
  51277. */
  51278. this.textureNode = textureNode;
  51279. /**
  51280. * The uniform group node.
  51281. *
  51282. * @type {UniformGroupNode}
  51283. */
  51284. this.groupNode = groupNode;
  51285. }
  51286. /**
  51287. * Updates the texture value of this sampler.
  51288. *
  51289. * @return {boolean} Whether the sampler needs an update or not.
  51290. */
  51291. update() {
  51292. const { textureNode } = this;
  51293. if ( this.texture !== textureNode.value ) {
  51294. this.texture = textureNode.value;
  51295. return true;
  51296. }
  51297. return super.update();
  51298. }
  51299. }
  51300. /**
  51301. * Represents a storage buffer binding type.
  51302. *
  51303. * @private
  51304. * @augments Buffer
  51305. */
  51306. class StorageBuffer extends Buffer {
  51307. /**
  51308. * Constructs a new uniform buffer.
  51309. *
  51310. * @param {string} name - The buffer's name.
  51311. * @param {BufferAttribute} attribute - The buffer attribute.
  51312. */
  51313. constructor( name, attribute ) {
  51314. super( name, attribute ? attribute.array : null );
  51315. /**
  51316. * This flag can be used for type testing.
  51317. *
  51318. * @private
  51319. * @type {BufferAttribute}
  51320. */
  51321. this._attribute = attribute;
  51322. /**
  51323. * This flag can be used for type testing.
  51324. *
  51325. * @type {boolean}
  51326. * @readonly
  51327. * @default true
  51328. */
  51329. this.isStorageBuffer = true;
  51330. }
  51331. /**
  51332. * The storage buffer attribute.
  51333. *
  51334. * @type {BufferAttribute}
  51335. */
  51336. get attribute() {
  51337. return this._attribute;
  51338. }
  51339. }
  51340. let _id = 0;
  51341. /**
  51342. * A special form of storage buffer binding type.
  51343. * It's buffer value is managed by a node object.
  51344. *
  51345. * @private
  51346. * @augments StorageBuffer
  51347. */
  51348. class NodeStorageBuffer extends StorageBuffer {
  51349. /**
  51350. * Constructs a new node-based storage buffer.
  51351. *
  51352. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  51353. * @param {UniformGroupNode} groupNode - The uniform group node.
  51354. */
  51355. constructor( nodeUniform, groupNode ) {
  51356. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  51357. /**
  51358. * The node uniform.
  51359. *
  51360. * @type {StorageBufferNode}
  51361. */
  51362. this.nodeUniform = nodeUniform;
  51363. /**
  51364. * The access type.
  51365. *
  51366. * @type {string}
  51367. */
  51368. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  51369. /**
  51370. * The uniform group node.
  51371. *
  51372. * @type {UniformGroupNode}
  51373. */
  51374. this.groupNode = groupNode;
  51375. }
  51376. /**
  51377. * The storage buffer attribute node.
  51378. *
  51379. * @type {StorageBufferAttribute}
  51380. */
  51381. get attribute() {
  51382. return this.nodeUniform.value;
  51383. }
  51384. /**
  51385. * The storage buffer.
  51386. *
  51387. * @type {Float32Array}
  51388. */
  51389. get buffer() {
  51390. return this.nodeUniform.value.array;
  51391. }
  51392. }
  51393. /**
  51394. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  51395. *
  51396. * @private
  51397. */
  51398. class WebGPUTexturePassUtils extends DataMap {
  51399. /**
  51400. * Constructs a new utility object.
  51401. *
  51402. * @param {GPUDevice} device - The WebGPU device.
  51403. */
  51404. constructor( device ) {
  51405. super();
  51406. /**
  51407. * The WebGPU device.
  51408. *
  51409. * @type {GPUDevice}
  51410. */
  51411. this.device = device;
  51412. const mipmapSource = `
  51413. struct VarysStruct {
  51414. @builtin( position ) Position: vec4f,
  51415. @location( 0 ) vTex : vec2f,
  51416. @location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,
  51417. };
  51418. @group( 0 ) @binding ( 2 )
  51419. var<uniform> flipY: u32;
  51420. @vertex
  51421. fn mainVS(
  51422. @builtin( vertex_index ) vertexIndex : u32,
  51423. @builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {
  51424. var Varys : VarysStruct;
  51425. var pos = array(
  51426. vec2f( -1, -1 ),
  51427. vec2f( -1, 3 ),
  51428. vec2f( 3, -1 ),
  51429. );
  51430. let p = pos[ vertexIndex ];
  51431. let mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );
  51432. Varys.vTex = p * mult + vec2f( 0.5 );
  51433. Varys.Position = vec4f( p, 0, 1 );
  51434. Varys.vBaseArrayLayer = instanceIndex;
  51435. return Varys;
  51436. }
  51437. @group( 0 ) @binding( 0 )
  51438. var imgSampler : sampler;
  51439. @group( 0 ) @binding( 1 )
  51440. var img2d : texture_2d<f32>;
  51441. @fragment
  51442. fn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  51443. return textureSample( img2d, imgSampler, Varys.vTex );
  51444. }
  51445. @group( 0 ) @binding( 1 )
  51446. var img2dArray : texture_2d_array<f32>;
  51447. @fragment
  51448. fn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  51449. return textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );
  51450. }
  51451. const faceMat = array(
  51452. mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x
  51453. mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x
  51454. mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y
  51455. mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y
  51456. mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z
  51457. mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z
  51458. );
  51459. @group( 0 ) @binding( 1 )
  51460. var imgCube : texture_cube<f32>;
  51461. @fragment
  51462. fn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  51463. return textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );
  51464. }
  51465. `;
  51466. /**
  51467. * The mipmap GPU sampler.
  51468. *
  51469. * @type {GPUSampler}
  51470. */
  51471. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  51472. /**
  51473. * The flipY GPU sampler.
  51474. *
  51475. * @type {GPUSampler}
  51476. */
  51477. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  51478. /**
  51479. * flip uniform buffer
  51480. * @type {GPUBuffer}
  51481. */
  51482. this.flipUniformBuffer = device.createBuffer( {
  51483. size: 4,
  51484. usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
  51485. } );
  51486. device.queue.writeBuffer( this.flipUniformBuffer, 0, new Uint32Array( [ 1 ] ) );
  51487. /**
  51488. * no flip uniform buffer
  51489. * @type {GPUBuffer}
  51490. */
  51491. this.noFlipUniformBuffer = device.createBuffer( {
  51492. size: 4,
  51493. usage: GPUBufferUsage.UNIFORM
  51494. } );
  51495. /**
  51496. * A cache for GPU render pipelines used for copy/transfer passes.
  51497. * Every texture format and textureBindingViewDimension combo requires a unique pipeline.
  51498. *
  51499. * @type {Object<string,GPURenderPipeline>}
  51500. */
  51501. this.transferPipelines = {};
  51502. /**
  51503. * The mipmap shader module.
  51504. *
  51505. * @type {GPUShaderModule}
  51506. */
  51507. this.mipmapShaderModule = device.createShaderModule( {
  51508. label: 'mipmap',
  51509. code: mipmapSource
  51510. } );
  51511. }
  51512. /**
  51513. * Returns a render pipeline for the internal copy render pass. The pass
  51514. * requires a unique render pipeline for each texture format.
  51515. *
  51516. * @param {string} format - The GPU texture format
  51517. * @param {string?} textureBindingViewDimension - The GPU texture binding view dimension
  51518. * @return {GPURenderPipeline} The GPU render pipeline.
  51519. */
  51520. getTransferPipeline( format, textureBindingViewDimension ) {
  51521. textureBindingViewDimension = textureBindingViewDimension || '2d-array';
  51522. const key = `${ format }-${ textureBindingViewDimension }`;
  51523. let pipeline = this.transferPipelines[ key ];
  51524. if ( pipeline === undefined ) {
  51525. pipeline = this.device.createRenderPipeline( {
  51526. label: `mipmap-${ format }-${ textureBindingViewDimension }`,
  51527. vertex: {
  51528. module: this.mipmapShaderModule,
  51529. },
  51530. fragment: {
  51531. module: this.mipmapShaderModule,
  51532. entryPoint: `main_${ textureBindingViewDimension.replace( '-', '_' ) }`,
  51533. targets: [ { format } ]
  51534. },
  51535. layout: 'auto'
  51536. } );
  51537. this.transferPipelines[ key ] = pipeline;
  51538. }
  51539. return pipeline;
  51540. }
  51541. /**
  51542. * Flip the contents of the given GPU texture along its vertical axis.
  51543. *
  51544. * @param {GPUTexture} textureGPU - The GPU texture object.
  51545. * @param {Object} textureGPUDescriptor - The texture descriptor.
  51546. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  51547. */
  51548. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  51549. const format = textureGPUDescriptor.format;
  51550. const { width, height } = textureGPUDescriptor.size;
  51551. const tempTexture = this.device.createTexture( {
  51552. size: { width, height },
  51553. format,
  51554. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  51555. } );
  51556. const copyTransferPipeline = this.getTransferPipeline( format, textureGPU.textureBindingViewDimension );
  51557. const flipTransferPipeline = this.getTransferPipeline( format, tempTexture.textureBindingViewDimension );
  51558. const commandEncoder = this.device.createCommandEncoder( {} );
  51559. const pass = ( pipeline, sourceTexture, sourceArrayLayer, destinationTexture, destinationArrayLayer, flipY ) => {
  51560. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  51561. const bindGroup = this.device.createBindGroup( {
  51562. layout: bindGroupLayout,
  51563. entries: [ {
  51564. binding: 0,
  51565. resource: this.flipYSampler
  51566. }, {
  51567. binding: 1,
  51568. resource: sourceTexture.createView( {
  51569. dimension: sourceTexture.textureBindingViewDimension || '2d-array',
  51570. baseMipLevel: 0,
  51571. mipLevelCount: 1,
  51572. } ),
  51573. }, {
  51574. binding: 2,
  51575. resource: { buffer: flipY ? this.flipUniformBuffer : this.noFlipUniformBuffer }
  51576. } ]
  51577. } );
  51578. const passEncoder = commandEncoder.beginRenderPass( {
  51579. colorAttachments: [ {
  51580. view: destinationTexture.createView( {
  51581. dimension: '2d',
  51582. baseMipLevel: 0,
  51583. mipLevelCount: 1,
  51584. baseArrayLayer: destinationArrayLayer,
  51585. arrayLayerCount: 1,
  51586. } ),
  51587. loadOp: GPULoadOp.Clear,
  51588. storeOp: GPUStoreOp.Store,
  51589. } ]
  51590. } );
  51591. passEncoder.setPipeline( pipeline );
  51592. passEncoder.setBindGroup( 0, bindGroup );
  51593. passEncoder.draw( 3, 1, 0, sourceArrayLayer );
  51594. passEncoder.end();
  51595. };
  51596. pass( copyTransferPipeline, textureGPU, baseArrayLayer, tempTexture, 0, false );
  51597. pass( flipTransferPipeline, tempTexture, 0, textureGPU, baseArrayLayer, true );
  51598. this.device.queue.submit( [ commandEncoder.finish() ] );
  51599. tempTexture.destroy();
  51600. }
  51601. /**
  51602. * Generates mipmaps for the given GPU texture.
  51603. *
  51604. * @param {GPUTexture} textureGPU - The GPU texture object.
  51605. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  51606. */
  51607. generateMipmaps( textureGPU, encoder = null ) {
  51608. const textureData = this.get( textureGPU );
  51609. const passes = textureData.layers || this._mipmapCreateBundles( textureGPU );
  51610. const commandEncoder = encoder || this.device.createCommandEncoder( { label: 'mipmapEncoder' } );
  51611. this._mipmapRunBundles( commandEncoder, passes );
  51612. if ( encoder === null ) this.device.queue.submit( [ commandEncoder.finish() ] );
  51613. textureData.layers = passes;
  51614. }
  51615. /**
  51616. * Since multiple copy render passes are required to generate mipmaps, the passes
  51617. * are managed as render bundles to improve performance.
  51618. *
  51619. * @param {GPUTexture} textureGPU - The GPU texture object.
  51620. * @return {Array<Object>} An array of render bundles.
  51621. */
  51622. _mipmapCreateBundles( textureGPU ) {
  51623. const textureBindingViewDimension = textureGPU.textureBindingViewDimension || '2d-array';
  51624. const pipeline = this.getTransferPipeline( textureGPU.format, textureBindingViewDimension );
  51625. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  51626. const passes = [];
  51627. for ( let baseMipLevel = 1; baseMipLevel < textureGPU.mipLevelCount; baseMipLevel ++ ) {
  51628. for ( let baseArrayLayer = 0; baseArrayLayer < textureGPU.depthOrArrayLayers; baseArrayLayer ++ ) {
  51629. const bindGroup = this.device.createBindGroup( {
  51630. layout: bindGroupLayout,
  51631. entries: [ {
  51632. binding: 0,
  51633. resource: this.mipmapSampler
  51634. }, {
  51635. binding: 1,
  51636. resource: textureGPU.createView( {
  51637. dimension: textureBindingViewDimension,
  51638. baseMipLevel: baseMipLevel - 1,
  51639. mipLevelCount: 1,
  51640. } ),
  51641. }, {
  51642. binding: 2,
  51643. resource: { buffer: this.noFlipUniformBuffer }
  51644. } ]
  51645. } );
  51646. const passDescriptor = {
  51647. colorAttachments: [ {
  51648. view: textureGPU.createView( {
  51649. dimension: '2d',
  51650. baseMipLevel,
  51651. mipLevelCount: 1,
  51652. baseArrayLayer,
  51653. arrayLayerCount: 1,
  51654. } ),
  51655. loadOp: GPULoadOp.Clear,
  51656. storeOp: GPUStoreOp.Store,
  51657. } ]
  51658. };
  51659. const passEncoder = this.device.createRenderBundleEncoder( {
  51660. colorFormats: [ textureGPU.format ]
  51661. } );
  51662. passEncoder.setPipeline( pipeline );
  51663. passEncoder.setBindGroup( 0, bindGroup );
  51664. passEncoder.draw( 3, 1, 0, baseArrayLayer );
  51665. passes.push( {
  51666. renderBundles: [ passEncoder.finish() ],
  51667. passDescriptor
  51668. } );
  51669. }
  51670. }
  51671. return passes;
  51672. }
  51673. /**
  51674. * Executes the render bundles.
  51675. *
  51676. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  51677. * @param {Array<Object>} passes - An array of render bundles.
  51678. */
  51679. _mipmapRunBundles( commandEncoder, passes ) {
  51680. const levels = passes.length;
  51681. for ( let i = 0; i < levels; i ++ ) {
  51682. const pass = passes[ i ];
  51683. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  51684. passEncoder.executeBundles( pass.renderBundles );
  51685. passEncoder.end();
  51686. }
  51687. }
  51688. }
  51689. const _compareToWebGPU = {
  51690. [ NeverCompare ]: 'never',
  51691. [ LessCompare ]: 'less',
  51692. [ EqualCompare ]: 'equal',
  51693. [ LessEqualCompare ]: 'less-equal',
  51694. [ GreaterCompare ]: 'greater',
  51695. [ GreaterEqualCompare ]: 'greater-equal',
  51696. [ AlwaysCompare ]: 'always',
  51697. [ NotEqualCompare ]: 'not-equal'
  51698. };
  51699. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  51700. /**
  51701. * A WebGPU backend utility module for managing textures.
  51702. *
  51703. * @private
  51704. */
  51705. class WebGPUTextureUtils {
  51706. /**
  51707. * Constructs a new utility object.
  51708. *
  51709. * @param {WebGPUBackend} backend - The WebGPU backend.
  51710. */
  51711. constructor( backend ) {
  51712. /**
  51713. * A reference to the WebGPU backend.
  51714. *
  51715. * @type {WebGPUBackend}
  51716. */
  51717. this.backend = backend;
  51718. /**
  51719. * A reference to the pass utils.
  51720. *
  51721. * @type {?WebGPUTexturePassUtils}
  51722. * @default null
  51723. */
  51724. this._passUtils = null;
  51725. /**
  51726. * A dictionary for managing default textures. The key
  51727. * is the texture format, the value the texture object.
  51728. *
  51729. * @type {Object<string,Texture>}
  51730. */
  51731. this.defaultTexture = {};
  51732. /**
  51733. * A dictionary for managing default cube textures. The key
  51734. * is the texture format, the value the texture object.
  51735. *
  51736. * @type {Object<string,CubeTexture>}
  51737. */
  51738. this.defaultCubeTexture = {};
  51739. /**
  51740. * A default video frame.
  51741. *
  51742. * @type {?VideoFrame}
  51743. * @default null
  51744. */
  51745. this.defaultVideoFrame = null;
  51746. /**
  51747. * A cache of shared texture samplers.
  51748. *
  51749. * @type {Map<string, Object>}
  51750. */
  51751. this._samplerCache = new Map();
  51752. }
  51753. /**
  51754. * Creates a GPU sampler for the given texture.
  51755. *
  51756. * @param {Texture} texture - The texture to create the sampler for.
  51757. * @return {string} The current sampler key.
  51758. */
  51759. updateSampler( texture ) {
  51760. const backend = this.backend;
  51761. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  51762. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  51763. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  51764. let samplerData = this._samplerCache.get( samplerKey );
  51765. if ( samplerData === undefined ) {
  51766. const samplerDescriptorGPU = {
  51767. addressModeU: this._convertAddressMode( texture.wrapS ),
  51768. addressModeV: this._convertAddressMode( texture.wrapT ),
  51769. addressModeW: this._convertAddressMode( texture.wrapR ),
  51770. magFilter: this._convertFilterMode( texture.magFilter ),
  51771. minFilter: this._convertFilterMode( texture.minFilter ),
  51772. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  51773. maxAnisotropy: 1
  51774. };
  51775. // Depth textures without compare function must use non-filtering (nearest) sampling
  51776. if ( texture.isDepthTexture && texture.compareFunction === null ) {
  51777. samplerDescriptorGPU.magFilter = GPUFilterMode.Nearest;
  51778. samplerDescriptorGPU.minFilter = GPUFilterMode.Nearest;
  51779. samplerDescriptorGPU.mipmapFilter = GPUFilterMode.Nearest;
  51780. }
  51781. // anisotropy can only be used when all filter modes are set to linear.
  51782. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  51783. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  51784. }
  51785. if ( texture.isDepthTexture && texture.compareFunction !== null && backend.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  51786. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  51787. }
  51788. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  51789. samplerData = { sampler, usedTimes: 0 };
  51790. this._samplerCache.set( samplerKey, samplerData );
  51791. }
  51792. const textureData = backend.get( texture );
  51793. if ( textureData.sampler !== samplerData.sampler ) {
  51794. // check if previous sampler is unused so it can be deleted
  51795. if ( textureData.sampler !== undefined ) {
  51796. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  51797. oldSamplerData.usedTimes --;
  51798. if ( oldSamplerData.usedTimes === 0 ) {
  51799. this._samplerCache.delete( textureData.samplerKey );
  51800. }
  51801. }
  51802. // update to new sampler data
  51803. textureData.samplerKey = samplerKey;
  51804. textureData.sampler = samplerData.sampler;
  51805. samplerData.usedTimes ++;
  51806. }
  51807. return samplerKey;
  51808. }
  51809. /**
  51810. * Creates a default texture for the given texture that can be used
  51811. * as a placeholder until the actual texture is ready for usage.
  51812. *
  51813. * @param {Texture} texture - The texture to create a default texture for.
  51814. */
  51815. createDefaultTexture( texture ) {
  51816. let textureGPU;
  51817. const format = getFormat( texture );
  51818. if ( texture.isCubeTexture ) {
  51819. textureGPU = this._getDefaultCubeTextureGPU( format );
  51820. } else {
  51821. textureGPU = this._getDefaultTextureGPU( format );
  51822. }
  51823. this.backend.get( texture ).texture = textureGPU;
  51824. }
  51825. /**
  51826. * Defines a texture on the GPU for the given texture object.
  51827. *
  51828. * @param {Texture} texture - The texture.
  51829. * @param {Object} [options={}] - Optional configuration parameter.
  51830. */
  51831. createTexture( texture, options = {} ) {
  51832. const backend = this.backend;
  51833. const textureData = backend.get( texture );
  51834. if ( textureData.initialized ) {
  51835. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  51836. }
  51837. if ( texture.isExternalTexture ) {
  51838. textureData.texture = texture.sourceTexture;
  51839. textureData.initialized = true;
  51840. return;
  51841. }
  51842. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  51843. if ( options.levels === undefined ) options.levels = 1;
  51844. if ( options.depth === undefined ) options.depth = 1;
  51845. const { width, height, depth, levels } = options;
  51846. if ( texture.isFramebufferTexture ) {
  51847. if ( options.renderTarget ) {
  51848. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  51849. } else {
  51850. options.format = this.backend.utils.getPreferredCanvasFormat();
  51851. }
  51852. }
  51853. const dimension = this._getDimension( texture );
  51854. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  51855. textureData.format = format;
  51856. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  51857. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  51858. if ( texture.isStorageTexture === true ) {
  51859. usage |= GPUTextureUsage.STORAGE_BINDING;
  51860. }
  51861. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  51862. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  51863. }
  51864. const textureDescriptorGPU = {
  51865. label: texture.name,
  51866. size: {
  51867. width: width,
  51868. height: height,
  51869. depthOrArrayLayers: depth,
  51870. },
  51871. mipLevelCount: levels,
  51872. sampleCount: primarySamples,
  51873. dimension: dimension,
  51874. format: format,
  51875. usage: usage
  51876. };
  51877. // texture creation
  51878. if ( format === undefined ) {
  51879. warn( 'WebGPURenderer: Texture format not supported.' );
  51880. this.createDefaultTexture( texture );
  51881. return;
  51882. }
  51883. if ( texture.isCubeTexture ) {
  51884. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  51885. }
  51886. try {
  51887. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  51888. } catch ( e ) {
  51889. warn( 'WebGPURenderer: Failed to create texture with descriptor:', textureDescriptorGPU );
  51890. this.createDefaultTexture( texture );
  51891. return;
  51892. }
  51893. if ( isMSAA ) {
  51894. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  51895. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  51896. msaaTextureDescriptorGPU.sampleCount = samples;
  51897. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  51898. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  51899. }
  51900. textureData.initialized = true;
  51901. textureData.textureDescriptorGPU = textureDescriptorGPU;
  51902. }
  51903. /**
  51904. * Destroys the GPU data for the given texture object.
  51905. *
  51906. * @param {Texture} texture - The texture.
  51907. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  51908. */
  51909. destroyTexture( texture, isDefaultTexture = false ) {
  51910. const backend = this.backend;
  51911. const textureData = backend.get( texture );
  51912. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  51913. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  51914. backend.delete( texture );
  51915. }
  51916. /**
  51917. * Generates mipmaps for the given texture.
  51918. *
  51919. * @param {Texture} texture - The texture.
  51920. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  51921. */
  51922. generateMipmaps( texture, encoder = null ) {
  51923. const textureData = this.backend.get( texture );
  51924. this._generateMipmaps( textureData.texture, encoder );
  51925. }
  51926. /**
  51927. * Returns the color buffer representing the color
  51928. * attachment of the default framebuffer.
  51929. *
  51930. * @return {GPUTexture} The color buffer.
  51931. */
  51932. getColorBuffer() {
  51933. const backend = this.backend;
  51934. const canvasTarget = backend.renderer.getCanvasTarget();
  51935. const { width, height } = backend.getDrawingBufferSize();
  51936. const samples = backend.renderer.currentSamples;
  51937. const colorTexture = canvasTarget.colorTexture;
  51938. const colorTextureData = backend.get( colorTexture );
  51939. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  51940. return colorTextureData.texture;
  51941. }
  51942. // recreate
  51943. let colorBuffer = colorTextureData.texture;
  51944. if ( colorBuffer ) colorBuffer.destroy();
  51945. colorBuffer = backend.device.createTexture( {
  51946. label: 'colorBuffer',
  51947. size: {
  51948. width: width,
  51949. height: height,
  51950. depthOrArrayLayers: 1
  51951. },
  51952. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  51953. format: backend.utils.getPreferredCanvasFormat(),
  51954. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  51955. } );
  51956. //
  51957. colorTexture.source.width = width;
  51958. colorTexture.source.height = height;
  51959. colorTexture.samples = samples;
  51960. colorTextureData.texture = colorBuffer;
  51961. return colorBuffer;
  51962. }
  51963. /**
  51964. * Returns the depth buffer representing the depth
  51965. * attachment of the default framebuffer.
  51966. *
  51967. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  51968. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  51969. * @return {GPUTexture} The depth buffer.
  51970. */
  51971. getDepthBuffer( depth = true, stencil = false ) {
  51972. const backend = this.backend;
  51973. const canvasTarget = backend.renderer.getCanvasTarget();
  51974. const { width, height } = backend.getDrawingBufferSize();
  51975. const samples = backend.renderer.currentSamples;
  51976. const depthTexture = canvasTarget.depthTexture;
  51977. if ( depthTexture.width === width &&
  51978. depthTexture.height === height &&
  51979. depthTexture.samples === samples &&
  51980. depthTexture.depth === depth &&
  51981. depthTexture.stencil === stencil ) {
  51982. return backend.get( depthTexture ).texture;
  51983. }
  51984. //
  51985. const depthTextureGPU = backend.get( depthTexture ).texture;
  51986. let format, type;
  51987. if ( stencil ) {
  51988. format = DepthStencilFormat;
  51989. type = backend.renderer.reversedDepthBuffer === true ? FloatType : UnsignedInt248Type;
  51990. } else if ( depth ) {
  51991. format = DepthFormat;
  51992. type = backend.renderer.reversedDepthBuffer === true ? FloatType : UnsignedIntType;
  51993. }
  51994. if ( depthTextureGPU !== undefined ) {
  51995. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  51996. return depthTextureGPU;
  51997. }
  51998. this.destroyTexture( depthTexture );
  51999. }
  52000. // recreate
  52001. depthTexture.name = 'depthBuffer';
  52002. depthTexture.format = format;
  52003. depthTexture.type = type;
  52004. depthTexture.image.width = width;
  52005. depthTexture.image.height = height;
  52006. depthTexture.samples = samples;
  52007. this.createTexture( depthTexture, { width, height } );
  52008. return backend.get( depthTexture ).texture;
  52009. }
  52010. /**
  52011. * Uploads the updated texture data to the GPU.
  52012. *
  52013. * @param {Texture} texture - The texture.
  52014. * @param {Object} [options={}] - Optional configuration parameter.
  52015. */
  52016. updateTexture( texture, options ) {
  52017. const textureData = this.backend.get( texture );
  52018. const mipmaps = texture.mipmaps;
  52019. const { textureDescriptorGPU } = textureData;
  52020. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  52021. return;
  52022. // transfer texture data
  52023. if ( texture.isDataTexture ) {
  52024. if ( mipmaps.length > 0 ) {
  52025. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  52026. const mipmap = mipmaps[ i ];
  52027. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  52028. }
  52029. } else {
  52030. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  52031. }
  52032. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  52033. if ( texture.layerUpdates && texture.layerUpdates.size > 0 ) {
  52034. for ( const layerIndex of texture.layerUpdates ) {
  52035. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, layerIndex, texture.flipY, layerIndex );
  52036. }
  52037. texture.clearLayerUpdates();
  52038. } else {
  52039. for ( let i = 0; i < options.image.depth; i ++ ) {
  52040. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  52041. }
  52042. }
  52043. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  52044. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  52045. } else if ( texture.isCubeTexture ) {
  52046. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  52047. } else {
  52048. if ( mipmaps.length > 0 ) {
  52049. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  52050. const mipmap = mipmaps[ i ];
  52051. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  52052. }
  52053. } else {
  52054. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  52055. }
  52056. }
  52057. //
  52058. textureData.version = texture.version;
  52059. }
  52060. /**
  52061. * Returns texture data as a typed array.
  52062. *
  52063. * @async
  52064. * @param {Texture} texture - The texture to copy.
  52065. * @param {number} x - The x coordinate of the copy origin.
  52066. * @param {number} y - The y coordinate of the copy origin.
  52067. * @param {number} width - The width of the copy.
  52068. * @param {number} height - The height of the copy.
  52069. * @param {number} faceIndex - The face index.
  52070. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  52071. */
  52072. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  52073. const device = this.backend.device;
  52074. const textureData = this.backend.get( texture );
  52075. const textureGPU = textureData.texture;
  52076. const format = textureData.textureDescriptorGPU.format;
  52077. const bytesPerTexel = this._getBytesPerTexel( format );
  52078. let bytesPerRow = width * bytesPerTexel;
  52079. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  52080. const readBuffer = device.createBuffer(
  52081. {
  52082. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  52083. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  52084. }
  52085. );
  52086. const encoder = device.createCommandEncoder();
  52087. encoder.copyTextureToBuffer(
  52088. {
  52089. texture: textureGPU,
  52090. origin: { x, y, z: faceIndex },
  52091. },
  52092. {
  52093. buffer: readBuffer,
  52094. bytesPerRow: bytesPerRow
  52095. },
  52096. {
  52097. width: width,
  52098. height: height
  52099. }
  52100. );
  52101. const typedArrayType = this._getTypedArrayType( format );
  52102. device.queue.submit( [ encoder.finish() ] );
  52103. await readBuffer.mapAsync( GPUMapMode.READ );
  52104. const buffer = readBuffer.getMappedRange();
  52105. return new typedArrayType( buffer );
  52106. }
  52107. /**
  52108. * Frees all internal resources.
  52109. */
  52110. dispose() {
  52111. this._samplerCache.clear();
  52112. }
  52113. /**
  52114. * Returns the default GPU texture for the given format.
  52115. *
  52116. * @private
  52117. * @param {string} format - The GPU format.
  52118. * @return {GPUTexture} The GPU texture.
  52119. */
  52120. _getDefaultTextureGPU( format ) {
  52121. let defaultTexture = this.defaultTexture[ format ];
  52122. if ( defaultTexture === undefined ) {
  52123. const texture = new Texture();
  52124. texture.minFilter = NearestFilter;
  52125. texture.magFilter = NearestFilter;
  52126. this.createTexture( texture, { width: 1, height: 1, format } );
  52127. this.defaultTexture[ format ] = defaultTexture = texture;
  52128. }
  52129. return this.backend.get( defaultTexture ).texture;
  52130. }
  52131. /**
  52132. * Returns the default GPU cube texture for the given format.
  52133. *
  52134. * @private
  52135. * @param {string} format - The GPU format.
  52136. * @return {GPUTexture} The GPU texture.
  52137. */
  52138. _getDefaultCubeTextureGPU( format ) {
  52139. let defaultCubeTexture = this.defaultCubeTexture[ format ];
  52140. if ( defaultCubeTexture === undefined ) {
  52141. const texture = new CubeTexture();
  52142. texture.minFilter = NearestFilter;
  52143. texture.magFilter = NearestFilter;
  52144. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  52145. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  52146. }
  52147. return this.backend.get( defaultCubeTexture ).texture;
  52148. }
  52149. /**
  52150. * Uploads cube texture image data to the GPU memory.
  52151. *
  52152. * @private
  52153. * @param {CubeTexture} texture - The cube texture.
  52154. * @param {GPUTexture} textureGPU - The GPU texture.
  52155. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  52156. */
  52157. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  52158. const images = texture.images;
  52159. const mipmaps = texture.mipmaps;
  52160. for ( let i = 0; i < 6; i ++ ) {
  52161. const image = images[ i ];
  52162. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  52163. if ( image.isDataTexture ) {
  52164. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  52165. } else {
  52166. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  52167. }
  52168. for ( let j = 0; j < mipmaps.length; j ++ ) {
  52169. const mipmap = mipmaps[ j ];
  52170. const image = mipmap.images[ i ];
  52171. if ( image.isDataTexture ) {
  52172. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  52173. } else {
  52174. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  52175. }
  52176. }
  52177. }
  52178. }
  52179. /**
  52180. * Uploads texture image data to the GPU memory.
  52181. *
  52182. * @private
  52183. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  52184. * @param {GPUTexture} textureGPU - The GPU texture.
  52185. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  52186. * @param {number} originDepth - The origin depth.
  52187. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  52188. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  52189. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  52190. */
  52191. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  52192. const device = this.backend.device;
  52193. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  52194. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  52195. try {
  52196. device.queue.copyExternalImageToTexture(
  52197. {
  52198. source: image,
  52199. flipY: flipY
  52200. }, {
  52201. texture: textureGPU,
  52202. mipLevel: mipLevel,
  52203. origin: { x: 0, y: 0, z: originDepth },
  52204. premultipliedAlpha: premultiplyAlpha
  52205. }, {
  52206. width: width,
  52207. height: height,
  52208. depthOrArrayLayers: 1
  52209. }
  52210. );
  52211. // try/catch has been added to fix bad video frame data on certain devices, see #32391
  52212. } catch ( _ ) {}
  52213. }
  52214. /**
  52215. * Returns the pass utils singleton.
  52216. *
  52217. * @private
  52218. * @return {WebGPUTexturePassUtils} The utils instance.
  52219. */
  52220. _getPassUtils() {
  52221. let passUtils = this._passUtils;
  52222. if ( passUtils === null ) {
  52223. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  52224. }
  52225. return passUtils;
  52226. }
  52227. /**
  52228. * Generates mipmaps for the given GPU texture.
  52229. *
  52230. * @private
  52231. * @param {GPUTexture} textureGPU - The GPU texture object.
  52232. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  52233. */
  52234. _generateMipmaps( textureGPU, encoder = null ) {
  52235. this._getPassUtils().generateMipmaps( textureGPU, encoder );
  52236. }
  52237. /**
  52238. * Flip the contents of the given GPU texture along its vertical axis.
  52239. *
  52240. * @private
  52241. * @param {GPUTexture} textureGPU - The GPU texture object.
  52242. * @param {Object} textureDescriptorGPU - The texture descriptor.
  52243. * @param {number} [originDepth=0] - The origin depth.
  52244. */
  52245. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  52246. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  52247. }
  52248. /**
  52249. * Uploads texture buffer data to the GPU memory.
  52250. *
  52251. * @private
  52252. * @param {Object} image - An object defining the image buffer data.
  52253. * @param {GPUTexture} textureGPU - The GPU texture.
  52254. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  52255. * @param {number} originDepth - The origin depth.
  52256. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  52257. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  52258. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  52259. */
  52260. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  52261. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  52262. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  52263. const device = this.backend.device;
  52264. const data = image.data;
  52265. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  52266. const bytesPerRow = image.width * bytesPerTexel;
  52267. device.queue.writeTexture(
  52268. {
  52269. texture: textureGPU,
  52270. mipLevel: mipLevel,
  52271. origin: { x: 0, y: 0, z: originDepth }
  52272. },
  52273. data,
  52274. {
  52275. offset: image.width * image.height * bytesPerTexel * depth,
  52276. bytesPerRow
  52277. },
  52278. {
  52279. width: image.width,
  52280. height: image.height,
  52281. depthOrArrayLayers: 1
  52282. } );
  52283. if ( flipY === true ) {
  52284. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  52285. }
  52286. }
  52287. /**
  52288. * Uploads compressed texture data to the GPU memory.
  52289. *
  52290. * @private
  52291. * @param {Array<Object>} mipmaps - An array with mipmap data.
  52292. * @param {GPUTexture} textureGPU - The GPU texture.
  52293. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  52294. */
  52295. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  52296. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  52297. const device = this.backend.device;
  52298. const blockData = this._getBlockData( textureDescriptorGPU.format );
  52299. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  52300. for ( let i = 0; i < mipmaps.length; i ++ ) {
  52301. const mipmap = mipmaps[ i ];
  52302. const width = mipmap.width;
  52303. const height = mipmap.height;
  52304. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  52305. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  52306. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  52307. for ( let j = 0; j < depth; j ++ ) {
  52308. device.queue.writeTexture(
  52309. {
  52310. texture: textureGPU,
  52311. mipLevel: i,
  52312. origin: { x: 0, y: 0, z: j }
  52313. },
  52314. mipmap.data,
  52315. {
  52316. offset: j * bytesPerImage,
  52317. bytesPerRow,
  52318. rowsPerImage: Math.ceil( height / blockData.height )
  52319. },
  52320. {
  52321. width: Math.ceil( width / blockData.width ) * blockData.width,
  52322. height: Math.ceil( height / blockData.height ) * blockData.height,
  52323. depthOrArrayLayers: 1
  52324. }
  52325. );
  52326. }
  52327. }
  52328. }
  52329. /**
  52330. * This method is only relevant for compressed texture formats. It returns a block
  52331. * data descriptor for the given GPU compressed texture format.
  52332. *
  52333. * @private
  52334. * @param {string} format - The GPU compressed texture format.
  52335. * @return {Object} The block data descriptor.
  52336. */
  52337. _getBlockData( format ) {
  52338. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  52339. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  52340. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  52341. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  52342. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  52343. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  52344. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  52345. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  52346. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  52347. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  52348. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  52349. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  52350. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  52351. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  52352. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  52353. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  52354. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  52355. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  52356. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  52357. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  52358. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  52359. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  52360. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  52361. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  52362. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  52363. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  52364. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  52365. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  52366. }
  52367. /**
  52368. * Converts the three.js uv wrapping constants to GPU address mode constants.
  52369. *
  52370. * @private
  52371. * @param {number} value - The three.js constant defining a uv wrapping mode.
  52372. * @return {string} The GPU address mode.
  52373. */
  52374. _convertAddressMode( value ) {
  52375. let addressMode = GPUAddressMode.ClampToEdge;
  52376. if ( value === RepeatWrapping ) {
  52377. addressMode = GPUAddressMode.Repeat;
  52378. } else if ( value === MirroredRepeatWrapping ) {
  52379. addressMode = GPUAddressMode.MirrorRepeat;
  52380. }
  52381. return addressMode;
  52382. }
  52383. /**
  52384. * Converts the three.js filter constants to GPU filter constants.
  52385. *
  52386. * @private
  52387. * @param {number} value - The three.js constant defining a filter mode.
  52388. * @return {string} The GPU filter mode.
  52389. */
  52390. _convertFilterMode( value ) {
  52391. let filterMode = GPUFilterMode.Linear;
  52392. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  52393. filterMode = GPUFilterMode.Nearest;
  52394. }
  52395. return filterMode;
  52396. }
  52397. /**
  52398. * Returns the bytes-per-texel value for the given GPU texture format.
  52399. *
  52400. * @private
  52401. * @param {string} format - The GPU texture format.
  52402. * @return {number} The bytes-per-texel.
  52403. */
  52404. _getBytesPerTexel( format ) {
  52405. // 8-bit formats
  52406. if ( format === GPUTextureFormat.R8Unorm ||
  52407. format === GPUTextureFormat.R8Snorm ||
  52408. format === GPUTextureFormat.R8Uint ||
  52409. format === GPUTextureFormat.R8Sint ) return 1;
  52410. // 16-bit formats
  52411. if ( format === GPUTextureFormat.R16Uint ||
  52412. format === GPUTextureFormat.R16Sint ||
  52413. format === GPUTextureFormat.R16Float ||
  52414. format === GPUTextureFormat.RG8Unorm ||
  52415. format === GPUTextureFormat.RG8Snorm ||
  52416. format === GPUTextureFormat.RG8Uint ||
  52417. format === GPUTextureFormat.RG8Sint ) return 2;
  52418. // 32-bit formats
  52419. if ( format === GPUTextureFormat.R32Uint ||
  52420. format === GPUTextureFormat.R32Sint ||
  52421. format === GPUTextureFormat.R32Float ||
  52422. format === GPUTextureFormat.RG16Uint ||
  52423. format === GPUTextureFormat.RG16Sint ||
  52424. format === GPUTextureFormat.RG16Float ||
  52425. format === GPUTextureFormat.RGBA8Unorm ||
  52426. format === GPUTextureFormat.RGBA8UnormSRGB ||
  52427. format === GPUTextureFormat.RGBA8Snorm ||
  52428. format === GPUTextureFormat.RGBA8Uint ||
  52429. format === GPUTextureFormat.RGBA8Sint ||
  52430. format === GPUTextureFormat.BGRA8Unorm ||
  52431. format === GPUTextureFormat.BGRA8UnormSRGB ||
  52432. // Packed 32-bit formats
  52433. format === GPUTextureFormat.RGB9E5UFloat ||
  52434. format === GPUTextureFormat.RGB10A2Unorm ||
  52435. format === GPUTextureFormat.RG11B10UFloat ||
  52436. format === GPUTextureFormat.Depth32Float ||
  52437. format === GPUTextureFormat.Depth24Plus ||
  52438. format === GPUTextureFormat.Depth24PlusStencil8 ||
  52439. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  52440. // 64-bit formats
  52441. if ( format === GPUTextureFormat.RG32Uint ||
  52442. format === GPUTextureFormat.RG32Sint ||
  52443. format === GPUTextureFormat.RG32Float ||
  52444. format === GPUTextureFormat.RGBA16Uint ||
  52445. format === GPUTextureFormat.RGBA16Sint ||
  52446. format === GPUTextureFormat.RGBA16Float ) return 8;
  52447. // 128-bit formats
  52448. if ( format === GPUTextureFormat.RGBA32Uint ||
  52449. format === GPUTextureFormat.RGBA32Sint ||
  52450. format === GPUTextureFormat.RGBA32Float ) return 16;
  52451. }
  52452. /**
  52453. * Returns the corresponding typed array type for the given GPU texture format.
  52454. *
  52455. * @private
  52456. * @param {string} format - The GPU texture format.
  52457. * @return {TypedArray.constructor} The typed array type.
  52458. */
  52459. _getTypedArrayType( format ) {
  52460. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  52461. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  52462. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  52463. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  52464. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  52465. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  52466. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  52467. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  52468. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  52469. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  52470. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  52471. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  52472. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  52473. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  52474. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  52475. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  52476. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  52477. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  52478. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  52479. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  52480. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  52481. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  52482. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  52483. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  52484. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  52485. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  52486. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  52487. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  52488. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  52489. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  52490. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  52491. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  52492. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  52493. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  52494. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  52495. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  52496. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  52497. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  52498. }
  52499. /**
  52500. * Returns the GPU dimensions for the given texture.
  52501. *
  52502. * @private
  52503. * @param {Texture} texture - The texture.
  52504. * @return {string} The GPU dimension.
  52505. */
  52506. _getDimension( texture ) {
  52507. let dimension;
  52508. if ( texture.is3DTexture || texture.isData3DTexture ) {
  52509. dimension = GPUTextureDimension.ThreeD;
  52510. } else {
  52511. dimension = GPUTextureDimension.TwoD;
  52512. }
  52513. return dimension;
  52514. }
  52515. }
  52516. /**
  52517. * Returns the GPU format for the given texture.
  52518. *
  52519. * @param {Texture} texture - The texture.
  52520. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  52521. * It is not necessary to apply the device for most formats.
  52522. * @return {string} The GPU format.
  52523. */
  52524. function getFormat( texture, device = null ) {
  52525. const format = texture.format;
  52526. const type = texture.type;
  52527. const colorSpace = texture.colorSpace;
  52528. const transfer = ColorManagement.getTransfer( colorSpace );
  52529. let formatGPU;
  52530. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  52531. switch ( format ) {
  52532. case RGB_S3TC_DXT1_Format:
  52533. case RGBA_S3TC_DXT1_Format:
  52534. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  52535. break;
  52536. case RGBA_S3TC_DXT3_Format:
  52537. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  52538. break;
  52539. case RGBA_S3TC_DXT5_Format:
  52540. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  52541. break;
  52542. case RED_RGTC1_Format:
  52543. formatGPU = GPUTextureFormat.BC4RUnorm;
  52544. break;
  52545. case SIGNED_RED_RGTC1_Format:
  52546. formatGPU = GPUTextureFormat.BC4RSnorm;
  52547. break;
  52548. case RED_GREEN_RGTC2_Format:
  52549. formatGPU = GPUTextureFormat.BC5RGUnorm;
  52550. break;
  52551. case SIGNED_RED_GREEN_RGTC2_Format:
  52552. formatGPU = GPUTextureFormat.BC5RGSnorm;
  52553. break;
  52554. case RGBA_BPTC_Format:
  52555. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  52556. break;
  52557. case RGB_ETC2_Format:
  52558. case RGB_ETC1_Format:
  52559. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  52560. break;
  52561. case RGBA_ETC2_EAC_Format:
  52562. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  52563. break;
  52564. case R11_EAC_Format:
  52565. formatGPU = GPUTextureFormat.EACR11Unorm;
  52566. break;
  52567. case SIGNED_R11_EAC_Format:
  52568. formatGPU = GPUTextureFormat.EACR11Snorm;
  52569. break;
  52570. case RG11_EAC_Format:
  52571. formatGPU = GPUTextureFormat.EACRG11Unorm;
  52572. break;
  52573. case SIGNED_RG11_EAC_Format:
  52574. formatGPU = GPUTextureFormat.EACRG11Snorm;
  52575. break;
  52576. case RGBA_ASTC_4x4_Format:
  52577. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  52578. break;
  52579. case RGBA_ASTC_5x4_Format:
  52580. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  52581. break;
  52582. case RGBA_ASTC_5x5_Format:
  52583. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  52584. break;
  52585. case RGBA_ASTC_6x5_Format:
  52586. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  52587. break;
  52588. case RGBA_ASTC_6x6_Format:
  52589. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  52590. break;
  52591. case RGBA_ASTC_8x5_Format:
  52592. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  52593. break;
  52594. case RGBA_ASTC_8x6_Format:
  52595. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  52596. break;
  52597. case RGBA_ASTC_8x8_Format:
  52598. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  52599. break;
  52600. case RGBA_ASTC_10x5_Format:
  52601. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  52602. break;
  52603. case RGBA_ASTC_10x6_Format:
  52604. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  52605. break;
  52606. case RGBA_ASTC_10x8_Format:
  52607. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  52608. break;
  52609. case RGBA_ASTC_10x10_Format:
  52610. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  52611. break;
  52612. case RGBA_ASTC_12x10_Format:
  52613. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  52614. break;
  52615. case RGBA_ASTC_12x12_Format:
  52616. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  52617. break;
  52618. case RGBAFormat:
  52619. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  52620. break;
  52621. default:
  52622. error( 'WebGPURenderer: Unsupported texture format.', format );
  52623. }
  52624. } else {
  52625. switch ( format ) {
  52626. case RGBAFormat:
  52627. switch ( type ) {
  52628. case ByteType:
  52629. formatGPU = GPUTextureFormat.RGBA8Snorm;
  52630. break;
  52631. case ShortType:
  52632. formatGPU = GPUTextureFormat.RGBA16Sint;
  52633. break;
  52634. case UnsignedShortType:
  52635. formatGPU = GPUTextureFormat.RGBA16Uint;
  52636. break;
  52637. case UnsignedIntType:
  52638. formatGPU = GPUTextureFormat.RGBA32Uint;
  52639. break;
  52640. case IntType:
  52641. formatGPU = GPUTextureFormat.RGBA32Sint;
  52642. break;
  52643. case UnsignedByteType:
  52644. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  52645. break;
  52646. case HalfFloatType:
  52647. formatGPU = GPUTextureFormat.RGBA16Float;
  52648. break;
  52649. case FloatType:
  52650. formatGPU = GPUTextureFormat.RGBA32Float;
  52651. break;
  52652. default:
  52653. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  52654. }
  52655. break;
  52656. case RGBFormat:
  52657. switch ( type ) {
  52658. case UnsignedInt5999Type:
  52659. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  52660. break;
  52661. case UnsignedInt101111Type:
  52662. formatGPU = GPUTextureFormat.RG11B10UFloat;
  52663. break;
  52664. default:
  52665. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  52666. }
  52667. break;
  52668. case RedFormat:
  52669. switch ( type ) {
  52670. case ByteType:
  52671. formatGPU = GPUTextureFormat.R8Snorm;
  52672. break;
  52673. case ShortType:
  52674. formatGPU = GPUTextureFormat.R16Sint;
  52675. break;
  52676. case UnsignedShortType:
  52677. formatGPU = GPUTextureFormat.R16Uint;
  52678. break;
  52679. case UnsignedIntType:
  52680. formatGPU = GPUTextureFormat.R32Uint;
  52681. break;
  52682. case IntType:
  52683. formatGPU = GPUTextureFormat.R32Sint;
  52684. break;
  52685. case UnsignedByteType:
  52686. formatGPU = GPUTextureFormat.R8Unorm;
  52687. break;
  52688. case HalfFloatType:
  52689. formatGPU = GPUTextureFormat.R16Float;
  52690. break;
  52691. case FloatType:
  52692. formatGPU = GPUTextureFormat.R32Float;
  52693. break;
  52694. default:
  52695. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  52696. }
  52697. break;
  52698. case RGFormat:
  52699. switch ( type ) {
  52700. case ByteType:
  52701. formatGPU = GPUTextureFormat.RG8Snorm;
  52702. break;
  52703. case ShortType:
  52704. formatGPU = GPUTextureFormat.RG16Sint;
  52705. break;
  52706. case UnsignedShortType:
  52707. formatGPU = GPUTextureFormat.RG16Uint;
  52708. break;
  52709. case UnsignedIntType:
  52710. formatGPU = GPUTextureFormat.RG32Uint;
  52711. break;
  52712. case IntType:
  52713. formatGPU = GPUTextureFormat.RG32Sint;
  52714. break;
  52715. case UnsignedByteType:
  52716. formatGPU = GPUTextureFormat.RG8Unorm;
  52717. break;
  52718. case HalfFloatType:
  52719. formatGPU = GPUTextureFormat.RG16Float;
  52720. break;
  52721. case FloatType:
  52722. formatGPU = GPUTextureFormat.RG32Float;
  52723. break;
  52724. default:
  52725. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  52726. }
  52727. break;
  52728. case DepthFormat:
  52729. switch ( type ) {
  52730. case UnsignedShortType:
  52731. formatGPU = GPUTextureFormat.Depth16Unorm;
  52732. break;
  52733. case UnsignedIntType:
  52734. formatGPU = GPUTextureFormat.Depth24Plus;
  52735. break;
  52736. case FloatType:
  52737. formatGPU = GPUTextureFormat.Depth32Float;
  52738. break;
  52739. default:
  52740. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  52741. }
  52742. break;
  52743. case DepthStencilFormat:
  52744. switch ( type ) {
  52745. case UnsignedInt248Type:
  52746. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  52747. break;
  52748. case FloatType:
  52749. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  52750. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  52751. }
  52752. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  52753. break;
  52754. default:
  52755. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  52756. }
  52757. break;
  52758. case RedIntegerFormat:
  52759. switch ( type ) {
  52760. case IntType:
  52761. formatGPU = GPUTextureFormat.R32Sint;
  52762. break;
  52763. case UnsignedIntType:
  52764. formatGPU = GPUTextureFormat.R32Uint;
  52765. break;
  52766. default:
  52767. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  52768. }
  52769. break;
  52770. case RGIntegerFormat:
  52771. switch ( type ) {
  52772. case IntType:
  52773. formatGPU = GPUTextureFormat.RG32Sint;
  52774. break;
  52775. case UnsignedIntType:
  52776. formatGPU = GPUTextureFormat.RG32Uint;
  52777. break;
  52778. default:
  52779. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  52780. }
  52781. break;
  52782. case RGBAIntegerFormat:
  52783. switch ( type ) {
  52784. case IntType:
  52785. formatGPU = GPUTextureFormat.RGBA32Sint;
  52786. break;
  52787. case UnsignedIntType:
  52788. formatGPU = GPUTextureFormat.RGBA32Uint;
  52789. break;
  52790. default:
  52791. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  52792. }
  52793. break;
  52794. default:
  52795. error( 'WebGPURenderer: Unsupported texture format.', format );
  52796. }
  52797. }
  52798. return formatGPU;
  52799. }
  52800. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  52801. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  52802. const wgslTypeLib$1 = {
  52803. 'f32': 'float',
  52804. 'i32': 'int',
  52805. 'u32': 'uint',
  52806. 'bool': 'bool',
  52807. 'vec2<f32>': 'vec2',
  52808. 'vec2<i32>': 'ivec2',
  52809. 'vec2<u32>': 'uvec2',
  52810. 'vec2<bool>': 'bvec2',
  52811. 'vec2f': 'vec2',
  52812. 'vec2i': 'ivec2',
  52813. 'vec2u': 'uvec2',
  52814. 'vec2b': 'bvec2',
  52815. 'vec3<f32>': 'vec3',
  52816. 'vec3<i32>': 'ivec3',
  52817. 'vec3<u32>': 'uvec3',
  52818. 'vec3<bool>': 'bvec3',
  52819. 'vec3f': 'vec3',
  52820. 'vec3i': 'ivec3',
  52821. 'vec3u': 'uvec3',
  52822. 'vec3b': 'bvec3',
  52823. 'vec4<f32>': 'vec4',
  52824. 'vec4<i32>': 'ivec4',
  52825. 'vec4<u32>': 'uvec4',
  52826. 'vec4<bool>': 'bvec4',
  52827. 'vec4f': 'vec4',
  52828. 'vec4i': 'ivec4',
  52829. 'vec4u': 'uvec4',
  52830. 'vec4b': 'bvec4',
  52831. 'mat2x2<f32>': 'mat2',
  52832. 'mat2x2f': 'mat2',
  52833. 'mat3x3<f32>': 'mat3',
  52834. 'mat3x3f': 'mat3',
  52835. 'mat4x4<f32>': 'mat4',
  52836. 'mat4x4f': 'mat4',
  52837. 'sampler': 'sampler',
  52838. 'texture_1d': 'texture',
  52839. 'texture_2d': 'texture',
  52840. 'texture_2d_array': 'texture',
  52841. 'texture_multisampled_2d': 'cubeTexture',
  52842. 'texture_depth_2d': 'depthTexture',
  52843. 'texture_depth_2d_array': 'depthTexture',
  52844. 'texture_depth_multisampled_2d': 'depthTexture',
  52845. 'texture_depth_cube': 'depthTexture',
  52846. 'texture_depth_cube_array': 'depthTexture',
  52847. 'texture_3d': 'texture3D',
  52848. 'texture_cube': 'cubeTexture',
  52849. 'texture_cube_array': 'cubeTexture',
  52850. 'texture_storage_1d': 'storageTexture',
  52851. 'texture_storage_2d': 'storageTexture',
  52852. 'texture_storage_2d_array': 'storageTexture',
  52853. 'texture_storage_3d': 'storageTexture'
  52854. };
  52855. const parse = ( source ) => {
  52856. source = source.trim();
  52857. const declaration = source.match( declarationRegexp );
  52858. if ( declaration !== null && declaration.length === 4 ) {
  52859. const inputsCode = declaration[ 2 ];
  52860. const propsMatches = [];
  52861. let match = null;
  52862. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  52863. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  52864. }
  52865. // Process matches to correctly pair names and types
  52866. const inputs = [];
  52867. for ( let i = 0; i < propsMatches.length; i ++ ) {
  52868. const { name, type } = propsMatches[ i ];
  52869. let resolvedType = type;
  52870. if ( resolvedType.startsWith( 'ptr' ) ) {
  52871. resolvedType = 'pointer';
  52872. } else {
  52873. if ( resolvedType.startsWith( 'texture' ) ) {
  52874. resolvedType = type.split( '<' )[ 0 ];
  52875. }
  52876. resolvedType = wgslTypeLib$1[ resolvedType ];
  52877. }
  52878. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  52879. }
  52880. const blockCode = source.substring( declaration[ 0 ].length );
  52881. const outputType = declaration[ 3 ] || 'void';
  52882. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  52883. const type = wgslTypeLib$1[ outputType ] || outputType;
  52884. return {
  52885. type,
  52886. inputs,
  52887. name,
  52888. inputsCode,
  52889. blockCode,
  52890. outputType
  52891. };
  52892. } else {
  52893. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  52894. }
  52895. };
  52896. /**
  52897. * This class represents a WSL node function.
  52898. *
  52899. * @augments NodeFunction
  52900. */
  52901. class WGSLNodeFunction extends NodeFunction {
  52902. /**
  52903. * Constructs a new WGSL node function.
  52904. *
  52905. * @param {string} source - The WGSL source.
  52906. */
  52907. constructor( source ) {
  52908. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  52909. super( type, inputs, name );
  52910. this.inputsCode = inputsCode;
  52911. this.blockCode = blockCode;
  52912. this.outputType = outputType;
  52913. }
  52914. /**
  52915. * This method returns the WGSL code of the node function.
  52916. *
  52917. * @param {string} [name=this.name] - The function's name.
  52918. * @return {string} The shader code.
  52919. */
  52920. getCode( name = this.name ) {
  52921. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  52922. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  52923. }
  52924. }
  52925. /**
  52926. * A WGSL node parser.
  52927. *
  52928. * @augments NodeParser
  52929. */
  52930. class WGSLNodeParser extends NodeParser {
  52931. /**
  52932. * The method parses the given WGSL code an returns a node function.
  52933. *
  52934. * @param {string} source - The WGSL code.
  52935. * @return {WGSLNodeFunction} A node function.
  52936. */
  52937. parseFunction( source ) {
  52938. return new WGSLNodeFunction( source );
  52939. }
  52940. }
  52941. const accessNames = {
  52942. [ NodeAccess.READ_ONLY ]: 'read',
  52943. [ NodeAccess.WRITE_ONLY ]: 'write',
  52944. [ NodeAccess.READ_WRITE ]: 'read_write'
  52945. };
  52946. const wrapNames = {
  52947. [ RepeatWrapping ]: 'repeat',
  52948. [ ClampToEdgeWrapping ]: 'clamp',
  52949. [ MirroredRepeatWrapping ]: 'mirror'
  52950. };
  52951. const gpuShaderStageLib = {
  52952. 'vertex': GPUShaderStage.VERTEX,
  52953. 'fragment': GPUShaderStage.FRAGMENT,
  52954. 'compute': GPUShaderStage.COMPUTE
  52955. };
  52956. const supports = {
  52957. instance: true,
  52958. swizzleAssign: false,
  52959. storageBuffer: true
  52960. };
  52961. const wgslFnOpLib = {
  52962. '^^': 'tsl_xor'
  52963. };
  52964. const wgslTypeLib = {
  52965. float: 'f32',
  52966. int: 'i32',
  52967. uint: 'u32',
  52968. bool: 'bool',
  52969. color: 'vec3<f32>',
  52970. vec2: 'vec2<f32>',
  52971. ivec2: 'vec2<i32>',
  52972. uvec2: 'vec2<u32>',
  52973. bvec2: 'vec2<bool>',
  52974. vec3: 'vec3<f32>',
  52975. ivec3: 'vec3<i32>',
  52976. uvec3: 'vec3<u32>',
  52977. bvec3: 'vec3<bool>',
  52978. vec4: 'vec4<f32>',
  52979. ivec4: 'vec4<i32>',
  52980. uvec4: 'vec4<u32>',
  52981. bvec4: 'vec4<bool>',
  52982. mat2: 'mat2x2<f32>',
  52983. mat3: 'mat3x3<f32>',
  52984. mat4: 'mat4x4<f32>'
  52985. };
  52986. const wgslCodeCache = {};
  52987. const wgslPolyfill = {
  52988. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  52989. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  52990. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  52991. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  52992. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  52993. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  52994. 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 ); }' ),
  52995. 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 ); }' ),
  52996. 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 ); }' ),
  52997. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  52998. 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 ); }' ),
  52999. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  53000. biquadraticTexture: new CodeNode( /* wgsl */`
  53001. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  53002. let res = vec2f( iRes );
  53003. let uvScaled = coord * res;
  53004. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  53005. // https://www.shadertoy.com/view/WtyXRy
  53006. let uv = uvWrapping - 0.5;
  53007. let iuv = floor( uv );
  53008. let f = fract( uv );
  53009. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  53010. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  53011. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  53012. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  53013. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  53014. }
  53015. ` ),
  53016. biquadraticTextureArray: new CodeNode( /* wgsl */`
  53017. fn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {
  53018. let res = vec2f( iRes );
  53019. let uvScaled = coord * res;
  53020. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  53021. // https://www.shadertoy.com/view/WtyXRy
  53022. let uv = uvWrapping - 0.5;
  53023. let iuv = floor( uv );
  53024. let f = fract( uv );
  53025. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );
  53026. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );
  53027. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );
  53028. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );
  53029. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  53030. }
  53031. ` )
  53032. };
  53033. const wgslMethods = {
  53034. dFdx: 'dpdx',
  53035. dFdy: '- dpdy',
  53036. mod_float: 'tsl_mod_float',
  53037. mod_vec2: 'tsl_mod_vec2',
  53038. mod_vec3: 'tsl_mod_vec3',
  53039. mod_vec4: 'tsl_mod_vec4',
  53040. equals_bool: 'tsl_equals_bool',
  53041. equals_bvec2: 'tsl_equals_bvec2',
  53042. equals_bvec3: 'tsl_equals_bvec3',
  53043. equals_bvec4: 'tsl_equals_bvec4',
  53044. inversesqrt: 'inverseSqrt',
  53045. bitcast: 'bitcast<f32>',
  53046. floatpack_snorm_2x16: 'pack2x16snorm',
  53047. floatpack_unorm_2x16: 'pack2x16unorm',
  53048. floatpack_float16_2x16: 'pack2x16float',
  53049. floatunpack_snorm_2x16: 'unpack2x16snorm',
  53050. floatunpack_unorm_2x16: 'unpack2x16unorm',
  53051. floatunpack_float16_2x16: 'unpack2x16float'
  53052. };
  53053. //
  53054. let diagnostics = '';
  53055. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  53056. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  53057. }
  53058. /**
  53059. * A node builder targeting WGSL.
  53060. *
  53061. * This module generates WGSL shader code from node materials and also
  53062. * generates the respective bindings and vertex buffer definitions. These
  53063. * data are later used by the renderer to create render and compute pipelines
  53064. * for render objects.
  53065. *
  53066. * @augments NodeBuilder
  53067. */
  53068. class WGSLNodeBuilder extends NodeBuilder {
  53069. /**
  53070. * Constructs a new WGSL node builder renderer.
  53071. *
  53072. * @param {Object3D} object - The 3D object.
  53073. * @param {Renderer} renderer - The renderer.
  53074. */
  53075. constructor( object, renderer ) {
  53076. super( object, renderer, new WGSLNodeParser() );
  53077. /**
  53078. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  53079. * another dictionary which manages UBOs per group ('render','frame','object').
  53080. *
  53081. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  53082. */
  53083. this.uniformGroups = {};
  53084. /**
  53085. * A dictionary that holds the assigned binding indices for each uniform group.
  53086. * This ensures the same binding index is used across all shader stages.
  53087. *
  53088. * @type {Object<string,{index: number, id: number}>}
  53089. */
  53090. this.uniformGroupsBindings = {};
  53091. /**
  53092. * A dictionary that holds for each shader stage a Map of builtins.
  53093. *
  53094. * @type {Object<string,Map<string,Object>>}
  53095. */
  53096. this.builtins = {};
  53097. /**
  53098. * A dictionary that holds for each shader stage a Set of directives.
  53099. *
  53100. * @type {Object<string,Set<string>>}
  53101. */
  53102. this.directives = {};
  53103. /**
  53104. * A map for managing scope arrays. Only relevant for when using
  53105. * {@link WorkgroupInfoNode} in context of compute shaders.
  53106. *
  53107. * @type {Map<string,Object>}
  53108. */
  53109. this.scopedArrays = new Map();
  53110. /**
  53111. * A flag that indicates that early returns are allowed.
  53112. *
  53113. * @type {boolean}
  53114. * @default true
  53115. */
  53116. this.allowEarlyReturns = true;
  53117. }
  53118. /**
  53119. * Generates the WGSL snippet for sampled textures.
  53120. *
  53121. * @private
  53122. * @param {Texture} texture - The texture.
  53123. * @param {string} textureProperty - The name of the texture uniform in the shader.
  53124. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  53125. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  53126. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  53127. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  53128. * @return {string} The WGSL snippet.
  53129. */
  53130. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  53131. if ( shaderStage === 'fragment' ) {
  53132. if ( depthSnippet ) {
  53133. if ( offsetSnippet ) {
  53134. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  53135. }
  53136. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  53137. } else {
  53138. if ( offsetSnippet ) {
  53139. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  53140. }
  53141. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  53142. }
  53143. } else {
  53144. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  53145. }
  53146. }
  53147. /**
  53148. * Generates the WGSL snippet when sampling textures with explicit mip level.
  53149. *
  53150. * @private
  53151. * @param {Texture} texture - The texture.
  53152. * @param {string} textureProperty - The name of the texture uniform in the shader.
  53153. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  53154. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  53155. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  53156. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  53157. * @return {string} The WGSL snippet.
  53158. */
  53159. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  53160. if ( this.isUnfilterable( texture ) === false ) {
  53161. if ( depthSnippet ) {
  53162. if ( offsetSnippet ) {
  53163. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  53164. }
  53165. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  53166. } else {
  53167. if ( offsetSnippet ) {
  53168. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  53169. }
  53170. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  53171. }
  53172. } else if ( this.isFilteredTexture( texture ) ) {
  53173. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet, depthSnippet );
  53174. } else {
  53175. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  53176. }
  53177. }
  53178. /**
  53179. * Generates a wrap function used in context of textures.
  53180. *
  53181. * @param {Texture} texture - The texture to generate the function for.
  53182. * @return {string} The name of the generated function.
  53183. */
  53184. generateWrapFunction( texture ) {
  53185. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.is3DTexture || texture.isData3DTexture ? '3d' : '2d' }T`;
  53186. let nodeCode = wgslCodeCache[ functionName ];
  53187. if ( nodeCode === undefined ) {
  53188. const includes = [];
  53189. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  53190. const coordType = texture.is3DTexture || texture.isData3DTexture ? 'vec3f' : 'vec2f';
  53191. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  53192. const addWrapSnippet = ( wrap, axis ) => {
  53193. if ( wrap === RepeatWrapping ) {
  53194. includes.push( wgslPolyfill.repeatWrapping_float );
  53195. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  53196. } else if ( wrap === ClampToEdgeWrapping ) {
  53197. includes.push( wgslPolyfill.clampWrapping_float );
  53198. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  53199. } else if ( wrap === MirroredRepeatWrapping ) {
  53200. includes.push( wgslPolyfill.mirrorWrapping_float );
  53201. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  53202. } else {
  53203. code += `\t\tcoord.${ axis }`;
  53204. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  53205. }
  53206. };
  53207. addWrapSnippet( texture.wrapS, 'x' );
  53208. code += ',\n';
  53209. addWrapSnippet( texture.wrapT, 'y' );
  53210. if ( texture.is3DTexture || texture.isData3DTexture ) {
  53211. code += ',\n';
  53212. addWrapSnippet( texture.wrapR, 'z' );
  53213. }
  53214. code += '\n\t);\n\n}\n';
  53215. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  53216. }
  53217. nodeCode.build( this );
  53218. return functionName;
  53219. }
  53220. /**
  53221. * Generates the array declaration string.
  53222. *
  53223. * @param {string} type - The type.
  53224. * @param {?number} [count] - The count.
  53225. * @return {string} The generated value as a shader string.
  53226. */
  53227. generateArrayDeclaration( type, count ) {
  53228. return `array< ${ this.getType( type ) }, ${ count } >`;
  53229. }
  53230. /**
  53231. * Generates a WGSL variable that holds the texture dimension of the given texture.
  53232. * It also returns information about the number of layers (elements) of an arrayed
  53233. * texture as well as the cube face count of cube textures.
  53234. *
  53235. * @param {Texture} texture - The texture to generate the function for.
  53236. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  53237. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  53238. * @return {string} The name of the dimension variable.
  53239. */
  53240. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  53241. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  53242. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  53243. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  53244. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  53245. let textureDimensionsParams;
  53246. let dimensionType;
  53247. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  53248. const isMultisampled = primarySamples > 1;
  53249. if ( texture.is3DTexture || texture.isData3DTexture ) {
  53250. dimensionType = 'vec3<u32>';
  53251. } else {
  53252. // Regular 2D textures, depth textures, etc.
  53253. dimensionType = 'vec2<u32>';
  53254. }
  53255. // Build parameters string based on texture type and multisampling
  53256. if ( isMultisampled || texture.isStorageTexture ) {
  53257. textureDimensionsParams = textureProperty;
  53258. } else {
  53259. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  53260. }
  53261. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  53262. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  53263. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.is3DTexture || texture.isData3DTexture ) {
  53264. textureData.arrayLayerCount = new VarNode(
  53265. new ExpressionNode(
  53266. `textureNumLayers(${textureProperty})`,
  53267. 'u32'
  53268. )
  53269. );
  53270. }
  53271. // For cube textures, we know it's always 6 faces
  53272. if ( texture.isTextureCube ) {
  53273. textureData.cubeFaceCount = new VarNode(
  53274. new ExpressionNode( '6u', 'u32' )
  53275. );
  53276. }
  53277. }
  53278. return textureDimensionNode.build( this );
  53279. }
  53280. /**
  53281. * Generates the WGSL snippet for a manual filtered texture.
  53282. *
  53283. * @param {Texture} texture - The texture.
  53284. * @param {string} textureProperty - The name of the texture uniform in the shader.
  53285. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  53286. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  53287. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  53288. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  53289. * @return {string} The WGSL snippet.
  53290. */
  53291. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u', depthSnippet ) {
  53292. const wrapFunction = this.generateWrapFunction( texture );
  53293. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  53294. if ( offsetSnippet ) {
  53295. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  53296. }
  53297. if ( depthSnippet ) {
  53298. this._include( 'biquadraticTextureArray' );
  53299. return `tsl_biquadraticTexture_array( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ depthSnippet } ), u32( ${ levelSnippet } ) )`;
  53300. }
  53301. this._include( 'biquadraticTexture' );
  53302. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  53303. }
  53304. /**
  53305. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  53306. * Since it's a lookup, no sampling or filtering is applied.
  53307. *
  53308. * @param {Texture} texture - The texture.
  53309. * @param {string} textureProperty - The name of the texture uniform in the shader.
  53310. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  53311. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  53312. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  53313. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  53314. * @return {string} The WGSL snippet.
  53315. */
  53316. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  53317. // Cube textures cannot use textureLoad in WGSL, must use textureSampleLevel
  53318. if ( texture.isCubeTexture === true ) {
  53319. if ( offsetSnippet ) {
  53320. uvSnippet = `${ uvSnippet } + vec3<f32>(${ offsetSnippet })`;
  53321. }
  53322. // Depth textures require integer level, regular textures use float
  53323. const levelType = texture.isDepthTexture ? 'u32' : 'f32';
  53324. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelType }( ${ levelSnippet } ) )`;
  53325. }
  53326. const wrapFunction = this.generateWrapFunction( texture );
  53327. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  53328. const vecType = texture.is3DTexture || texture.isData3DTexture ? 'vec3' : 'vec2';
  53329. const textureDimensionMargin = ( vecType === 'vec3' ) ? 'vec3<u32>( 1, 1, 1 )' : 'vec2<u32>( 1, 1 )';
  53330. if ( offsetSnippet ) {
  53331. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  53332. }
  53333. const clampMin = `${ vecType }<f32>( 0 )`;
  53334. const clampMax = `${ vecType }<f32>( ${ textureDimension } - ${ textureDimensionMargin } )`;
  53335. uvSnippet = `${ vecType }<u32>( clamp( floor( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) ), ${ clampMin }, ${ clampMax } ) )`;
  53336. return this.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, null );
  53337. }
  53338. /**
  53339. * Generates the WGSL snippet that reads a single texel from a storage texture.
  53340. *
  53341. * @param {Texture} texture - The texture.
  53342. * @param {string} textureProperty - The name of the texture uniform in the shader.
  53343. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  53344. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  53345. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  53346. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  53347. * @return {string} The WGSL snippet.
  53348. */
  53349. generateStorageTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  53350. if ( offsetSnippet ) {
  53351. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  53352. }
  53353. let snippet;
  53354. if ( depthSnippet ) {
  53355. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet } )`;
  53356. } else {
  53357. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  53358. }
  53359. return snippet;
  53360. }
  53361. /**
  53362. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  53363. *
  53364. * @param {Texture} texture - The texture.
  53365. * @param {string} textureProperty - The name of the texture uniform in the shader.
  53366. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  53367. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  53368. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  53369. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  53370. * @return {string} The WGSL snippet.
  53371. */
  53372. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  53373. if ( levelSnippet === null ) levelSnippet = '0u';
  53374. if ( offsetSnippet ) {
  53375. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  53376. }
  53377. let snippet;
  53378. if ( depthSnippet ) {
  53379. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  53380. } else {
  53381. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  53382. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  53383. snippet += '.x';
  53384. }
  53385. }
  53386. return snippet;
  53387. }
  53388. /**
  53389. * Generates the WGSL snippet that writes a single texel to a texture.
  53390. *
  53391. * @param {Texture} texture - The texture.
  53392. * @param {string} textureProperty - The name of the texture uniform in the shader.
  53393. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  53394. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  53395. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  53396. * @return {string} The WGSL snippet.
  53397. */
  53398. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  53399. let snippet;
  53400. if ( depthSnippet ) {
  53401. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  53402. } else {
  53403. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  53404. }
  53405. return snippet;
  53406. }
  53407. /**
  53408. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  53409. *
  53410. * @param {Texture} texture - The texture.
  53411. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  53412. */
  53413. isSampleCompare( texture ) {
  53414. return texture.isDepthTexture === true && texture.compareFunction !== null && this.renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE );
  53415. }
  53416. /**
  53417. * Returns `true` if the given texture is unfilterable.
  53418. *
  53419. * @param {Texture} texture - The texture.
  53420. * @return {boolean} Whether the given texture is unfilterable or not.
  53421. */
  53422. isUnfilterable( texture ) {
  53423. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  53424. ( ! this.isAvailable( 'float32Filterable' ) && texture.type === FloatType ) ||
  53425. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  53426. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  53427. }
  53428. /**
  53429. * Generates the WGSL snippet for sampling/loading the given texture.
  53430. *
  53431. * @param {Texture} texture - The texture.
  53432. * @param {string} textureProperty - The name of the texture uniform in the shader.
  53433. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  53434. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  53435. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  53436. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  53437. * @return {string} The WGSL snippet.
  53438. */
  53439. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  53440. let snippet = null;
  53441. if ( this.isUnfilterable( texture ) ) {
  53442. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  53443. } else {
  53444. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  53445. }
  53446. return snippet;
  53447. }
  53448. /**
  53449. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  53450. *
  53451. * @param {Texture} texture - The texture.
  53452. * @param {string} textureProperty - The name of the texture uniform in the shader.
  53453. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  53454. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  53455. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  53456. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  53457. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  53458. * @return {string} The WGSL snippet.
  53459. */
  53460. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  53461. if ( shaderStage === 'fragment' ) {
  53462. if ( depthSnippet ) {
  53463. if ( offsetSnippet ) {
  53464. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  53465. }
  53466. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  53467. } else {
  53468. if ( offsetSnippet ) {
  53469. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  53470. }
  53471. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  53472. }
  53473. } else {
  53474. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  53475. }
  53476. }
  53477. /**
  53478. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  53479. * against a reference value.
  53480. *
  53481. * @param {Texture} texture - The texture.
  53482. * @param {string} textureProperty - The name of the texture uniform in the shader.
  53483. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  53484. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  53485. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  53486. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  53487. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  53488. * @return {string} The WGSL snippet.
  53489. */
  53490. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  53491. if ( shaderStage === 'fragment' ) {
  53492. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  53493. if ( offsetSnippet ) {
  53494. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  53495. }
  53496. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  53497. }
  53498. if ( offsetSnippet ) {
  53499. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  53500. }
  53501. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  53502. } else {
  53503. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  53504. }
  53505. }
  53506. /**
  53507. * Generates the WGSL snippet when sampling textures with explicit mip level.
  53508. *
  53509. * @param {Texture} texture - The texture.
  53510. * @param {string} textureProperty - The name of the texture uniform in the shader.
  53511. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  53512. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  53513. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  53514. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  53515. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  53516. * @return {string} The WGSL snippet.
  53517. */
  53518. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  53519. if ( this.isUnfilterable( texture ) === false ) {
  53520. if ( depthSnippet ) {
  53521. if ( offsetSnippet ) {
  53522. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  53523. }
  53524. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  53525. } else {
  53526. if ( offsetSnippet ) {
  53527. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  53528. }
  53529. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  53530. }
  53531. } else if ( this.isFilteredTexture( texture ) ) {
  53532. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet, depthSnippet );
  53533. } else {
  53534. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  53535. }
  53536. }
  53537. /**
  53538. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  53539. *
  53540. * @param {Texture} texture - The texture.
  53541. * @param {string} textureProperty - The name of the texture uniform in the shader.
  53542. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  53543. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  53544. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  53545. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  53546. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  53547. * @return {string} The WGSL snippet.
  53548. */
  53549. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  53550. if ( shaderStage === 'fragment' ) {
  53551. if ( depthSnippet ) {
  53552. if ( offsetSnippet ) {
  53553. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  53554. }
  53555. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ biasSnippet } )`;
  53556. } else {
  53557. if ( offsetSnippet ) {
  53558. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  53559. }
  53560. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  53561. }
  53562. } else {
  53563. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  53564. }
  53565. }
  53566. /**
  53567. * Returns a WGSL snippet that represents the property name of the given node.
  53568. *
  53569. * @param {Node} node - The node.
  53570. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  53571. * @return {string} The property name.
  53572. */
  53573. getPropertyName( node, shaderStage = this.shaderStage ) {
  53574. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  53575. if ( shaderStage === 'vertex' ) {
  53576. return `varyings.${ node.name }`;
  53577. }
  53578. } else if ( node.isNodeUniform === true ) {
  53579. const name = node.name;
  53580. const type = node.type;
  53581. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  53582. return name;
  53583. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  53584. if ( this.isCustomStruct( node ) ) {
  53585. return name;
  53586. }
  53587. return name + '.value';
  53588. } else {
  53589. return node.groupNode.name + '.' + name;
  53590. }
  53591. }
  53592. return super.getPropertyName( node );
  53593. }
  53594. /**
  53595. * Returns the output struct name.
  53596. *
  53597. * @return {string} The name of the output struct.
  53598. */
  53599. getOutputStructName() {
  53600. return 'output';
  53601. }
  53602. /**
  53603. * Returns the native shader operator name for a given generic name.
  53604. *
  53605. * @param {string} op - The operator name to resolve.
  53606. * @return {?string} The resolved operator name.
  53607. */
  53608. getFunctionOperator( op ) {
  53609. const fnOp = wgslFnOpLib[ op ];
  53610. if ( fnOp !== undefined ) {
  53611. this._include( fnOp );
  53612. return fnOp;
  53613. }
  53614. return null;
  53615. }
  53616. /**
  53617. * Returns the node access for the given node and shader stage.
  53618. *
  53619. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  53620. * @param {string} shaderStage - The shader stage.
  53621. * @return {string} The node access.
  53622. */
  53623. getNodeAccess( node, shaderStage ) {
  53624. if ( shaderStage !== 'compute' ) {
  53625. if ( node.isAtomic === true ) {
  53626. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  53627. return NodeAccess.READ_WRITE;
  53628. }
  53629. return NodeAccess.READ_ONLY;
  53630. }
  53631. return node.access;
  53632. }
  53633. /**
  53634. * Returns A WGSL snippet representing the storage access.
  53635. *
  53636. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  53637. * @param {string} shaderStage - The shader stage.
  53638. * @return {string} The WGSL snippet representing the storage access.
  53639. */
  53640. getStorageAccess( node, shaderStage ) {
  53641. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  53642. }
  53643. /**
  53644. * This method is one of the more important ones since it's responsible
  53645. * for generating a matching binding instance for the given uniform node.
  53646. *
  53647. * These bindings are later used in the renderer to create bind groups
  53648. * and layouts.
  53649. *
  53650. * @param {UniformNode} node - The uniform node.
  53651. * @param {string} type - The node data type.
  53652. * @param {string} shaderStage - The shader stage.
  53653. * @param {?string} [name=null] - An optional uniform name.
  53654. * @return {NodeUniform} The node uniform object.
  53655. */
  53656. getUniformFromNode( node, type, shaderStage, name = null ) {
  53657. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  53658. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  53659. if ( nodeData.uniformGPU === undefined ) {
  53660. let uniformGPU;
  53661. const group = node.groupNode;
  53662. const groupName = group.name;
  53663. const bindings = this.getBindGroupArray( groupName, shaderStage );
  53664. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  53665. let texture = null;
  53666. const access = this.getNodeAccess( node, shaderStage );
  53667. if ( type === 'texture' || type === 'storageTexture' ) {
  53668. if ( node.value.is3DTexture === true ) {
  53669. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  53670. } else {
  53671. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  53672. }
  53673. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  53674. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  53675. } else if ( type === 'texture3D' ) {
  53676. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  53677. }
  53678. texture.store = node.isStorageTextureNode === true;
  53679. texture.mipLevel = texture.store ? node.mipLevel : 0;
  53680. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  53681. // Cube textures always need samplers (they use textureSampleLevel, not textureLoad)
  53682. const needsSampler = node.value.isCubeTexture === true || ( this.isUnfilterable( node.value ) === false && texture.store === false );
  53683. if ( needsSampler ) {
  53684. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  53685. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  53686. bindings.push( sampler, texture );
  53687. uniformGPU = [ sampler, texture ];
  53688. } else {
  53689. bindings.push( texture );
  53690. uniformGPU = [ texture ];
  53691. }
  53692. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  53693. const sharedData = this.getSharedDataFromNode( node );
  53694. let buffer = sharedData.buffer;
  53695. if ( buffer === undefined ) {
  53696. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  53697. buffer = new bufferClass( node, group );
  53698. sharedData.buffer = buffer;
  53699. }
  53700. buffer.setVisibility( buffer.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  53701. bindings.push( buffer );
  53702. uniformGPU = buffer;
  53703. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  53704. } else {
  53705. let uniformsGroup = this.uniformGroups[ groupName ];
  53706. if ( uniformsGroup === undefined ) {
  53707. uniformsGroup = new NodeUniformsGroup( groupName, group );
  53708. uniformsGroup.setVisibility( GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT | GPUShaderStage.COMPUTE );
  53709. this.uniformGroups[ groupName ] = uniformsGroup;
  53710. }
  53711. // Add to bindings for this stage if not already present
  53712. if ( bindings.indexOf( uniformsGroup ) === -1 ) {
  53713. bindings.push( uniformsGroup );
  53714. }
  53715. uniformGPU = this.getNodeUniform( uniformNode, type );
  53716. // Only add uniform if not already present in the group (check by name to avoid duplicates across stages)
  53717. const uniformName = uniformGPU.name;
  53718. const alreadyExists = uniformsGroup.uniforms.some( u => u.name === uniformName );
  53719. if ( ! alreadyExists ) {
  53720. uniformsGroup.addUniform( uniformGPU );
  53721. }
  53722. }
  53723. nodeData.uniformGPU = uniformGPU;
  53724. }
  53725. return uniformNode;
  53726. }
  53727. /**
  53728. * This method should be used whenever builtins are required in nodes.
  53729. * The internal builtins data structure will make sure builtins are
  53730. * defined in the WGSL source.
  53731. *
  53732. * @param {string} name - The builtin name.
  53733. * @param {string} property - The property name.
  53734. * @param {string} type - The node data type.
  53735. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  53736. * @return {string} The property name.
  53737. */
  53738. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  53739. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  53740. if ( map.has( name ) === false ) {
  53741. map.set( name, {
  53742. name,
  53743. property,
  53744. type
  53745. } );
  53746. }
  53747. return property;
  53748. }
  53749. /**
  53750. * Returns `true` if the given builtin is defined in the given shader stage.
  53751. *
  53752. * @param {string} name - The builtin name.
  53753. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  53754. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  53755. */
  53756. hasBuiltin( name, shaderStage = this.shaderStage ) {
  53757. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  53758. }
  53759. /**
  53760. * Returns the vertex index builtin.
  53761. *
  53762. * @return {string} The vertex index.
  53763. */
  53764. getVertexIndex() {
  53765. if ( this.shaderStage === 'vertex' ) {
  53766. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  53767. }
  53768. return 'vertexIndex';
  53769. }
  53770. /**
  53771. * Builds the given shader node.
  53772. *
  53773. * @param {ShaderNodeInternal} shaderNode - The shader node.
  53774. * @return {string} The WGSL function code.
  53775. */
  53776. buildFunctionCode( shaderNode ) {
  53777. const layout = shaderNode.layout;
  53778. const flowData = this.flowShaderNode( shaderNode );
  53779. const parameters = [];
  53780. for ( const input of layout.inputs ) {
  53781. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  53782. }
  53783. //
  53784. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  53785. ${ flowData.vars }
  53786. ${ flowData.code }
  53787. `;
  53788. if ( flowData.result ) {
  53789. code += `\treturn ${ flowData.result };\n`;
  53790. }
  53791. code += '\n}\n';
  53792. //
  53793. return code;
  53794. }
  53795. /**
  53796. * Contextually returns either the vertex stage instance index builtin
  53797. * or the linearized index of an compute invocation within a grid of workgroups.
  53798. *
  53799. * @return {string} The instance index.
  53800. */
  53801. getInstanceIndex() {
  53802. if ( this.shaderStage === 'vertex' ) {
  53803. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  53804. }
  53805. return 'instanceIndex';
  53806. }
  53807. /**
  53808. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  53809. *
  53810. * @return {string} The invocation local index.
  53811. */
  53812. getInvocationLocalIndex() {
  53813. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  53814. }
  53815. /**
  53816. * Returns a builtin representing the size of a subgroup within the current shader.
  53817. *
  53818. * @return {string} The subgroup size.
  53819. */
  53820. getSubgroupSize() {
  53821. this.enableSubGroups();
  53822. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  53823. }
  53824. /**
  53825. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  53826. *
  53827. * @return {string} The invocation subgroup index.
  53828. */
  53829. getInvocationSubgroupIndex() {
  53830. this.enableSubGroups();
  53831. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  53832. }
  53833. /**
  53834. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  53835. *
  53836. * @return {string} The subgroup index.
  53837. */
  53838. getSubgroupIndex() {
  53839. this.enableSubGroups();
  53840. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  53841. }
  53842. /**
  53843. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  53844. *
  53845. * @return {null} Null.
  53846. */
  53847. getDrawIndex() {
  53848. return null;
  53849. }
  53850. /**
  53851. * Returns the front facing builtin.
  53852. *
  53853. * @return {string} The front facing builtin.
  53854. */
  53855. getFrontFacing() {
  53856. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  53857. }
  53858. /**
  53859. * Returns the frag coord builtin.
  53860. *
  53861. * @return {string} The frag coord builtin.
  53862. */
  53863. getFragCoord() {
  53864. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  53865. }
  53866. /**
  53867. * Returns the frag depth builtin.
  53868. *
  53869. * @return {string} The frag depth builtin.
  53870. */
  53871. getFragDepth() {
  53872. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  53873. }
  53874. /**
  53875. * Returns the clip distances builtin.
  53876. *
  53877. * @return {string} The clip distances builtin.
  53878. */
  53879. getClipDistance() {
  53880. return 'varyings.hw_clip_distances';
  53881. }
  53882. /**
  53883. * Whether to flip texture data along its vertical axis or not.
  53884. *
  53885. * @return {boolean} Returns always `false` in context of WGSL.
  53886. */
  53887. isFlipY() {
  53888. return false;
  53889. }
  53890. /**
  53891. * Enables the given directive for the given shader stage.
  53892. *
  53893. * @param {string} name - The directive name.
  53894. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  53895. */
  53896. enableDirective( name, shaderStage = this.shaderStage ) {
  53897. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  53898. stage.add( name );
  53899. }
  53900. /**
  53901. * Returns the directives of the given shader stage as a WGSL string.
  53902. *
  53903. * @param {string} shaderStage - The shader stage.
  53904. * @return {string} A WGSL snippet that enables the directives of the given stage.
  53905. */
  53906. getDirectives( shaderStage ) {
  53907. const snippets = [];
  53908. const directives = this.directives[ shaderStage ];
  53909. if ( directives !== undefined ) {
  53910. for ( const directive of directives ) {
  53911. snippets.push( `enable ${directive};` );
  53912. }
  53913. }
  53914. return snippets.join( '\n' );
  53915. }
  53916. /**
  53917. * Enables the 'subgroups' directive.
  53918. */
  53919. enableSubGroups() {
  53920. this.enableDirective( 'subgroups' );
  53921. }
  53922. /**
  53923. * Enables the 'subgroups-f16' directive.
  53924. */
  53925. enableSubgroupsF16() {
  53926. this.enableDirective( 'subgroups-f16' );
  53927. }
  53928. /**
  53929. * Enables the 'clip_distances' directive.
  53930. */
  53931. enableClipDistances() {
  53932. this.enableDirective( 'clip_distances' );
  53933. }
  53934. /**
  53935. * Enables the 'f16' directive.
  53936. */
  53937. enableShaderF16() {
  53938. this.enableDirective( 'f16' );
  53939. }
  53940. /**
  53941. * Enables the 'dual_source_blending' directive.
  53942. */
  53943. enableDualSourceBlending() {
  53944. this.enableDirective( 'dual_source_blending' );
  53945. }
  53946. /**
  53947. * Enables hardware clipping.
  53948. *
  53949. * @param {string} planeCount - The clipping plane count.
  53950. */
  53951. enableHardwareClipping( planeCount ) {
  53952. this.enableClipDistances();
  53953. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  53954. }
  53955. /**
  53956. * Returns the builtins of the given shader stage as a WGSL string.
  53957. *
  53958. * @param {string} shaderStage - The shader stage.
  53959. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  53960. */
  53961. getBuiltins( shaderStage ) {
  53962. const snippets = [];
  53963. const builtins = this.builtins[ shaderStage ];
  53964. if ( builtins !== undefined ) {
  53965. for ( const { name, property, type } of builtins.values() ) {
  53966. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  53967. }
  53968. }
  53969. return snippets.join( ',\n\t' );
  53970. }
  53971. /**
  53972. * This method should be used when a new scoped buffer is used in context of
  53973. * compute shaders. It adds the array to the internal data structure which is
  53974. * later used to generate the respective WGSL.
  53975. *
  53976. * @param {string} name - The array name.
  53977. * @param {string} scope - The scope.
  53978. * @param {string} bufferType - The buffer type.
  53979. * @param {string} bufferCount - The buffer count.
  53980. * @return {string} The array name.
  53981. */
  53982. getScopedArray( name, scope, bufferType, bufferCount ) {
  53983. if ( this.scopedArrays.has( name ) === false ) {
  53984. this.scopedArrays.set( name, {
  53985. name,
  53986. scope,
  53987. bufferType,
  53988. bufferCount
  53989. } );
  53990. }
  53991. return name;
  53992. }
  53993. /**
  53994. * Returns the scoped arrays of the given shader stage as a WGSL string.
  53995. *
  53996. * @param {string} shaderStage - The shader stage.
  53997. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  53998. * Returns `undefined` when used in the vertex or fragment stage.
  53999. */
  54000. getScopedArrays( shaderStage ) {
  54001. if ( shaderStage !== 'compute' ) {
  54002. return;
  54003. }
  54004. const snippets = [];
  54005. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  54006. const type = this.getType( bufferType );
  54007. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  54008. }
  54009. return snippets.join( '\n' );
  54010. }
  54011. /**
  54012. * Returns the shader attributes of the given shader stage as a WGSL string.
  54013. *
  54014. * @param {string} shaderStage - The shader stage.
  54015. * @return {string} The WGSL snippet that defines the shader attributes.
  54016. */
  54017. getAttributes( shaderStage ) {
  54018. const snippets = [];
  54019. if ( shaderStage === 'compute' ) {
  54020. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  54021. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  54022. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  54023. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  54024. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  54025. this.enableDirective( 'subgroups', shaderStage );
  54026. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  54027. }
  54028. }
  54029. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  54030. const builtins = this.getBuiltins( 'attribute' );
  54031. if ( builtins ) snippets.push( builtins );
  54032. const attributes = this.getAttributesArray();
  54033. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  54034. const attribute = attributes[ index ];
  54035. const name = attribute.name;
  54036. const type = this.getType( attribute.type );
  54037. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  54038. }
  54039. }
  54040. return snippets.join( ',\n\t' );
  54041. }
  54042. /**
  54043. * Returns the members of the given struct type node as a WGSL string.
  54044. *
  54045. * @param {StructTypeNode} struct - The struct type node.
  54046. * @return {string} The WGSL snippet that defines the struct members.
  54047. */
  54048. getStructMembers( struct ) {
  54049. const snippets = [];
  54050. for ( const member of struct.members ) {
  54051. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  54052. let type = this.getType( member.type );
  54053. if ( member.atomic ) {
  54054. type = 'atomic< ' + type + ' >';
  54055. }
  54056. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  54057. }
  54058. if ( struct.output ) {
  54059. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  54060. }
  54061. return snippets.join( ',\n' );
  54062. }
  54063. /**
  54064. * Returns the structs of the given shader stage as a WGSL string.
  54065. *
  54066. * @param {string} shaderStage - The shader stage.
  54067. * @return {string} The WGSL snippet that defines the structs.
  54068. */
  54069. getStructs( shaderStage ) {
  54070. let result = '';
  54071. const structs = this.structs[ shaderStage ];
  54072. if ( structs.length > 0 ) {
  54073. const snippets = [];
  54074. for ( const struct of structs ) {
  54075. let snippet = `struct ${ struct.name } {\n`;
  54076. snippet += this.getStructMembers( struct );
  54077. snippet += '\n};';
  54078. snippets.push( snippet );
  54079. }
  54080. result = '\n' + snippets.join( '\n\n' ) + '\n';
  54081. }
  54082. return result;
  54083. }
  54084. /**
  54085. * Returns a WGSL string representing a variable.
  54086. *
  54087. * @param {string} type - The variable's type.
  54088. * @param {string} name - The variable's name.
  54089. * @param {?number} [count=null] - The array length.
  54090. * @return {string} The WGSL snippet that defines a variable.
  54091. */
  54092. getVar( type, name, count = null ) {
  54093. let snippet = `var ${ name } : `;
  54094. if ( count !== null ) {
  54095. snippet += this.generateArrayDeclaration( type, count );
  54096. } else {
  54097. snippet += this.getType( type );
  54098. }
  54099. return snippet;
  54100. }
  54101. /**
  54102. * Returns the variables of the given shader stage as a WGSL string.
  54103. *
  54104. * @param {string} shaderStage - The shader stage.
  54105. * @return {string} The WGSL snippet that defines the variables.
  54106. */
  54107. getVars( shaderStage ) {
  54108. const snippets = [];
  54109. const vars = this.vars[ shaderStage ];
  54110. if ( vars !== undefined ) {
  54111. for ( const variable of vars ) {
  54112. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  54113. }
  54114. }
  54115. return `\n${ snippets.join( '\n' ) }\n`;
  54116. }
  54117. /**
  54118. * Returns the varyings of the given shader stage as a WGSL string.
  54119. *
  54120. * @param {string} shaderStage - The shader stage.
  54121. * @return {string} The WGSL snippet that defines the varyings.
  54122. */
  54123. getVaryings( shaderStage ) {
  54124. const snippets = [];
  54125. if ( shaderStage === 'vertex' ) {
  54126. this.getBuiltin( 'position', 'builtinClipSpace', 'vec4<f32>', 'vertex' );
  54127. }
  54128. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  54129. const varyings = this.varyings;
  54130. const vars = this.vars[ shaderStage ];
  54131. let varyingIndex = 0;
  54132. for ( let index = 0; index < varyings.length; index ++ ) {
  54133. const varying = varyings[ index ];
  54134. if ( varying.needsInterpolation ) {
  54135. let attributesSnippet = `@location( ${ varyingIndex ++ } )`;
  54136. if ( varying.interpolationType ) {
  54137. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  54138. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  54139. // Otherwise, optimize interpolation when sensible
  54140. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  54141. attributesSnippet += ' @interpolate(flat, either)';
  54142. }
  54143. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  54144. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  54145. vars.push( varying );
  54146. }
  54147. }
  54148. }
  54149. const builtins = this.getBuiltins( shaderStage );
  54150. if ( builtins ) snippets.push( builtins );
  54151. const code = snippets.join( ',\n\t' );
  54152. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  54153. }
  54154. isCustomStruct( nodeUniform ) {
  54155. const attribute = nodeUniform.value;
  54156. const bufferNode = nodeUniform.node;
  54157. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  54158. const isStructArray =
  54159. ( bufferNode.value && bufferNode.value.array ) &&
  54160. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  54161. return isAttributeStructType && ! isStructArray;
  54162. }
  54163. /**
  54164. * Returns the uniforms of the given shader stage as a WGSL string.
  54165. *
  54166. * @param {string} shaderStage - The shader stage.
  54167. * @return {string} The WGSL snippet that defines the uniforms.
  54168. */
  54169. getUniforms( shaderStage ) {
  54170. const uniforms = this.uniforms[ shaderStage ];
  54171. const bindingSnippets = [];
  54172. const bufferSnippets = [];
  54173. const structSnippets = [];
  54174. const uniformGroups = {};
  54175. for ( const uniform of uniforms ) {
  54176. const groupName = uniform.groupNode.name;
  54177. const uniformIndexes = this.bindingsIndexes[ groupName ];
  54178. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'cubeDepthTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  54179. const texture = uniform.node.value;
  54180. // Cube textures always need samplers (they use textureSampleLevel, not textureLoad)
  54181. const needsSampler = texture.isCubeTexture === true || ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true );
  54182. if ( needsSampler ) {
  54183. if ( this.isSampleCompare( texture ) ) {
  54184. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  54185. } else {
  54186. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  54187. }
  54188. }
  54189. let textureType;
  54190. let multisampled = '';
  54191. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  54192. if ( primarySamples > 1 ) {
  54193. multisampled = '_multisampled';
  54194. }
  54195. if ( texture.isCubeTexture === true && texture.isDepthTexture === true ) {
  54196. textureType = 'texture_depth_cube';
  54197. } else if ( texture.isCubeTexture === true ) {
  54198. textureType = 'texture_cube<f32>';
  54199. } else if ( texture.isDepthTexture === true ) {
  54200. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  54201. textureType = `texture${ multisampled }_2d<f32>`;
  54202. } else {
  54203. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  54204. }
  54205. } else if ( uniform.node.isStorageTextureNode === true ) {
  54206. const format = getFormat( texture );
  54207. const access = this.getStorageAccess( uniform.node, shaderStage );
  54208. const is3D = uniform.node.value.is3DTexture;
  54209. const isArrayTexture = uniform.node.value.isArrayTexture;
  54210. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  54211. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  54212. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  54213. textureType = 'texture_2d_array<f32>';
  54214. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  54215. textureType = 'texture_3d<f32>';
  54216. } else {
  54217. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  54218. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  54219. }
  54220. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  54221. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  54222. const bufferNode = uniform.node;
  54223. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  54224. const bufferCount = bufferNode.bufferCount;
  54225. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  54226. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  54227. if ( this.isCustomStruct( uniform ) ) {
  54228. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  54229. } else {
  54230. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  54231. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  54232. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  54233. }
  54234. } else {
  54235. const groupName = uniform.groupNode.name;
  54236. // Check if this group has already been processed in this shader stage
  54237. if ( uniformGroups[ groupName ] === undefined ) {
  54238. // Get the shared uniform group that contains uniforms from all stages
  54239. const sharedUniformGroup = this.uniformGroups[ groupName ];
  54240. if ( sharedUniformGroup !== undefined ) {
  54241. // Generate snippets for ALL uniforms in this shared group
  54242. const snippets = [];
  54243. for ( const sharedUniform of sharedUniformGroup.uniforms ) {
  54244. const type = sharedUniform.getType();
  54245. const vectorType = this.getType( this.getVectorType( type ) );
  54246. snippets.push( `\t${ sharedUniform.name } : ${ vectorType }` );
  54247. }
  54248. // Check if this group already has an assigned binding index (from another shader stage)
  54249. let groupBinding = this.uniformGroupsBindings[ groupName ];
  54250. if ( groupBinding === undefined ) {
  54251. // First time processing this group - assign a new binding index
  54252. groupBinding = {
  54253. index: uniformIndexes.binding ++,
  54254. id: uniformIndexes.group
  54255. };
  54256. this.uniformGroupsBindings[ groupName ] = groupBinding;
  54257. }
  54258. uniformGroups[ groupName ] = {
  54259. index: groupBinding.index,
  54260. id: groupBinding.id,
  54261. snippets: snippets
  54262. };
  54263. }
  54264. }
  54265. }
  54266. }
  54267. for ( const name in uniformGroups ) {
  54268. const group = uniformGroups[ name ];
  54269. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  54270. }
  54271. const code = [ ...bindingSnippets, ...bufferSnippets, ...structSnippets ].join( '\n' );
  54272. return code;
  54273. }
  54274. /**
  54275. * Controls the code build of the shader stages.
  54276. */
  54277. buildCode() {
  54278. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  54279. this.sortBindingGroups();
  54280. for ( const shaderStage in shadersData ) {
  54281. this.shaderStage = shaderStage;
  54282. const stageData = shadersData[ shaderStage ];
  54283. stageData.uniforms = this.getUniforms( shaderStage );
  54284. stageData.attributes = this.getAttributes( shaderStage );
  54285. stageData.varyings = this.getVaryings( shaderStage );
  54286. stageData.structs = this.getStructs( shaderStage );
  54287. stageData.vars = this.getVars( shaderStage );
  54288. stageData.codes = this.getCodes( shaderStage );
  54289. stageData.directives = this.getDirectives( shaderStage );
  54290. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  54291. //
  54292. let flow = '// code\n\n';
  54293. flow += this.flowCode[ shaderStage ];
  54294. const flowNodes = this.flowNodes[ shaderStage ];
  54295. const mainNode = flowNodes[ flowNodes.length - 1 ];
  54296. const outputNode = mainNode.outputNode;
  54297. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  54298. for ( const node of flowNodes ) {
  54299. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  54300. const slotName = node.name;
  54301. if ( slotName ) {
  54302. if ( flow.length > 0 ) flow += '\n';
  54303. flow += `\t// flow -> ${ slotName }\n`;
  54304. }
  54305. flow += `${ flowSlotData.code }\n\t`;
  54306. if ( node === mainNode && shaderStage !== 'compute' ) {
  54307. flow += '// result\n\n\t';
  54308. if ( shaderStage === 'vertex' ) {
  54309. flow += `varyings.builtinClipSpace = ${ flowSlotData.result };`;
  54310. } else if ( shaderStage === 'fragment' ) {
  54311. if ( isOutputStruct ) {
  54312. stageData.returnType = outputNode.getNodeType( this );
  54313. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  54314. flow += `return ${ flowSlotData.result };`;
  54315. } else {
  54316. let structSnippet = '\t@location( 0 ) color: vec4<f32>';
  54317. const builtins = this.getBuiltins( 'output' );
  54318. if ( builtins ) structSnippet += ',\n\t' + builtins;
  54319. stageData.returnType = 'OutputStruct';
  54320. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  54321. stageData.structs += '\nvar<private> output : OutputStruct;';
  54322. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  54323. }
  54324. }
  54325. }
  54326. }
  54327. stageData.flow = flow;
  54328. }
  54329. this.shaderStage = null;
  54330. if ( this.material !== null ) {
  54331. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  54332. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  54333. } else {
  54334. // Early strictly validated in computeNode
  54335. const workgroupSize = this.object.workgroupSize;
  54336. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  54337. }
  54338. }
  54339. /**
  54340. * Returns the native shader method name for a given generic name.
  54341. *
  54342. * @param {string} method - The method name to resolve.
  54343. * @param {?string} [output=null] - An optional output.
  54344. * @return {string} The resolved WGSL method name.
  54345. */
  54346. getMethod( method, output = null ) {
  54347. let wgslMethod;
  54348. if ( output !== null ) {
  54349. wgslMethod = this._getWGSLMethod( method + '_' + output );
  54350. }
  54351. if ( wgslMethod === undefined ) {
  54352. wgslMethod = this._getWGSLMethod( method );
  54353. }
  54354. return wgslMethod || method;
  54355. }
  54356. /**
  54357. * Returns the bitcast method name for a given input and outputType.
  54358. *
  54359. * @param {string} type - The output type to bitcast to.
  54360. * @return {string} The resolved WGSL bitcast invocation.
  54361. */
  54362. getBitcastMethod( type ) {
  54363. const dataType = this.getType( type );
  54364. return `bitcast<${ dataType }>`;
  54365. }
  54366. /**
  54367. * Returns the float packing method name for a given numeric encoding.
  54368. *
  54369. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  54370. * @returns {string} The resolve WGSL float packing method name.
  54371. */
  54372. getFloatPackingMethod( encoding ) {
  54373. return this.getMethod( `floatpack_${ encoding }_2x16` );
  54374. }
  54375. /**
  54376. * Returns the float unpacking method name for a given numeric encoding.
  54377. *
  54378. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  54379. * @returns {string} The resolve WGSL float unpacking method name.
  54380. */
  54381. getFloatUnpackingMethod( encoding ) {
  54382. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  54383. }
  54384. /**
  54385. * Returns the native snippet for a ternary operation.
  54386. *
  54387. * @param {string} condSnippet - The condition determining which expression gets resolved.
  54388. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  54389. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  54390. * @return {string} The resolved method name.
  54391. */
  54392. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  54393. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  54394. }
  54395. /**
  54396. * Returns the WGSL type of the given node data type.
  54397. *
  54398. * @param {string} type - The node data type.
  54399. * @return {string} The WGSL type.
  54400. */
  54401. getType( type ) {
  54402. return wgslTypeLib[ type ] || type;
  54403. }
  54404. /**
  54405. * Whether the requested feature is available or not.
  54406. *
  54407. * @param {string} name - The requested feature.
  54408. * @return {boolean} Whether the requested feature is supported or not.
  54409. */
  54410. isAvailable( name ) {
  54411. let result = supports[ name ];
  54412. if ( result === undefined ) {
  54413. if ( name === 'float32Filterable' ) {
  54414. result = this.renderer.hasFeature( 'float32-filterable' );
  54415. } else if ( name === 'clipDistance' ) {
  54416. result = this.renderer.hasFeature( 'clip-distances' );
  54417. }
  54418. supports[ name ] = result;
  54419. }
  54420. return result;
  54421. }
  54422. /**
  54423. * Returns the native shader method name for a given generic name.
  54424. *
  54425. * @private
  54426. * @param {string} method - The method name to resolve.
  54427. * @return {string} The resolved WGSL method name.
  54428. */
  54429. _getWGSLMethod( method ) {
  54430. if ( wgslPolyfill[ method ] !== undefined ) {
  54431. this._include( method );
  54432. }
  54433. return wgslMethods[ method ];
  54434. }
  54435. /**
  54436. * Includes the given method name into the current
  54437. * function node.
  54438. *
  54439. * @private
  54440. * @param {string} name - The method name to include.
  54441. * @return {CodeNode} The respective code node.
  54442. */
  54443. _include( name ) {
  54444. const codeNode = wgslPolyfill[ name ];
  54445. codeNode.build( this );
  54446. this.addInclude( codeNode );
  54447. return codeNode;
  54448. }
  54449. /**
  54450. * Returns a WGSL vertex shader based on the given shader data.
  54451. *
  54452. * @private
  54453. * @param {Object} shaderData - The shader data.
  54454. * @return {string} The vertex shader.
  54455. */
  54456. _getWGSLVertexCode( shaderData ) {
  54457. return `${ this.getSignature() }
  54458. // directives
  54459. ${shaderData.directives}
  54460. // structs
  54461. ${shaderData.structs}
  54462. // uniforms
  54463. ${shaderData.uniforms}
  54464. // varyings
  54465. ${shaderData.varyings}
  54466. var<private> varyings : VaryingsStruct;
  54467. // codes
  54468. ${shaderData.codes}
  54469. @vertex
  54470. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  54471. // vars
  54472. ${shaderData.vars}
  54473. // flow
  54474. ${shaderData.flow}
  54475. return varyings;
  54476. }
  54477. `;
  54478. }
  54479. /**
  54480. * Returns a WGSL fragment shader based on the given shader data.
  54481. *
  54482. * @private
  54483. * @param {Object} shaderData - The shader data.
  54484. * @return {string} The vertex shader.
  54485. */
  54486. _getWGSLFragmentCode( shaderData ) {
  54487. return `${ this.getSignature() }
  54488. // global
  54489. ${ diagnostics }
  54490. // structs
  54491. ${shaderData.structs}
  54492. // uniforms
  54493. ${shaderData.uniforms}
  54494. // codes
  54495. ${shaderData.codes}
  54496. @fragment
  54497. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  54498. // vars
  54499. ${shaderData.vars}
  54500. // flow
  54501. ${shaderData.flow}
  54502. }
  54503. `;
  54504. }
  54505. /**
  54506. * Returns a WGSL compute shader based on the given shader data.
  54507. *
  54508. * @private
  54509. * @param {Object} shaderData - The shader data.
  54510. * @param {string} workgroupSize - The workgroup size.
  54511. * @return {string} The vertex shader.
  54512. */
  54513. _getWGSLComputeCode( shaderData, workgroupSize ) {
  54514. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  54515. return `${ this.getSignature() }
  54516. // directives
  54517. ${ shaderData.directives }
  54518. // system
  54519. var<private> instanceIndex : u32;
  54520. // locals
  54521. ${ shaderData.scopedArrays }
  54522. // structs
  54523. ${ shaderData.structs }
  54524. // uniforms
  54525. ${ shaderData.uniforms }
  54526. // codes
  54527. ${ shaderData.codes }
  54528. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  54529. fn main( ${ shaderData.attributes } ) {
  54530. // system
  54531. instanceIndex = globalId.x
  54532. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  54533. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  54534. // vars
  54535. ${ shaderData.vars }
  54536. // flow
  54537. ${ shaderData.flow }
  54538. }
  54539. `;
  54540. }
  54541. /**
  54542. * Returns a WGSL struct based on the given name and variables.
  54543. *
  54544. * @private
  54545. * @param {string} name - The struct name.
  54546. * @param {string} vars - The struct variables.
  54547. * @return {string} The WGSL snippet representing a struct.
  54548. */
  54549. _getWGSLStruct( name, vars ) {
  54550. return `
  54551. struct ${name} {
  54552. ${vars}
  54553. };`;
  54554. }
  54555. /**
  54556. * Returns a WGSL struct binding.
  54557. *
  54558. * @private
  54559. * @param {string} name - The struct name.
  54560. * @param {string} vars - The struct variables.
  54561. * @param {string} access - The access.
  54562. * @param {number} [binding=0] - The binding index.
  54563. * @param {number} [group=0] - The group index.
  54564. * @return {string} The WGSL snippet representing a struct binding.
  54565. */
  54566. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  54567. const structName = name + 'Struct';
  54568. const structSnippet = this._getWGSLStruct( structName, vars );
  54569. return `${structSnippet}
  54570. @binding( ${ binding } ) @group( ${ group } )
  54571. var<${access}> ${ name } : ${ structName };`;
  54572. }
  54573. }
  54574. /**
  54575. * A WebGPU backend utility module with common helpers.
  54576. *
  54577. * @private
  54578. */
  54579. class WebGPUUtils {
  54580. /**
  54581. * Constructs a new utility object.
  54582. *
  54583. * @param {WebGPUBackend} backend - The WebGPU backend.
  54584. */
  54585. constructor( backend ) {
  54586. /**
  54587. * A reference to the WebGPU backend.
  54588. *
  54589. * @type {WebGPUBackend}
  54590. */
  54591. this.backend = backend;
  54592. }
  54593. /**
  54594. * Returns the depth/stencil GPU format for the given render context.
  54595. *
  54596. * @param {RenderContext} renderContext - The render context.
  54597. * @return {string} The depth/stencil GPU texture format.
  54598. */
  54599. getCurrentDepthStencilFormat( renderContext ) {
  54600. let format;
  54601. if ( renderContext.depth ) {
  54602. if ( renderContext.depthTexture !== null ) {
  54603. format = this.getTextureFormatGPU( renderContext.depthTexture );
  54604. } else if ( renderContext.stencil ) {
  54605. if ( this.backend.renderer.reversedDepthBuffer === true ) {
  54606. format = GPUTextureFormat.Depth32FloatStencil8;
  54607. } else {
  54608. format = GPUTextureFormat.Depth24PlusStencil8;
  54609. }
  54610. } else {
  54611. if ( this.backend.renderer.reversedDepthBuffer === true ) {
  54612. format = GPUTextureFormat.Depth32Float;
  54613. } else {
  54614. format = GPUTextureFormat.Depth24Plus;
  54615. }
  54616. }
  54617. }
  54618. return format;
  54619. }
  54620. /**
  54621. * Returns the GPU format for the given texture.
  54622. *
  54623. * @param {Texture} texture - The texture.
  54624. * @return {string} The GPU texture format.
  54625. */
  54626. getTextureFormatGPU( texture ) {
  54627. return this.backend.get( texture ).format;
  54628. }
  54629. /**
  54630. * Returns an object that defines the multi-sampling state of the given texture.
  54631. *
  54632. * @param {Texture} texture - The texture.
  54633. * @return {Object} The multi-sampling state.
  54634. */
  54635. getTextureSampleData( texture ) {
  54636. let samples;
  54637. if ( texture.isFramebufferTexture ) {
  54638. samples = 1;
  54639. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  54640. const renderer = this.backend.renderer;
  54641. const renderTarget = renderer.getRenderTarget();
  54642. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  54643. } else if ( texture.renderTarget ) {
  54644. samples = texture.renderTarget.samples;
  54645. }
  54646. samples = samples || 1;
  54647. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  54648. const primarySamples = isMSAA ? 1 : samples;
  54649. return { samples, primarySamples, isMSAA };
  54650. }
  54651. /**
  54652. * Returns the default color attachment's GPU format of the current render context.
  54653. *
  54654. * @param {RenderContext} renderContext - The render context.
  54655. * @return {string} The GPU texture format of the default color attachment.
  54656. */
  54657. getCurrentColorFormat( renderContext ) {
  54658. let format;
  54659. if ( renderContext.textures !== null ) {
  54660. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  54661. } else {
  54662. format = this.getPreferredCanvasFormat(); // default context format
  54663. }
  54664. return format;
  54665. }
  54666. /**
  54667. * Returns the GPU formats of all color attachments of the current render context.
  54668. *
  54669. * @param {RenderContext} renderContext - The render context.
  54670. * @return {Array<string>} The GPU texture formats of all color attachments.
  54671. */
  54672. getCurrentColorFormats( renderContext ) {
  54673. if ( renderContext.textures !== null ) {
  54674. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  54675. } else {
  54676. return [ this.getPreferredCanvasFormat() ]; // default context format
  54677. }
  54678. }
  54679. /**
  54680. * Returns the output color space of the current render context.
  54681. *
  54682. * @param {RenderContext} renderContext - The render context.
  54683. * @return {string} The output color space.
  54684. */
  54685. getCurrentColorSpace( renderContext ) {
  54686. if ( renderContext.textures !== null ) {
  54687. return renderContext.textures[ 0 ].colorSpace;
  54688. }
  54689. return this.backend.renderer.outputColorSpace;
  54690. }
  54691. /**
  54692. * Returns GPU primitive topology for the given object and material.
  54693. *
  54694. * @param {Object3D} object - The 3D object.
  54695. * @param {Material} material - The material.
  54696. * @return {string} The GPU primitive topology.
  54697. */
  54698. getPrimitiveTopology( object, material ) {
  54699. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  54700. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  54701. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  54702. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  54703. }
  54704. /**
  54705. * Returns a modified sample count from the given sample count value.
  54706. *
  54707. * That is required since WebGPU only supports either 1 or 4.
  54708. *
  54709. * @param {number} sampleCount - The input sample count.
  54710. * @return {number} The (potentially updated) output sample count.
  54711. */
  54712. getSampleCount( sampleCount ) {
  54713. return sampleCount >= 4 ? 4 : 1;
  54714. }
  54715. /**
  54716. * Returns the sample count of the given render context.
  54717. *
  54718. * @param {RenderContext} renderContext - The render context.
  54719. * @return {number} The sample count.
  54720. */
  54721. getSampleCountRenderContext( renderContext ) {
  54722. if ( renderContext.textures !== null ) {
  54723. return this.getSampleCount( renderContext.sampleCount );
  54724. }
  54725. return this.getSampleCount( this.backend.renderer.currentSamples );
  54726. }
  54727. /**
  54728. * Returns the preferred canvas format.
  54729. *
  54730. * There is a separate method for this so it's possible to
  54731. * honor edge cases for specific devices.
  54732. *
  54733. * @return {string} The GPU texture format of the canvas.
  54734. */
  54735. getPreferredCanvasFormat() {
  54736. const parameters = this.backend.parameters;
  54737. const bufferType = parameters.outputType;
  54738. if ( bufferType === undefined ) {
  54739. return navigator.gpu.getPreferredCanvasFormat();
  54740. } else if ( bufferType === UnsignedByteType ) {
  54741. return GPUTextureFormat.BGRA8Unorm;
  54742. } else if ( bufferType === HalfFloatType ) {
  54743. return GPUTextureFormat.RGBA16Float;
  54744. } else {
  54745. throw new Error( 'Unsupported output buffer type.' );
  54746. }
  54747. }
  54748. }
  54749. const typedArraysToVertexFormatPrefix = new Map( [
  54750. [ Int8Array, [ 'sint8', 'snorm8' ]],
  54751. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  54752. [ Int16Array, [ 'sint16', 'snorm16' ]],
  54753. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  54754. [ Int32Array, [ 'sint32', 'snorm32' ]],
  54755. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  54756. [ Float32Array, [ 'float32', ]],
  54757. ] );
  54758. if ( typeof Float16Array !== 'undefined' ) {
  54759. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  54760. }
  54761. const typedAttributeToVertexFormatPrefix = new Map( [
  54762. [ Float16BufferAttribute, [ 'float16', ]],
  54763. ] );
  54764. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  54765. [ Int32Array, 'sint32' ],
  54766. [ Int16Array, 'sint32' ], // patch for INT16
  54767. [ Uint32Array, 'uint32' ],
  54768. [ Uint16Array, 'uint32' ], // patch for UINT16
  54769. [ Float32Array, 'float32' ]
  54770. ] );
  54771. /**
  54772. * A WebGPU backend utility module for managing shader attributes.
  54773. *
  54774. * @private
  54775. */
  54776. class WebGPUAttributeUtils {
  54777. /**
  54778. * Constructs a new utility object.
  54779. *
  54780. * @param {WebGPUBackend} backend - The WebGPU backend.
  54781. */
  54782. constructor( backend ) {
  54783. /**
  54784. * A reference to the WebGPU backend.
  54785. *
  54786. * @type {WebGPUBackend}
  54787. */
  54788. this.backend = backend;
  54789. }
  54790. /**
  54791. * Creates the GPU buffer for the given buffer attribute.
  54792. *
  54793. * @param {BufferAttribute} attribute - The buffer attribute.
  54794. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  54795. */
  54796. createAttribute( attribute, usage ) {
  54797. const bufferAttribute = this._getBufferAttribute( attribute );
  54798. const backend = this.backend;
  54799. const bufferData = backend.get( bufferAttribute );
  54800. let buffer = bufferData.buffer;
  54801. if ( buffer === undefined ) {
  54802. const device = backend.device;
  54803. let array = bufferAttribute.array;
  54804. // patch for INT16 and UINT16
  54805. if ( attribute.normalized === false ) {
  54806. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  54807. array = new Int32Array( array );
  54808. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  54809. array = new Uint32Array( array );
  54810. if ( usage & GPUBufferUsage.INDEX ) {
  54811. for ( let i = 0; i < array.length; i ++ ) {
  54812. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  54813. }
  54814. }
  54815. }
  54816. }
  54817. bufferAttribute.array = array;
  54818. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  54819. array = new array.constructor( bufferAttribute.count * 4 );
  54820. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  54821. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  54822. }
  54823. // Update BufferAttribute
  54824. bufferAttribute.itemSize = 4;
  54825. bufferAttribute.array = array;
  54826. bufferData._force3to4BytesAlignment = true;
  54827. }
  54828. // ensure 4 byte alignment
  54829. const byteLength = array.byteLength;
  54830. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  54831. buffer = device.createBuffer( {
  54832. label: bufferAttribute.name,
  54833. size: size,
  54834. usage: usage,
  54835. mappedAtCreation: true
  54836. } );
  54837. new array.constructor( buffer.getMappedRange() ).set( array );
  54838. buffer.unmap();
  54839. bufferData.buffer = buffer;
  54840. }
  54841. }
  54842. /**
  54843. * Updates the GPU buffer of the given buffer attribute.
  54844. *
  54845. * @param {BufferAttribute} attribute - The buffer attribute.
  54846. */
  54847. updateAttribute( attribute ) {
  54848. const bufferAttribute = this._getBufferAttribute( attribute );
  54849. const backend = this.backend;
  54850. const device = backend.device;
  54851. const bufferData = backend.get( bufferAttribute );
  54852. const buffer = backend.get( bufferAttribute ).buffer;
  54853. let array = bufferAttribute.array;
  54854. // if storage buffer ensure 4 byte alignment
  54855. if ( bufferData._force3to4BytesAlignment === true ) {
  54856. array = new array.constructor( bufferAttribute.count * 4 );
  54857. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  54858. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  54859. }
  54860. bufferAttribute.array = array;
  54861. }
  54862. const updateRanges = bufferAttribute.updateRanges;
  54863. if ( updateRanges.length === 0 ) {
  54864. // Not using update ranges
  54865. device.queue.writeBuffer(
  54866. buffer,
  54867. 0,
  54868. array,
  54869. 0
  54870. );
  54871. } else {
  54872. const isTyped = isTypedArray( array );
  54873. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  54874. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  54875. const range = updateRanges[ i ];
  54876. let dataOffset, size;
  54877. if ( bufferData._force3to4BytesAlignment === true ) {
  54878. const vertexStart = Math.floor( range.start / 3 );
  54879. const vertexCount = Math.ceil( range.count / 3 );
  54880. dataOffset = vertexStart * 4 * byteOffsetFactor;
  54881. size = vertexCount * 4 * byteOffsetFactor;
  54882. } else {
  54883. dataOffset = range.start * byteOffsetFactor;
  54884. size = range.count * byteOffsetFactor;
  54885. }
  54886. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  54887. device.queue.writeBuffer(
  54888. buffer,
  54889. bufferOffset,
  54890. array,
  54891. dataOffset,
  54892. size
  54893. );
  54894. }
  54895. bufferAttribute.clearUpdateRanges();
  54896. }
  54897. }
  54898. /**
  54899. * This method creates the vertex buffer layout data which are
  54900. * require when creating a render pipeline for the given render object.
  54901. *
  54902. * @param {RenderObject} renderObject - The render object.
  54903. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  54904. */
  54905. createShaderVertexBuffers( renderObject ) {
  54906. const attributes = renderObject.getAttributes();
  54907. const vertexBuffers = new Map();
  54908. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  54909. const geometryAttribute = attributes[ slot ];
  54910. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  54911. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  54912. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  54913. if ( vertexBufferLayout === undefined ) {
  54914. let arrayStride, stepMode;
  54915. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  54916. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  54917. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  54918. } else {
  54919. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  54920. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  54921. }
  54922. // patch for INT16 and UINT16
  54923. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  54924. arrayStride = 4;
  54925. }
  54926. vertexBufferLayout = {
  54927. arrayStride,
  54928. attributes: [],
  54929. stepMode
  54930. };
  54931. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  54932. }
  54933. const format = this._getVertexFormat( geometryAttribute );
  54934. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  54935. vertexBufferLayout.attributes.push( {
  54936. shaderLocation: slot,
  54937. offset,
  54938. format
  54939. } );
  54940. }
  54941. return Array.from( vertexBuffers.values() );
  54942. }
  54943. /**
  54944. * Destroys the GPU buffer of the given buffer attribute.
  54945. *
  54946. * @param {BufferAttribute} attribute - The buffer attribute.
  54947. */
  54948. destroyAttribute( attribute ) {
  54949. const backend = this.backend;
  54950. const data = backend.get( this._getBufferAttribute( attribute ) );
  54951. data.buffer.destroy();
  54952. backend.delete( attribute );
  54953. }
  54954. /**
  54955. * This method performs a readback operation by moving buffer data from
  54956. * a storage buffer attribute from the GPU to the CPU.
  54957. *
  54958. * @async
  54959. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  54960. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  54961. */
  54962. async getArrayBufferAsync( attribute ) {
  54963. const backend = this.backend;
  54964. const device = backend.device;
  54965. const data = backend.get( this._getBufferAttribute( attribute ) );
  54966. const bufferGPU = data.buffer;
  54967. const size = bufferGPU.size;
  54968. const readBufferGPU = device.createBuffer( {
  54969. label: `${ attribute.name }_readback`,
  54970. size,
  54971. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  54972. } );
  54973. const cmdEncoder = device.createCommandEncoder( {
  54974. label: `readback_encoder_${ attribute.name }`
  54975. } );
  54976. cmdEncoder.copyBufferToBuffer(
  54977. bufferGPU,
  54978. 0,
  54979. readBufferGPU,
  54980. 0,
  54981. size
  54982. );
  54983. const gpuCommands = cmdEncoder.finish();
  54984. device.queue.submit( [ gpuCommands ] );
  54985. await readBufferGPU.mapAsync( GPUMapMode.READ );
  54986. const arrayBuffer = readBufferGPU.getMappedRange();
  54987. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  54988. readBufferGPU.unmap();
  54989. return dstBuffer.buffer;
  54990. }
  54991. /**
  54992. * Returns the vertex format of the given buffer attribute.
  54993. *
  54994. * @private
  54995. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  54996. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  54997. */
  54998. _getVertexFormat( geometryAttribute ) {
  54999. const { itemSize, normalized } = geometryAttribute;
  55000. const ArrayType = geometryAttribute.array.constructor;
  55001. const AttributeType = geometryAttribute.constructor;
  55002. let format;
  55003. if ( itemSize === 1 ) {
  55004. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  55005. } else {
  55006. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  55007. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  55008. if ( prefix ) {
  55009. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  55010. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  55011. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  55012. if ( paddedItemSize % 1 ) {
  55013. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  55014. }
  55015. format = `${prefix}x${paddedItemSize}`;
  55016. }
  55017. }
  55018. if ( ! format ) {
  55019. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  55020. }
  55021. return format;
  55022. }
  55023. /**
  55024. * Utility method for handling interleaved buffer attributes correctly.
  55025. * To process them, their `InterleavedBuffer` is returned.
  55026. *
  55027. * @private
  55028. * @param {BufferAttribute} attribute - The attribute.
  55029. * @return {BufferAttribute|InterleavedBuffer}
  55030. */
  55031. _getBufferAttribute( attribute ) {
  55032. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  55033. return attribute;
  55034. }
  55035. }
  55036. /**
  55037. * Class representing a WebGPU bind group layout.
  55038. *
  55039. * @private
  55040. */
  55041. class BindGroupLayout {
  55042. /**
  55043. * Constructs a new layout.
  55044. *
  55045. * @param {GPUBindGroupLayout} layoutGPU - A GPU Bind Group Layout.
  55046. */
  55047. constructor( layoutGPU ) {
  55048. /**
  55049. * The current GPUBindGroupLayout.
  55050. *
  55051. * @type {GPUBindGroupLayout}
  55052. */
  55053. this.layoutGPU = layoutGPU;
  55054. /**
  55055. * The number of bind groups that use this layout.
  55056. *
  55057. * @type {number}
  55058. */
  55059. this.usedTimes = 0;
  55060. }
  55061. }
  55062. /**
  55063. * A WebGPU backend utility module for managing bindings.
  55064. *
  55065. * When reading the documentation it's helpful to keep in mind that
  55066. * all class definitions starting with 'GPU*' are modules from the
  55067. * WebGPU API. So for example `BindGroup` is a class from the engine
  55068. * whereas `GPUBindGroup` is a class from WebGPU.
  55069. *
  55070. * @private
  55071. */
  55072. class WebGPUBindingUtils {
  55073. /**
  55074. * Constructs a new utility object.
  55075. *
  55076. * @param {WebGPUBackend} backend - The WebGPU backend.
  55077. */
  55078. constructor( backend ) {
  55079. /**
  55080. * A reference to the WebGPU backend.
  55081. *
  55082. * @type {WebGPUBackend}
  55083. */
  55084. this.backend = backend;
  55085. /**
  55086. * A cache that maps combinations of layout entries to existing bind group layouts.
  55087. *
  55088. * @private
  55089. * @type {Map<string, BindGroupLayout>}
  55090. */
  55091. this._bindGroupLayoutCache = new Map();
  55092. }
  55093. /**
  55094. * Creates a GPU bind group layout for the given bind group.
  55095. *
  55096. * @param {BindGroup} bindGroup - The bind group.
  55097. * @return {GPUBindGroupLayout} The GPU bind group layout.
  55098. */
  55099. createBindingsLayout( bindGroup ) {
  55100. const backend = this.backend;
  55101. const device = backend.device;
  55102. const bindingsData = backend.get( bindGroup );
  55103. // check if the the bind group already has a layout
  55104. if ( bindingsData.layout ) {
  55105. return bindingsData.layout.layoutGPU;
  55106. }
  55107. // if not, assing one
  55108. const entries = this._createLayoutEntries( bindGroup );
  55109. const bindGroupLayoutKey = hashString( JSON.stringify( entries ) );
  55110. // try to find an existing layout in the cache
  55111. let bindGroupLayout = this._bindGroupLayoutCache.get( bindGroupLayoutKey );
  55112. // if not create a new one
  55113. if ( bindGroupLayout === undefined ) {
  55114. bindGroupLayout = new BindGroupLayout( device.createBindGroupLayout( { entries } ) );
  55115. this._bindGroupLayoutCache.set( bindGroupLayoutKey, bindGroupLayout );
  55116. }
  55117. bindGroupLayout.usedTimes ++;
  55118. bindingsData.layout = bindGroupLayout;
  55119. bindingsData.layoutKey = bindGroupLayoutKey;
  55120. return bindGroupLayout.layoutGPU;
  55121. }
  55122. /**
  55123. * Creates bindings from the given bind group definition.
  55124. *
  55125. * @param {BindGroup} bindGroup - The bind group.
  55126. * @param {Array<BindGroup>} bindings - Array of bind groups.
  55127. * @param {number} cacheIndex - The cache index.
  55128. * @param {number} version - The version.
  55129. */
  55130. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  55131. const { backend } = this;
  55132. const bindingsData = backend.get( bindGroup );
  55133. // setup (static) binding layout and (dynamic) binding group
  55134. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  55135. let bindGroupGPU;
  55136. if ( cacheIndex > 0 ) {
  55137. if ( bindingsData.groups === undefined ) {
  55138. bindingsData.groups = [];
  55139. bindingsData.versions = [];
  55140. }
  55141. if ( bindingsData.versions[ cacheIndex ] === version ) {
  55142. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  55143. }
  55144. }
  55145. if ( bindGroupGPU === undefined ) {
  55146. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  55147. if ( cacheIndex > 0 ) {
  55148. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  55149. bindingsData.versions[ cacheIndex ] = version;
  55150. }
  55151. }
  55152. bindingsData.group = bindGroupGPU;
  55153. }
  55154. /**
  55155. * Updates a buffer binding.
  55156. *
  55157. * @param {Buffer} binding - The buffer binding to update.
  55158. */
  55159. updateBinding( binding ) {
  55160. const backend = this.backend;
  55161. const device = backend.device;
  55162. const array = binding.buffer; // cpu
  55163. const buffer = backend.get( binding ).buffer; // gpu
  55164. const updateRanges = binding.updateRanges;
  55165. if ( updateRanges.length === 0 ) {
  55166. device.queue.writeBuffer(
  55167. buffer,
  55168. 0,
  55169. array,
  55170. 0
  55171. );
  55172. } else {
  55173. const isTyped = isTypedArray( array );
  55174. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  55175. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  55176. const range = updateRanges[ i ];
  55177. const dataOffset = range.start * byteOffsetFactor;
  55178. const size = range.count * byteOffsetFactor;
  55179. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  55180. device.queue.writeBuffer(
  55181. buffer,
  55182. bufferOffset,
  55183. array,
  55184. dataOffset,
  55185. size
  55186. );
  55187. }
  55188. }
  55189. }
  55190. /**
  55191. * Creates a GPU bind group for the camera index.
  55192. *
  55193. * @param {Uint32Array} data - The index data.
  55194. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  55195. * @return {GPUBindGroup} The GPU bind group.
  55196. */
  55197. createBindGroupIndex( data, layoutGPU ) {
  55198. const backend = this.backend;
  55199. const device = backend.device;
  55200. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  55201. const index = data[ 0 ];
  55202. const buffer = device.createBuffer( {
  55203. label: 'bindingCameraIndex_' + index,
  55204. size: 16, // uint(4) * 4
  55205. usage: usage
  55206. } );
  55207. device.queue.writeBuffer( buffer, 0, data, 0 );
  55208. const entries = [ { binding: 0, resource: { buffer } } ];
  55209. return device.createBindGroup( {
  55210. label: 'bindGroupCameraIndex_' + index,
  55211. layout: layoutGPU,
  55212. entries
  55213. } );
  55214. }
  55215. /**
  55216. * Creates a GPU bind group for the given bind group and GPU layout.
  55217. *
  55218. * @param {BindGroup} bindGroup - The bind group.
  55219. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  55220. * @return {GPUBindGroup} The GPU bind group.
  55221. */
  55222. createBindGroup( bindGroup, layoutGPU ) {
  55223. const backend = this.backend;
  55224. const device = backend.device;
  55225. let bindingPoint = 0;
  55226. const entriesGPU = [];
  55227. for ( const binding of bindGroup.bindings ) {
  55228. if ( binding.isUniformBuffer ) {
  55229. const bindingData = backend.get( binding );
  55230. if ( bindingData.buffer === undefined ) {
  55231. const byteLength = binding.byteLength;
  55232. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  55233. const visibilities = [];
  55234. if ( binding.visibility & GPUShaderStage.VERTEX ) {
  55235. visibilities.push( 'vertex' );
  55236. }
  55237. if ( binding.visibility & GPUShaderStage.FRAGMENT ) {
  55238. visibilities.push( 'fragment' );
  55239. }
  55240. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  55241. visibilities.push( 'compute' );
  55242. }
  55243. const bufferVisibility = `(${visibilities.join( ',' )})`;
  55244. const bufferGPU = device.createBuffer( {
  55245. label: `bindingBuffer${binding.id}_${binding.name}_${bufferVisibility}`,
  55246. size: byteLength,
  55247. usage: usage
  55248. } );
  55249. bindingData.buffer = bufferGPU;
  55250. }
  55251. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  55252. } else if ( binding.isStorageBuffer ) {
  55253. const buffer = backend.get( binding.attribute ).buffer;
  55254. entriesGPU.push( { binding: bindingPoint, resource: { buffer: buffer } } );
  55255. } else if ( binding.isSampledTexture ) {
  55256. const textureData = backend.get( binding.texture );
  55257. let resourceGPU;
  55258. if ( textureData.externalTexture !== undefined ) {
  55259. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  55260. } else {
  55261. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  55262. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  55263. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  55264. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  55265. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  55266. }
  55267. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  55268. resourceGPU = textureData[ propertyName ];
  55269. if ( resourceGPU === undefined ) {
  55270. const aspectGPU = GPUTextureAspect.All;
  55271. let dimensionViewGPU;
  55272. if ( binding.isSampledCubeTexture ) {
  55273. dimensionViewGPU = GPUTextureViewDimension.Cube;
  55274. } else if ( binding.isSampledTexture3D ) {
  55275. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  55276. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  55277. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  55278. } else {
  55279. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  55280. }
  55281. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount, baseMipLevel } );
  55282. }
  55283. }
  55284. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  55285. } else if ( binding.isSampler ) {
  55286. const textureGPU = backend.get( binding.texture );
  55287. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  55288. }
  55289. bindingPoint ++;
  55290. }
  55291. return device.createBindGroup( {
  55292. label: 'bindGroup_' + bindGroup.name,
  55293. layout: layoutGPU,
  55294. entries: entriesGPU
  55295. } );
  55296. }
  55297. /**
  55298. * Creates a GPU bind group layout entries for the given bind group.
  55299. *
  55300. * @private
  55301. * @param {BindGroup} bindGroup - The bind group.
  55302. * @return {Array<GPUBindGroupLayoutEntry>} The GPU bind group layout entries.
  55303. */
  55304. _createLayoutEntries( bindGroup ) {
  55305. const entries = [];
  55306. let index = 0;
  55307. for ( const binding of bindGroup.bindings ) {
  55308. const backend = this.backend;
  55309. const bindingGPU = {
  55310. binding: index,
  55311. visibility: binding.visibility
  55312. };
  55313. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  55314. const buffer = {}; // GPUBufferBindingLayout
  55315. if ( binding.isStorageBuffer ) {
  55316. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  55317. // compute
  55318. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  55319. buffer.type = GPUBufferBindingType.Storage;
  55320. } else {
  55321. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  55322. }
  55323. } else {
  55324. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  55325. }
  55326. }
  55327. bindingGPU.buffer = buffer;
  55328. } else if ( binding.isSampledTexture && binding.store ) {
  55329. const storageTexture = {}; // GPUStorageTextureBindingLayout
  55330. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  55331. const access = binding.access;
  55332. if ( access === NodeAccess.READ_WRITE ) {
  55333. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  55334. } else if ( access === NodeAccess.WRITE_ONLY ) {
  55335. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  55336. } else {
  55337. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  55338. }
  55339. if ( binding.texture.isArrayTexture ) {
  55340. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  55341. } else if ( binding.texture.is3DTexture ) {
  55342. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  55343. }
  55344. bindingGPU.storageTexture = storageTexture;
  55345. } else if ( binding.isSampledTexture ) {
  55346. const texture = {}; // GPUTextureBindingLayout
  55347. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  55348. if ( primarySamples > 1 ) {
  55349. texture.multisampled = true;
  55350. if ( ! binding.texture.isDepthTexture ) {
  55351. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  55352. }
  55353. }
  55354. if ( binding.texture.isDepthTexture ) {
  55355. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  55356. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  55357. } else {
  55358. texture.sampleType = GPUTextureSampleType.Depth;
  55359. }
  55360. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture || binding.texture.isStorageTexture ) {
  55361. const type = binding.texture.type;
  55362. if ( type === IntType ) {
  55363. texture.sampleType = GPUTextureSampleType.SInt;
  55364. } else if ( type === UnsignedIntType ) {
  55365. texture.sampleType = GPUTextureSampleType.UInt;
  55366. } else if ( type === FloatType ) {
  55367. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  55368. texture.sampleType = GPUTextureSampleType.Float;
  55369. } else {
  55370. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  55371. }
  55372. }
  55373. }
  55374. if ( binding.isSampledCubeTexture ) {
  55375. texture.viewDimension = GPUTextureViewDimension.Cube;
  55376. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  55377. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  55378. } else if ( binding.isSampledTexture3D ) {
  55379. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  55380. }
  55381. bindingGPU.texture = texture;
  55382. } else if ( binding.isSampler ) {
  55383. const sampler = {}; // GPUSamplerBindingLayout
  55384. if ( binding.texture.isDepthTexture ) {
  55385. if ( binding.texture.compareFunction !== null && backend.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  55386. sampler.type = GPUSamplerBindingType.Comparison;
  55387. } else {
  55388. // Depth textures without compare must use non-filtering sampler
  55389. sampler.type = GPUSamplerBindingType.NonFiltering;
  55390. }
  55391. }
  55392. bindingGPU.sampler = sampler;
  55393. } else {
  55394. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  55395. }
  55396. entries.push( bindingGPU );
  55397. index ++;
  55398. }
  55399. return entries;
  55400. }
  55401. /**
  55402. * Delete the data associated with a bind group.
  55403. *
  55404. * @param {BindGroup} bindGroup - The bind group.
  55405. */
  55406. deleteBindGroupData( bindGroup ) {
  55407. const { backend } = this;
  55408. const bindingsData = backend.get( bindGroup );
  55409. if ( bindingsData.layout ) {
  55410. bindingsData.layout.usedTimes --;
  55411. if ( bindingsData.layout.usedTimes === 0 ) {
  55412. this._bindGroupLayoutCache.delete( bindingsData.layoutKey );
  55413. }
  55414. bindingsData.layout = undefined;
  55415. bindingsData.layoutKey = undefined;
  55416. }
  55417. }
  55418. /**
  55419. * Frees internal resources.
  55420. */
  55421. dispose() {
  55422. this._bindGroupLayoutCache.clear();
  55423. }
  55424. }
  55425. /**
  55426. * A WebGPU backend utility module for managing the device's capabilities.
  55427. *
  55428. * @private
  55429. */
  55430. class WebGPUCapabilities {
  55431. /**
  55432. * Constructs a new utility object.
  55433. *
  55434. * @param {WebGPUBackend} backend - The WebGPU backend.
  55435. */
  55436. constructor( backend ) {
  55437. /**
  55438. * A reference to the WebGPU backend.
  55439. *
  55440. * @type {WebGPUBackend}
  55441. */
  55442. this.backend = backend;
  55443. }
  55444. /**
  55445. * Returns the maximum anisotropy texture filtering value.
  55446. *
  55447. * @return {number} The maximum anisotropy texture filtering value.
  55448. */
  55449. getMaxAnisotropy() {
  55450. return 16;
  55451. }
  55452. /**
  55453. * Returns the maximum number of bytes available for uniform buffers.
  55454. *
  55455. * @return {number} The maximum number of bytes available for uniform buffers.
  55456. */
  55457. getUniformBufferLimit() {
  55458. return this.backend.device.limits.maxUniformBufferBindingSize;
  55459. }
  55460. }
  55461. /**
  55462. * A WebGPU backend utility module for managing pipelines.
  55463. *
  55464. * @private
  55465. */
  55466. class WebGPUPipelineUtils {
  55467. /**
  55468. * Constructs a new utility object.
  55469. *
  55470. * @param {WebGPUBackend} backend - The WebGPU backend.
  55471. */
  55472. constructor( backend ) {
  55473. /**
  55474. * A reference to the WebGPU backend.
  55475. *
  55476. * @type {WebGPUBackend}
  55477. */
  55478. this.backend = backend;
  55479. /**
  55480. * A Weak Map that tracks the active pipeline for render or compute passes.
  55481. *
  55482. * @private
  55483. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  55484. */
  55485. this._activePipelines = new WeakMap();
  55486. }
  55487. /**
  55488. * Sets the given pipeline for the given pass. The method makes sure to only set the
  55489. * pipeline when necessary.
  55490. *
  55491. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  55492. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  55493. */
  55494. setPipeline( pass, pipeline ) {
  55495. const currentPipeline = this._activePipelines.get( pass );
  55496. if ( currentPipeline !== pipeline ) {
  55497. pass.setPipeline( pipeline );
  55498. this._activePipelines.set( pass, pipeline );
  55499. }
  55500. }
  55501. /**
  55502. * Returns the sample count derived from the given render context.
  55503. *
  55504. * @private
  55505. * @param {RenderContext} renderContext - The render context.
  55506. * @return {number} The sample count.
  55507. */
  55508. _getSampleCount( renderContext ) {
  55509. return this.backend.utils.getSampleCountRenderContext( renderContext );
  55510. }
  55511. /**
  55512. * Creates a render pipeline for the given render object.
  55513. *
  55514. * @param {RenderObject} renderObject - The render object.
  55515. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  55516. */
  55517. createRenderPipeline( renderObject, promises ) {
  55518. const { object, material, geometry, pipeline } = renderObject;
  55519. const { vertexProgram, fragmentProgram } = pipeline;
  55520. const backend = this.backend;
  55521. const device = backend.device;
  55522. const utils = backend.utils;
  55523. const pipelineData = backend.get( pipeline );
  55524. // bind group layouts
  55525. const bindGroupLayouts = [];
  55526. for ( const bindGroup of renderObject.getBindings() ) {
  55527. const bindingsData = backend.get( bindGroup );
  55528. const { layoutGPU } = bindingsData.layout;
  55529. bindGroupLayouts.push( layoutGPU );
  55530. }
  55531. // vertex buffers
  55532. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  55533. // material blending
  55534. let materialBlending;
  55535. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  55536. materialBlending = this._getBlending( material );
  55537. }
  55538. // stencil
  55539. let stencilFront = {};
  55540. if ( material.stencilWrite === true ) {
  55541. stencilFront = {
  55542. compare: this._getStencilCompare( material ),
  55543. failOp: this._getStencilOperation( material.stencilFail ),
  55544. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  55545. passOp: this._getStencilOperation( material.stencilZPass )
  55546. };
  55547. }
  55548. const colorWriteMask = this._getColorWriteMask( material );
  55549. const targets = [];
  55550. if ( renderObject.context.textures !== null ) {
  55551. const textures = renderObject.context.textures;
  55552. const mrt = renderObject.context.mrt;
  55553. for ( let i = 0; i < textures.length; i ++ ) {
  55554. const texture = textures[ i ];
  55555. const colorFormat = utils.getTextureFormatGPU( texture );
  55556. // mrt blending
  55557. let blending;
  55558. if ( mrt !== null ) {
  55559. if ( this.backend.compatibilityMode !== true ) {
  55560. const blendMode = mrt.getBlendMode( texture.name );
  55561. if ( blendMode.blending === MaterialBlending ) {
  55562. blending = materialBlending;
  55563. } else if ( blendMode.blending !== NoBlending ) {
  55564. blending = this._getBlending( blendMode );
  55565. }
  55566. } else {
  55567. warnOnce( 'WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.' );
  55568. blending = materialBlending;
  55569. }
  55570. } else {
  55571. blending = materialBlending;
  55572. }
  55573. targets.push( {
  55574. format: colorFormat,
  55575. blend: blending,
  55576. writeMask: colorWriteMask
  55577. } );
  55578. }
  55579. } else {
  55580. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  55581. targets.push( {
  55582. format: colorFormat,
  55583. blend: materialBlending,
  55584. writeMask: colorWriteMask
  55585. } );
  55586. }
  55587. const vertexModule = backend.get( vertexProgram ).module;
  55588. const fragmentModule = backend.get( fragmentProgram ).module;
  55589. const primitiveState = this._getPrimitiveState( object, geometry, material );
  55590. const depthCompare = this._getDepthCompare( material );
  55591. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  55592. const sampleCount = this._getSampleCount( renderObject.context );
  55593. const pipelineDescriptor = {
  55594. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  55595. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  55596. fragment: Object.assign( {}, fragmentModule, { targets } ),
  55597. primitive: primitiveState,
  55598. multisample: {
  55599. count: sampleCount,
  55600. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  55601. },
  55602. layout: device.createPipelineLayout( {
  55603. bindGroupLayouts
  55604. } )
  55605. };
  55606. const depthStencil = {};
  55607. const renderDepth = renderObject.context.depth;
  55608. const renderStencil = renderObject.context.stencil;
  55609. if ( renderDepth === true || renderStencil === true ) {
  55610. if ( renderDepth === true ) {
  55611. depthStencil.format = depthStencilFormat;
  55612. depthStencil.depthWriteEnabled = material.depthWrite;
  55613. depthStencil.depthCompare = depthCompare;
  55614. }
  55615. if ( renderStencil === true ) {
  55616. depthStencil.stencilFront = stencilFront;
  55617. depthStencil.stencilBack = stencilFront; // apply the same stencil ops to both faces, matching gl.stencilOp() which is not face-separated
  55618. depthStencil.stencilReadMask = material.stencilFuncMask;
  55619. depthStencil.stencilWriteMask = material.stencilWriteMask;
  55620. }
  55621. if ( material.polygonOffset === true ) {
  55622. depthStencil.depthBias = material.polygonOffsetUnits;
  55623. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  55624. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  55625. }
  55626. pipelineDescriptor.depthStencil = depthStencil;
  55627. }
  55628. // create pipeline
  55629. device.pushErrorScope( 'validation' );
  55630. if ( promises === null ) {
  55631. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  55632. device.popErrorScope().then( ( err ) => {
  55633. if ( err !== null ) {
  55634. pipelineData.error = true;
  55635. error( err.message );
  55636. }
  55637. } );
  55638. } else {
  55639. const p = new Promise( async ( resolve /*, reject*/ ) => {
  55640. try {
  55641. pipelineData.pipeline = await device.createRenderPipelineAsync( pipelineDescriptor );
  55642. } catch ( err ) { }
  55643. const errorScope = await device.popErrorScope();
  55644. if ( errorScope !== null ) {
  55645. pipelineData.error = true;
  55646. error( errorScope.message );
  55647. }
  55648. resolve();
  55649. } );
  55650. promises.push( p );
  55651. }
  55652. }
  55653. /**
  55654. * Creates GPU render bundle encoder for the given render context.
  55655. *
  55656. * @param {RenderContext} renderContext - The render context.
  55657. * @param {?string} [label='renderBundleEncoder'] - The label.
  55658. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  55659. */
  55660. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  55661. const backend = this.backend;
  55662. const { utils, device } = backend;
  55663. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  55664. const colorFormats = utils.getCurrentColorFormats( renderContext );
  55665. const sampleCount = this._getSampleCount( renderContext );
  55666. const descriptor = {
  55667. label,
  55668. colorFormats,
  55669. depthStencilFormat,
  55670. sampleCount
  55671. };
  55672. return device.createRenderBundleEncoder( descriptor );
  55673. }
  55674. /**
  55675. * Creates a compute pipeline for the given compute node.
  55676. *
  55677. * @param {ComputePipeline} pipeline - The compute pipeline.
  55678. * @param {Array<BindGroup>} bindings - The bindings.
  55679. */
  55680. createComputePipeline( pipeline, bindings ) {
  55681. const backend = this.backend;
  55682. const device = backend.device;
  55683. const computeProgram = backend.get( pipeline.computeProgram ).module;
  55684. const pipelineGPU = backend.get( pipeline );
  55685. // bind group layouts
  55686. const bindGroupLayouts = [];
  55687. for ( const bindingsGroup of bindings ) {
  55688. const bindingsData = backend.get( bindingsGroup );
  55689. const { layoutGPU } = bindingsData.layout;
  55690. bindGroupLayouts.push( layoutGPU );
  55691. }
  55692. pipelineGPU.pipeline = device.createComputePipeline( {
  55693. compute: computeProgram,
  55694. layout: device.createPipelineLayout( {
  55695. bindGroupLayouts
  55696. } )
  55697. } );
  55698. }
  55699. /**
  55700. * Returns the blending state as a descriptor object required
  55701. * for the pipeline creation.
  55702. *
  55703. * @private
  55704. * @param {Material|BlendMode} object - The object containing blending information.
  55705. * @return {Object} The blending state.
  55706. */
  55707. _getBlending( object ) {
  55708. let color, alpha;
  55709. const blending = object.blending;
  55710. const blendSrc = object.blendSrc;
  55711. const blendDst = object.blendDst;
  55712. const blendEquation = object.blendEquation;
  55713. if ( blending === CustomBlending ) {
  55714. const blendSrcAlpha = object.blendSrcAlpha !== null ? object.blendSrcAlpha : blendSrc;
  55715. const blendDstAlpha = object.blendDstAlpha !== null ? object.blendDstAlpha : blendDst;
  55716. const blendEquationAlpha = object.blendEquationAlpha !== null ? object.blendEquationAlpha : blendEquation;
  55717. color = {
  55718. srcFactor: this._getBlendFactor( blendSrc ),
  55719. dstFactor: this._getBlendFactor( blendDst ),
  55720. operation: this._getBlendOperation( blendEquation )
  55721. };
  55722. alpha = {
  55723. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  55724. dstFactor: this._getBlendFactor( blendDstAlpha ),
  55725. operation: this._getBlendOperation( blendEquationAlpha )
  55726. };
  55727. } else {
  55728. const premultipliedAlpha = object.premultipliedAlpha;
  55729. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  55730. color = {
  55731. srcFactor: srcRGB,
  55732. dstFactor: dstRGB,
  55733. operation: GPUBlendOperation.Add
  55734. };
  55735. alpha = {
  55736. srcFactor: srcAlpha,
  55737. dstFactor: dstAlpha,
  55738. operation: GPUBlendOperation.Add
  55739. };
  55740. };
  55741. if ( premultipliedAlpha ) {
  55742. switch ( blending ) {
  55743. case NormalBlending:
  55744. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  55745. break;
  55746. case AdditiveBlending:
  55747. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  55748. break;
  55749. case SubtractiveBlending:
  55750. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  55751. break;
  55752. case MultiplyBlending:
  55753. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  55754. break;
  55755. }
  55756. } else {
  55757. switch ( blending ) {
  55758. case NormalBlending:
  55759. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  55760. break;
  55761. case AdditiveBlending:
  55762. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  55763. break;
  55764. case SubtractiveBlending:
  55765. error( `WebGPURenderer: "SubtractiveBlending" requires "${ object.isMaterial ? 'material' : 'blendMode' }.premultipliedAlpha = true".` );
  55766. break;
  55767. case MultiplyBlending:
  55768. error( `WebGPURenderer: "MultiplyBlending" requires "${ object.isMaterial ? 'material' : 'blendMode' }.premultipliedAlpha = true".` );
  55769. break;
  55770. }
  55771. }
  55772. }
  55773. if ( color !== undefined && alpha !== undefined ) {
  55774. return { color, alpha };
  55775. } else {
  55776. error( 'WebGPURenderer: Invalid blending: ', blending );
  55777. }
  55778. }
  55779. /**
  55780. * Returns the GPU blend factor which is required for the pipeline creation.
  55781. *
  55782. * @private
  55783. * @param {number} blend - The blend factor as a three.js constant.
  55784. * @return {string} The GPU blend factor.
  55785. */
  55786. _getBlendFactor( blend ) {
  55787. let blendFactor;
  55788. switch ( blend ) {
  55789. case ZeroFactor:
  55790. blendFactor = GPUBlendFactor.Zero;
  55791. break;
  55792. case OneFactor:
  55793. blendFactor = GPUBlendFactor.One;
  55794. break;
  55795. case SrcColorFactor:
  55796. blendFactor = GPUBlendFactor.Src;
  55797. break;
  55798. case OneMinusSrcColorFactor:
  55799. blendFactor = GPUBlendFactor.OneMinusSrc;
  55800. break;
  55801. case SrcAlphaFactor:
  55802. blendFactor = GPUBlendFactor.SrcAlpha;
  55803. break;
  55804. case OneMinusSrcAlphaFactor:
  55805. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  55806. break;
  55807. case DstColorFactor:
  55808. blendFactor = GPUBlendFactor.Dst;
  55809. break;
  55810. case OneMinusDstColorFactor:
  55811. blendFactor = GPUBlendFactor.OneMinusDst;
  55812. break;
  55813. case DstAlphaFactor:
  55814. blendFactor = GPUBlendFactor.DstAlpha;
  55815. break;
  55816. case OneMinusDstAlphaFactor:
  55817. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  55818. break;
  55819. case SrcAlphaSaturateFactor:
  55820. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  55821. break;
  55822. case BlendColorFactor:
  55823. blendFactor = GPUBlendFactor.Constant;
  55824. break;
  55825. case OneMinusBlendColorFactor:
  55826. blendFactor = GPUBlendFactor.OneMinusConstant;
  55827. break;
  55828. default:
  55829. error( 'WebGPURenderer: Blend factor not supported.', blend );
  55830. }
  55831. return blendFactor;
  55832. }
  55833. /**
  55834. * Returns the GPU stencil compare function which is required for the pipeline creation.
  55835. *
  55836. * @private
  55837. * @param {Material} material - The material.
  55838. * @return {string} The GPU stencil compare function.
  55839. */
  55840. _getStencilCompare( material ) {
  55841. let stencilCompare;
  55842. const stencilFunc = material.stencilFunc;
  55843. switch ( stencilFunc ) {
  55844. case NeverStencilFunc:
  55845. stencilCompare = GPUCompareFunction.Never;
  55846. break;
  55847. case AlwaysStencilFunc:
  55848. stencilCompare = GPUCompareFunction.Always;
  55849. break;
  55850. case LessStencilFunc:
  55851. stencilCompare = GPUCompareFunction.Less;
  55852. break;
  55853. case LessEqualStencilFunc:
  55854. stencilCompare = GPUCompareFunction.LessEqual;
  55855. break;
  55856. case EqualStencilFunc:
  55857. stencilCompare = GPUCompareFunction.Equal;
  55858. break;
  55859. case GreaterEqualStencilFunc:
  55860. stencilCompare = GPUCompareFunction.GreaterEqual;
  55861. break;
  55862. case GreaterStencilFunc:
  55863. stencilCompare = GPUCompareFunction.Greater;
  55864. break;
  55865. case NotEqualStencilFunc:
  55866. stencilCompare = GPUCompareFunction.NotEqual;
  55867. break;
  55868. default:
  55869. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  55870. }
  55871. return stencilCompare;
  55872. }
  55873. /**
  55874. * Returns the GPU stencil operation which is required for the pipeline creation.
  55875. *
  55876. * @private
  55877. * @param {number} op - A three.js constant defining the stencil operation.
  55878. * @return {string} The GPU stencil operation.
  55879. */
  55880. _getStencilOperation( op ) {
  55881. let stencilOperation;
  55882. switch ( op ) {
  55883. case KeepStencilOp:
  55884. stencilOperation = GPUStencilOperation.Keep;
  55885. break;
  55886. case ZeroStencilOp:
  55887. stencilOperation = GPUStencilOperation.Zero;
  55888. break;
  55889. case ReplaceStencilOp:
  55890. stencilOperation = GPUStencilOperation.Replace;
  55891. break;
  55892. case InvertStencilOp:
  55893. stencilOperation = GPUStencilOperation.Invert;
  55894. break;
  55895. case IncrementStencilOp:
  55896. stencilOperation = GPUStencilOperation.IncrementClamp;
  55897. break;
  55898. case DecrementStencilOp:
  55899. stencilOperation = GPUStencilOperation.DecrementClamp;
  55900. break;
  55901. case IncrementWrapStencilOp:
  55902. stencilOperation = GPUStencilOperation.IncrementWrap;
  55903. break;
  55904. case DecrementWrapStencilOp:
  55905. stencilOperation = GPUStencilOperation.DecrementWrap;
  55906. break;
  55907. default:
  55908. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  55909. }
  55910. return stencilOperation;
  55911. }
  55912. /**
  55913. * Returns the GPU blend operation which is required for the pipeline creation.
  55914. *
  55915. * @private
  55916. * @param {number} blendEquation - A three.js constant defining the blend equation.
  55917. * @return {string} The GPU blend operation.
  55918. */
  55919. _getBlendOperation( blendEquation ) {
  55920. let blendOperation;
  55921. switch ( blendEquation ) {
  55922. case AddEquation:
  55923. blendOperation = GPUBlendOperation.Add;
  55924. break;
  55925. case SubtractEquation:
  55926. blendOperation = GPUBlendOperation.Subtract;
  55927. break;
  55928. case ReverseSubtractEquation:
  55929. blendOperation = GPUBlendOperation.ReverseSubtract;
  55930. break;
  55931. case MinEquation:
  55932. blendOperation = GPUBlendOperation.Min;
  55933. break;
  55934. case MaxEquation:
  55935. blendOperation = GPUBlendOperation.Max;
  55936. break;
  55937. default:
  55938. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  55939. }
  55940. return blendOperation;
  55941. }
  55942. /**
  55943. * Returns the primitive state as a descriptor object required
  55944. * for the pipeline creation.
  55945. *
  55946. * @private
  55947. * @param {Object3D} object - The 3D object.
  55948. * @param {BufferGeometry} geometry - The geometry.
  55949. * @param {Material} material - The material.
  55950. * @return {Object} The primitive state.
  55951. */
  55952. _getPrimitiveState( object, geometry, material ) {
  55953. const descriptor = {};
  55954. const utils = this.backend.utils;
  55955. //
  55956. descriptor.topology = utils.getPrimitiveTopology( object, material );
  55957. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  55958. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  55959. }
  55960. //
  55961. let flipSided = ( material.side === BackSide );
  55962. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  55963. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  55964. //
  55965. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  55966. return descriptor;
  55967. }
  55968. /**
  55969. * Returns the GPU color write mask which is required for the pipeline creation.
  55970. *
  55971. * @private
  55972. * @param {Material} material - The material.
  55973. * @return {number} The GPU color write mask.
  55974. */
  55975. _getColorWriteMask( material ) {
  55976. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  55977. }
  55978. /**
  55979. * Returns the GPU depth compare function which is required for the pipeline creation.
  55980. *
  55981. * @private
  55982. * @param {Material} material - The material.
  55983. * @return {string} The GPU depth compare function.
  55984. */
  55985. _getDepthCompare( material ) {
  55986. let depthCompare;
  55987. if ( material.depthTest === false ) {
  55988. depthCompare = GPUCompareFunction.Always;
  55989. } else {
  55990. const depthFunc = ( this.backend.parameters.reversedDepthBuffer ) ? ReversedDepthFuncs[ material.depthFunc ] : material.depthFunc;
  55991. switch ( depthFunc ) {
  55992. case NeverDepth:
  55993. depthCompare = GPUCompareFunction.Never;
  55994. break;
  55995. case AlwaysDepth:
  55996. depthCompare = GPUCompareFunction.Always;
  55997. break;
  55998. case LessDepth:
  55999. depthCompare = GPUCompareFunction.Less;
  56000. break;
  56001. case LessEqualDepth:
  56002. depthCompare = GPUCompareFunction.LessEqual;
  56003. break;
  56004. case EqualDepth:
  56005. depthCompare = GPUCompareFunction.Equal;
  56006. break;
  56007. case GreaterEqualDepth:
  56008. depthCompare = GPUCompareFunction.GreaterEqual;
  56009. break;
  56010. case GreaterDepth:
  56011. depthCompare = GPUCompareFunction.Greater;
  56012. break;
  56013. case NotEqualDepth:
  56014. depthCompare = GPUCompareFunction.NotEqual;
  56015. break;
  56016. default:
  56017. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  56018. }
  56019. }
  56020. return depthCompare;
  56021. }
  56022. }
  56023. /**
  56024. * Manages a pool of WebGPU timestamp queries for performance measurement.
  56025. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  56026. *
  56027. * @augments TimestampQueryPool
  56028. */
  56029. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  56030. /**
  56031. * Creates a new WebGPU timestamp query pool.
  56032. *
  56033. * @param {GPUDevice} device - The WebGPU device to create queries on.
  56034. * @param {string} type - The type identifier for this query pool.
  56035. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  56036. */
  56037. constructor( device, type, maxQueries = 2048 ) {
  56038. super( maxQueries );
  56039. this.device = device;
  56040. this.type = type;
  56041. this.querySet = this.device.createQuerySet( {
  56042. type: 'timestamp',
  56043. count: this.maxQueries,
  56044. label: `queryset_global_timestamp_${type}`
  56045. } );
  56046. const bufferSize = this.maxQueries * 8;
  56047. this.resolveBuffer = this.device.createBuffer( {
  56048. label: `buffer_timestamp_resolve_${type}`,
  56049. size: bufferSize,
  56050. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  56051. } );
  56052. this.resultBuffer = this.device.createBuffer( {
  56053. label: `buffer_timestamp_result_${type}`,
  56054. size: bufferSize,
  56055. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  56056. } );
  56057. }
  56058. /**
  56059. * Allocates a pair of queries for a given render context.
  56060. *
  56061. * @param {string} uid - A unique identifier for the render context.
  56062. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  56063. */
  56064. allocateQueriesForContext( uid ) {
  56065. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  56066. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  56067. 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() } ).` );
  56068. return null;
  56069. }
  56070. const baseOffset = this.currentQueryIndex;
  56071. this.currentQueryIndex += 2;
  56072. this.queryOffsets.set( uid, baseOffset );
  56073. return baseOffset;
  56074. }
  56075. /**
  56076. * Asynchronously resolves all pending queries and returns the total duration.
  56077. * If there's already a pending resolve operation, returns that promise instead.
  56078. *
  56079. * @async
  56080. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  56081. */
  56082. async resolveQueriesAsync() {
  56083. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  56084. return this.lastValue;
  56085. }
  56086. if ( this.pendingResolve ) {
  56087. return this.pendingResolve;
  56088. }
  56089. this.pendingResolve = this._resolveQueries();
  56090. try {
  56091. const result = await this.pendingResolve;
  56092. return result;
  56093. } finally {
  56094. this.pendingResolve = null;
  56095. }
  56096. }
  56097. /**
  56098. * Internal method to resolve queries and calculate total duration.
  56099. *
  56100. * @async
  56101. * @private
  56102. * @returns {Promise<number>} The total duration in milliseconds.
  56103. */
  56104. async _resolveQueries() {
  56105. if ( this.isDisposed ) {
  56106. return this.lastValue;
  56107. }
  56108. try {
  56109. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  56110. return this.lastValue;
  56111. }
  56112. const currentOffsets = new Map( this.queryOffsets );
  56113. const queryCount = this.currentQueryIndex;
  56114. const bytesUsed = queryCount * 8;
  56115. // Reset state before GPU work
  56116. this.currentQueryIndex = 0;
  56117. this.queryOffsets.clear();
  56118. const commandEncoder = this.device.createCommandEncoder();
  56119. commandEncoder.resolveQuerySet(
  56120. this.querySet,
  56121. 0,
  56122. queryCount,
  56123. this.resolveBuffer,
  56124. 0
  56125. );
  56126. commandEncoder.copyBufferToBuffer(
  56127. this.resolveBuffer,
  56128. 0,
  56129. this.resultBuffer,
  56130. 0,
  56131. bytesUsed
  56132. );
  56133. const commandBuffer = commandEncoder.finish();
  56134. this.device.queue.submit( [ commandBuffer ] );
  56135. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  56136. return this.lastValue;
  56137. }
  56138. // Create and track the mapping operation
  56139. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  56140. if ( this.isDisposed ) {
  56141. if ( this.resultBuffer.mapState === 'mapped' ) {
  56142. this.resultBuffer.unmap();
  56143. }
  56144. return this.lastValue;
  56145. }
  56146. //
  56147. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  56148. const framesDuration = {};
  56149. const frames = [];
  56150. for ( const [ uid, baseOffset ] of currentOffsets ) {
  56151. const match = uid.match( /^(.*):f(\d+)$/ );
  56152. const frame = parseInt( match[ 2 ] );
  56153. if ( frames.includes( frame ) === false ) {
  56154. frames.push( frame );
  56155. }
  56156. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  56157. const startTime = times[ baseOffset ];
  56158. const endTime = times[ baseOffset + 1 ];
  56159. const duration = Number( endTime - startTime ) / 1e6;
  56160. this.timestamps.set( uid, duration );
  56161. framesDuration[ frame ] += duration;
  56162. }
  56163. // Return the total duration of the last frame
  56164. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  56165. this.resultBuffer.unmap();
  56166. this.lastValue = totalDuration;
  56167. this.frames = frames;
  56168. return totalDuration;
  56169. } catch ( e ) {
  56170. error( 'Error resolving queries:', e );
  56171. if ( this.resultBuffer.mapState === 'mapped' ) {
  56172. this.resultBuffer.unmap();
  56173. }
  56174. return this.lastValue;
  56175. }
  56176. }
  56177. /**
  56178. * Dispose of the query pool.
  56179. *
  56180. * @async
  56181. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  56182. */
  56183. async dispose() {
  56184. if ( this.isDisposed ) {
  56185. return;
  56186. }
  56187. this.isDisposed = true;
  56188. // Wait for pending resolve operation
  56189. if ( this.pendingResolve ) {
  56190. try {
  56191. await this.pendingResolve;
  56192. } catch ( e ) {
  56193. error( 'Error waiting for pending resolve:', e );
  56194. }
  56195. }
  56196. // Ensure buffer is unmapped before destroying
  56197. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  56198. try {
  56199. this.resultBuffer.unmap();
  56200. } catch ( e ) {
  56201. error( 'Error unmapping buffer:', e );
  56202. }
  56203. }
  56204. // Destroy resources
  56205. if ( this.querySet ) {
  56206. this.querySet.destroy();
  56207. this.querySet = null;
  56208. }
  56209. if ( this.resolveBuffer ) {
  56210. this.resolveBuffer.destroy();
  56211. this.resolveBuffer = null;
  56212. }
  56213. if ( this.resultBuffer ) {
  56214. this.resultBuffer.destroy();
  56215. this.resultBuffer = null;
  56216. }
  56217. this.queryOffsets.clear();
  56218. this.pendingResolve = null;
  56219. }
  56220. }
  56221. /*// debugger tools
  56222. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  56223. //*/
  56224. const _clearValue = { r: 0, g: 0, b: 0, a: 1 };
  56225. /**
  56226. * A backend implementation targeting WebGPU.
  56227. *
  56228. * @private
  56229. * @augments Backend
  56230. */
  56231. class WebGPUBackend extends Backend {
  56232. /**
  56233. * WebGPUBackend options.
  56234. *
  56235. * @typedef {Object} WebGPUBackend~Options
  56236. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  56237. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  56238. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  56239. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  56240. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  56241. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  56242. * @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.
  56243. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  56244. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  56245. * @property {string} [powerPreference=undefined] - The power preference.
  56246. * @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.
  56247. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  56248. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  56249. */
  56250. /**
  56251. * Constructs a new WebGPU backend.
  56252. *
  56253. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  56254. */
  56255. constructor( parameters = {} ) {
  56256. super( parameters );
  56257. /**
  56258. * This flag can be used for type testing.
  56259. *
  56260. * @type {boolean}
  56261. * @readonly
  56262. * @default true
  56263. */
  56264. this.isWebGPUBackend = true;
  56265. // some parameters require default values other than "undefined"
  56266. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  56267. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  56268. /**
  56269. * Indicates whether the backend is in WebGPU compatibility mode or not.
  56270. * The backend must be initialized before the property can be evaluated.
  56271. *
  56272. * @type {?boolean}
  56273. * @readonly
  56274. * @default null
  56275. */
  56276. this.compatibilityMode = null;
  56277. /**
  56278. * A reference to the device.
  56279. *
  56280. * @type {?GPUDevice}
  56281. * @default null
  56282. */
  56283. this.device = null;
  56284. /**
  56285. * A reference to the default render pass descriptor.
  56286. *
  56287. * @type {?Object}
  56288. * @default null
  56289. */
  56290. this.defaultRenderPassdescriptor = null;
  56291. /**
  56292. * A reference to a backend module holding common utility functions.
  56293. *
  56294. * @type {WebGPUUtils}
  56295. */
  56296. this.utils = new WebGPUUtils( this );
  56297. /**
  56298. * A reference to a backend module holding shader attribute-related
  56299. * utility functions.
  56300. *
  56301. * @type {WebGPUAttributeUtils}
  56302. */
  56303. this.attributeUtils = new WebGPUAttributeUtils( this );
  56304. /**
  56305. * A reference to a backend module holding shader binding-related
  56306. * utility functions.
  56307. *
  56308. * @type {WebGPUBindingUtils}
  56309. */
  56310. this.bindingUtils = new WebGPUBindingUtils( this );
  56311. /**
  56312. * A reference to a backend module holding device capability related
  56313. * utility functions.
  56314. *
  56315. * @type {WebGPUCapabilities}
  56316. */
  56317. this.capabilities = new WebGPUCapabilities( this );
  56318. /**
  56319. * A reference to a backend module holding shader pipeline-related
  56320. * utility functions.
  56321. *
  56322. * @type {WebGPUPipelineUtils}
  56323. */
  56324. this.pipelineUtils = new WebGPUPipelineUtils( this );
  56325. /**
  56326. * A reference to a backend module holding shader texture-related
  56327. * utility functions.
  56328. *
  56329. * @type {WebGPUTextureUtils}
  56330. */
  56331. this.textureUtils = new WebGPUTextureUtils( this );
  56332. /**
  56333. * A map that manages the resolve buffers for occlusion queries.
  56334. *
  56335. * @type {Map<number,GPUBuffer>}
  56336. */
  56337. this.occludedResolveCache = new Map();
  56338. // compatibility checks
  56339. const compatibilityTextureCompare = typeof navigator === 'undefined' ? true : /Android/.test( navigator.userAgent ) === false;
  56340. /**
  56341. * A map of compatibility checks.
  56342. *
  56343. * @type {Object}
  56344. */
  56345. this._compatibility = {
  56346. [ Compatibility.TEXTURE_COMPARE ]: compatibilityTextureCompare
  56347. };
  56348. }
  56349. /**
  56350. * Initializes the backend so it is ready for usage.
  56351. *
  56352. * @async
  56353. * @param {Renderer} renderer - The renderer.
  56354. * @return {Promise} A Promise that resolves when the backend has been initialized.
  56355. */
  56356. async init( renderer ) {
  56357. await super.init( renderer );
  56358. //
  56359. const parameters = this.parameters;
  56360. // create the device if it is not passed with parameters
  56361. let device;
  56362. if ( parameters.device === undefined ) {
  56363. const adapterOptions = {
  56364. powerPreference: parameters.powerPreference,
  56365. featureLevel: 'compatibility'
  56366. };
  56367. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  56368. if ( adapter === null ) {
  56369. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  56370. }
  56371. // feature support
  56372. const features = Object.values( GPUFeatureName );
  56373. const supportedFeatures = [];
  56374. for ( const name of features ) {
  56375. if ( adapter.features.has( name ) ) {
  56376. supportedFeatures.push( name );
  56377. }
  56378. }
  56379. const deviceDescriptor = {
  56380. requiredFeatures: supportedFeatures,
  56381. requiredLimits: parameters.requiredLimits
  56382. };
  56383. device = await adapter.requestDevice( deviceDescriptor );
  56384. } else {
  56385. device = parameters.device;
  56386. }
  56387. this.compatibilityMode = ! device.features.has( 'core-features-and-limits' );
  56388. if ( this.compatibilityMode ) {
  56389. renderer._samples = 0;
  56390. }
  56391. device.lost.then( ( info ) => {
  56392. if ( info.reason === 'destroyed' ) return;
  56393. const deviceLossInfo = {
  56394. api: 'WebGPU',
  56395. message: info.message || 'Unknown reason',
  56396. reason: info.reason || null,
  56397. originalEvent: info
  56398. };
  56399. renderer.onDeviceLost( deviceLossInfo );
  56400. } );
  56401. this.device = device;
  56402. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  56403. this.updateSize();
  56404. }
  56405. /**
  56406. * A reference to the context.
  56407. *
  56408. * @type {?GPUCanvasContext}
  56409. * @default null
  56410. */
  56411. get context() {
  56412. const canvasTarget = this.renderer.getCanvasTarget();
  56413. const canvasData = this.get( canvasTarget );
  56414. let context = canvasData.context;
  56415. if ( context === undefined ) {
  56416. const parameters = this.parameters;
  56417. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  56418. context = parameters.context;
  56419. } else {
  56420. context = canvasTarget.domElement.getContext( 'webgpu' );
  56421. }
  56422. // OffscreenCanvas does not have setAttribute, see #22811
  56423. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  56424. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  56425. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  56426. context.configure( {
  56427. device: this.device,
  56428. format: this.utils.getPreferredCanvasFormat(),
  56429. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  56430. alphaMode: alphaMode,
  56431. toneMapping: {
  56432. mode: toneMappingMode
  56433. }
  56434. } );
  56435. canvasData.context = context;
  56436. }
  56437. return context;
  56438. }
  56439. /**
  56440. * The coordinate system of the backend.
  56441. *
  56442. * @type {number}
  56443. * @readonly
  56444. */
  56445. get coordinateSystem() {
  56446. return WebGPUCoordinateSystem;
  56447. }
  56448. /**
  56449. * This method performs a readback operation by moving buffer data from
  56450. * a storage buffer attribute from the GPU to the CPU.
  56451. *
  56452. * @async
  56453. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  56454. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  56455. */
  56456. async getArrayBufferAsync( attribute ) {
  56457. return await this.attributeUtils.getArrayBufferAsync( attribute );
  56458. }
  56459. /**
  56460. * Returns the backend's rendering context.
  56461. *
  56462. * @return {GPUCanvasContext} The rendering context.
  56463. */
  56464. getContext() {
  56465. return this.context;
  56466. }
  56467. /**
  56468. * Returns the default render pass descriptor.
  56469. *
  56470. * In WebGPU, the default framebuffer must be configured
  56471. * like custom framebuffers so the backend needs a render
  56472. * pass descriptor even when rendering directly to screen.
  56473. *
  56474. * @private
  56475. * @return {Object} The render pass descriptor.
  56476. */
  56477. _getDefaultRenderPassDescriptor() {
  56478. const renderer = this.renderer;
  56479. const canvasTarget = renderer.getCanvasTarget();
  56480. const canvasData = this.get( canvasTarget );
  56481. const samples = renderer.currentSamples;
  56482. let descriptor = canvasData.descriptor;
  56483. if ( descriptor === undefined || canvasData.samples !== samples ) {
  56484. descriptor = {
  56485. colorAttachments: [ {
  56486. view: null
  56487. } ]
  56488. };
  56489. if ( renderer.depth === true || renderer.stencil === true ) {
  56490. descriptor.depthStencilAttachment = {
  56491. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  56492. };
  56493. }
  56494. const colorAttachment = descriptor.colorAttachments[ 0 ];
  56495. if ( samples > 0 ) {
  56496. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  56497. } else {
  56498. colorAttachment.resolveTarget = undefined;
  56499. }
  56500. canvasData.descriptor = descriptor;
  56501. canvasData.samples = samples;
  56502. }
  56503. const colorAttachment = descriptor.colorAttachments[ 0 ];
  56504. if ( samples > 0 ) {
  56505. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  56506. } else {
  56507. colorAttachment.view = this.context.getCurrentTexture().createView();
  56508. }
  56509. return descriptor;
  56510. }
  56511. /**
  56512. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  56513. *
  56514. * @param {RenderContext} renderContext - The render context.
  56515. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  56516. *
  56517. * @private
  56518. */
  56519. _isRenderCameraDepthArray( renderContext ) {
  56520. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  56521. }
  56522. /**
  56523. * Returns the render pass descriptor for the given render context.
  56524. *
  56525. * @private
  56526. * @param {RenderContext} renderContext - The render context.
  56527. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  56528. * @return {Object} The render pass descriptor.
  56529. */
  56530. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  56531. const renderTarget = renderContext.renderTarget;
  56532. const renderTargetData = this.get( renderTarget );
  56533. let descriptors = renderTargetData.descriptors;
  56534. if ( descriptors === undefined ||
  56535. renderTargetData.width !== renderTarget.width ||
  56536. renderTargetData.height !== renderTarget.height ||
  56537. renderTargetData.samples !== renderTarget.samples
  56538. ) {
  56539. descriptors = {};
  56540. renderTargetData.descriptors = descriptors;
  56541. }
  56542. const cacheKey = renderContext.getCacheKey();
  56543. let descriptorBase = descriptors[ cacheKey ];
  56544. if ( descriptorBase === undefined ) {
  56545. const textures = renderContext.textures;
  56546. const textureViews = [];
  56547. let sliceIndex;
  56548. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  56549. for ( let i = 0; i < textures.length; i ++ ) {
  56550. const textureData = this.get( textures[ i ] );
  56551. const viewDescriptor = {
  56552. label: `colorAttachment_${ i }`,
  56553. baseMipLevel: renderContext.activeMipmapLevel,
  56554. mipLevelCount: 1,
  56555. baseArrayLayer: renderContext.activeCubeFace,
  56556. arrayLayerCount: 1,
  56557. dimension: GPUTextureViewDimension.TwoD
  56558. };
  56559. if ( renderTarget.isRenderTarget3D ) {
  56560. sliceIndex = renderContext.activeCubeFace;
  56561. viewDescriptor.baseArrayLayer = 0;
  56562. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  56563. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  56564. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  56565. if ( isRenderCameraDepthArray === true ) {
  56566. const cameras = renderContext.camera.cameras;
  56567. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  56568. const layerViewDescriptor = {
  56569. ...viewDescriptor,
  56570. baseArrayLayer: layer,
  56571. arrayLayerCount: 1,
  56572. dimension: GPUTextureViewDimension.TwoD
  56573. };
  56574. const textureView = textureData.texture.createView( layerViewDescriptor );
  56575. textureViews.push( {
  56576. view: textureView,
  56577. resolveTarget: undefined,
  56578. depthSlice: undefined
  56579. } );
  56580. }
  56581. } else {
  56582. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  56583. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  56584. }
  56585. }
  56586. if ( isRenderCameraDepthArray !== true ) {
  56587. const textureView = textureData.texture.createView( viewDescriptor );
  56588. let view, resolveTarget;
  56589. if ( textureData.msaaTexture !== undefined ) {
  56590. view = textureData.msaaTexture.createView();
  56591. resolveTarget = textureView;
  56592. } else {
  56593. view = textureView;
  56594. resolveTarget = undefined;
  56595. }
  56596. textureViews.push( {
  56597. view,
  56598. resolveTarget,
  56599. depthSlice: sliceIndex
  56600. } );
  56601. }
  56602. }
  56603. descriptorBase = { textureViews };
  56604. if ( renderContext.depth ) {
  56605. const depthTextureData = this.get( renderContext.depthTexture );
  56606. const options = {};
  56607. if ( renderContext.depthTexture.isArrayTexture || renderContext.depthTexture.isCubeTexture ) {
  56608. options.dimension = GPUTextureViewDimension.TwoD;
  56609. options.arrayLayerCount = 1;
  56610. options.baseArrayLayer = renderContext.activeCubeFace;
  56611. }
  56612. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  56613. }
  56614. descriptors[ cacheKey ] = descriptorBase;
  56615. renderTargetData.width = renderTarget.width;
  56616. renderTargetData.height = renderTarget.height;
  56617. renderTargetData.samples = renderTarget.samples;
  56618. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  56619. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  56620. }
  56621. const descriptor = {
  56622. colorAttachments: []
  56623. };
  56624. // Apply dynamic properties to cached views
  56625. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  56626. const viewInfo = descriptorBase.textureViews[ i ];
  56627. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  56628. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  56629. clearValue = colorAttachmentsConfig.clearValue;
  56630. }
  56631. descriptor.colorAttachments.push( {
  56632. view: viewInfo.view,
  56633. depthSlice: viewInfo.depthSlice,
  56634. resolveTarget: viewInfo.resolveTarget,
  56635. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  56636. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  56637. clearValue: clearValue
  56638. } );
  56639. }
  56640. if ( descriptorBase.depthStencilView ) {
  56641. descriptor.depthStencilAttachment = {
  56642. view: descriptorBase.depthStencilView
  56643. };
  56644. }
  56645. return descriptor;
  56646. }
  56647. /**
  56648. * This method is executed at the beginning of a render call and prepares
  56649. * the WebGPU state for upcoming render calls
  56650. *
  56651. * @param {RenderContext} renderContext - The render context.
  56652. */
  56653. beginRender( renderContext ) {
  56654. const renderContextData = this.get( renderContext );
  56655. //
  56656. const device = this.device;
  56657. const occlusionQueryCount = renderContext.occlusionQueryCount;
  56658. let occlusionQuerySet;
  56659. if ( occlusionQueryCount > 0 ) {
  56660. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  56661. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  56662. // Get a reference to the array of objects with queries. The renderContextData property
  56663. // can be changed by another render pass before the buffer.mapAsyc() completes.
  56664. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  56665. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  56666. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  56667. //
  56668. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  56669. renderContextData.occlusionQuerySet = occlusionQuerySet;
  56670. renderContextData.occlusionQueryIndex = 0;
  56671. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  56672. renderContextData.lastOcclusionObject = null;
  56673. }
  56674. let descriptor;
  56675. if ( renderContext.textures === null ) {
  56676. descriptor = this._getDefaultRenderPassDescriptor();
  56677. } else {
  56678. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  56679. }
  56680. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  56681. descriptor.occlusionQuerySet = occlusionQuerySet;
  56682. const depthStencilAttachment = descriptor.depthStencilAttachment;
  56683. if ( renderContext.textures !== null ) {
  56684. const colorAttachments = descriptor.colorAttachments;
  56685. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  56686. const colorAttachment = colorAttachments[ i ];
  56687. if ( renderContext.clearColor ) {
  56688. if ( i === 0 ) {
  56689. colorAttachment.clearValue = renderContext.clearColorValue;
  56690. } else {
  56691. _clearValue.r = 0;
  56692. _clearValue.g = 0;
  56693. _clearValue.b = 0;
  56694. _clearValue.a = 1;
  56695. colorAttachment.clearValue = _clearValue;
  56696. }
  56697. colorAttachment.loadOp = GPULoadOp.Clear;
  56698. } else {
  56699. colorAttachment.loadOp = GPULoadOp.Load;
  56700. }
  56701. colorAttachment.storeOp = GPUStoreOp.Store;
  56702. }
  56703. } else {
  56704. const colorAttachment = descriptor.colorAttachments[ 0 ];
  56705. if ( renderContext.clearColor ) {
  56706. colorAttachment.clearValue = renderContext.clearColorValue;
  56707. colorAttachment.loadOp = GPULoadOp.Clear;
  56708. } else {
  56709. colorAttachment.loadOp = GPULoadOp.Load;
  56710. }
  56711. colorAttachment.storeOp = GPUStoreOp.Store;
  56712. }
  56713. //
  56714. if ( renderContext.depth ) {
  56715. if ( renderContext.clearDepth ) {
  56716. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  56717. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  56718. } else {
  56719. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  56720. }
  56721. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  56722. }
  56723. if ( renderContext.stencil ) {
  56724. if ( renderContext.clearStencil ) {
  56725. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  56726. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  56727. } else {
  56728. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  56729. }
  56730. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  56731. }
  56732. //
  56733. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  56734. // shadow arrays - prepare bundle encoders for each camera in an array camera
  56735. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  56736. const cameras = renderContext.camera.cameras;
  56737. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  56738. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  56739. } else {
  56740. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  56741. }
  56742. // Create bundle encoders for each layer
  56743. renderContextData.bundleEncoders = [];
  56744. renderContextData.bundleSets = [];
  56745. // Create separate bundle encoders for each camera in the array
  56746. for ( let i = 0; i < cameras.length; i ++ ) {
  56747. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  56748. renderContext,
  56749. 'renderBundleArrayCamera_' + i
  56750. );
  56751. // Initialize state tracking for this bundle
  56752. const bundleSets = {
  56753. attributes: {},
  56754. bindingGroups: [],
  56755. pipeline: null,
  56756. index: null
  56757. };
  56758. renderContextData.bundleEncoders.push( bundleEncoder );
  56759. renderContextData.bundleSets.push( bundleSets );
  56760. }
  56761. // We'll complete the bundles in finishRender
  56762. renderContextData.currentPass = null;
  56763. } else {
  56764. const currentPass = encoder.beginRenderPass( descriptor );
  56765. renderContextData.currentPass = currentPass;
  56766. if ( renderContext.viewport ) {
  56767. this.updateViewport( renderContext );
  56768. }
  56769. if ( renderContext.scissor ) {
  56770. this.updateScissor( renderContext );
  56771. }
  56772. }
  56773. //
  56774. renderContextData.descriptor = descriptor;
  56775. renderContextData.encoder = encoder;
  56776. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56777. renderContextData.renderBundles = [];
  56778. }
  56779. /**
  56780. * This method creates layer descriptors for each camera in an array camera
  56781. * to prepare for rendering to a depth array texture.
  56782. *
  56783. * @param {RenderContext} renderContext - The render context.
  56784. * @param {Object} renderContextData - The render context data.
  56785. * @param {Object} descriptor - The render pass descriptor.
  56786. * @param {ArrayCamera} cameras - The array camera.
  56787. *
  56788. * @private
  56789. */
  56790. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  56791. const depthStencilAttachment = descriptor.depthStencilAttachment;
  56792. renderContextData.layerDescriptors = [];
  56793. const depthTextureData = this.get( renderContext.depthTexture );
  56794. if ( ! depthTextureData.viewCache ) {
  56795. depthTextureData.viewCache = [];
  56796. }
  56797. for ( let i = 0; i < cameras.length; i ++ ) {
  56798. const layerDescriptor = {
  56799. ...descriptor,
  56800. colorAttachments: [ {
  56801. ...descriptor.colorAttachments[ 0 ],
  56802. view: descriptor.colorAttachments[ i ].view
  56803. } ]
  56804. };
  56805. if ( descriptor.depthStencilAttachment ) {
  56806. const layerIndex = i;
  56807. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  56808. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  56809. dimension: GPUTextureViewDimension.TwoD,
  56810. baseArrayLayer: i,
  56811. arrayLayerCount: 1
  56812. } );
  56813. }
  56814. layerDescriptor.depthStencilAttachment = {
  56815. view: depthTextureData.viewCache[ layerIndex ],
  56816. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  56817. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  56818. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  56819. };
  56820. if ( renderContext.stencil ) {
  56821. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  56822. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  56823. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  56824. }
  56825. } else {
  56826. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  56827. }
  56828. renderContextData.layerDescriptors.push( layerDescriptor );
  56829. }
  56830. }
  56831. /**
  56832. * This method updates the layer descriptors for each camera in an array camera
  56833. * to prepare for rendering to a depth array texture.
  56834. *
  56835. * @param {RenderContext} renderContext - The render context.
  56836. * @param {Object} renderContextData - The render context data.
  56837. * @param {ArrayCamera} cameras - The array camera.
  56838. *
  56839. */
  56840. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  56841. for ( let i = 0; i < cameras.length; i ++ ) {
  56842. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  56843. if ( layerDescriptor.depthStencilAttachment ) {
  56844. const depthAttachment = layerDescriptor.depthStencilAttachment;
  56845. if ( renderContext.depth ) {
  56846. if ( renderContext.clearDepth ) {
  56847. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  56848. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  56849. } else {
  56850. depthAttachment.depthLoadOp = GPULoadOp.Load;
  56851. }
  56852. }
  56853. if ( renderContext.stencil ) {
  56854. if ( renderContext.clearStencil ) {
  56855. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  56856. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  56857. } else {
  56858. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  56859. }
  56860. }
  56861. }
  56862. }
  56863. }
  56864. /**
  56865. * This method is executed at the end of a render call and finalizes work
  56866. * after draw calls.
  56867. *
  56868. * @param {RenderContext} renderContext - The render context.
  56869. */
  56870. finishRender( renderContext ) {
  56871. const renderContextData = this.get( renderContext );
  56872. const occlusionQueryCount = renderContext.occlusionQueryCount;
  56873. if ( renderContextData.renderBundles.length > 0 ) {
  56874. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  56875. }
  56876. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  56877. renderContextData.currentPass.endOcclusionQuery();
  56878. }
  56879. // shadow arrays - Execute bundles for each layer
  56880. const encoder = renderContextData.encoder;
  56881. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  56882. const bundles = [];
  56883. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  56884. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  56885. bundles.push( bundleEncoder.finish() );
  56886. }
  56887. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  56888. if ( i < bundles.length ) {
  56889. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  56890. const renderPass = encoder.beginRenderPass( layerDescriptor );
  56891. if ( renderContext.viewport ) {
  56892. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  56893. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  56894. }
  56895. if ( renderContext.scissor ) {
  56896. const { x, y, width, height } = renderContext.scissorValue;
  56897. renderPass.setScissorRect( x, y, width, height );
  56898. }
  56899. renderPass.executeBundles( [ bundles[ i ] ] );
  56900. renderPass.end();
  56901. }
  56902. }
  56903. } else if ( renderContextData.currentPass ) {
  56904. renderContextData.currentPass.end();
  56905. }
  56906. if ( occlusionQueryCount > 0 ) {
  56907. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  56908. //
  56909. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  56910. if ( queryResolveBuffer === undefined ) {
  56911. queryResolveBuffer = this.device.createBuffer(
  56912. {
  56913. size: bufferSize,
  56914. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  56915. }
  56916. );
  56917. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  56918. }
  56919. //
  56920. const readBuffer = this.device.createBuffer(
  56921. {
  56922. size: bufferSize,
  56923. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  56924. }
  56925. );
  56926. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  56927. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  56928. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  56929. renderContextData.occlusionQueryBuffer = readBuffer;
  56930. //
  56931. this.resolveOccludedAsync( renderContext );
  56932. }
  56933. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  56934. //
  56935. if ( renderContext.textures !== null ) {
  56936. const textures = renderContext.textures;
  56937. for ( let i = 0; i < textures.length; i ++ ) {
  56938. const texture = textures[ i ];
  56939. if ( texture.generateMipmaps === true ) {
  56940. this.textureUtils.generateMipmaps( texture );
  56941. }
  56942. }
  56943. }
  56944. }
  56945. /**
  56946. * Returns `true` if the given 3D object is fully occluded by other
  56947. * 3D objects in the scene.
  56948. *
  56949. * @param {RenderContext} renderContext - The render context.
  56950. * @param {Object3D} object - The 3D object to test.
  56951. * @return {boolean} Whether the 3D object is fully occluded or not.
  56952. */
  56953. isOccluded( renderContext, object ) {
  56954. const renderContextData = this.get( renderContext );
  56955. return renderContextData.occluded && renderContextData.occluded.has( object );
  56956. }
  56957. /**
  56958. * This method processes the result of occlusion queries and writes it
  56959. * into render context data.
  56960. *
  56961. * @async
  56962. * @param {RenderContext} renderContext - The render context.
  56963. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  56964. */
  56965. async resolveOccludedAsync( renderContext ) {
  56966. const renderContextData = this.get( renderContext );
  56967. // handle occlusion query results
  56968. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  56969. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  56970. const occluded = new WeakSet();
  56971. renderContextData.currentOcclusionQueryObjects = null;
  56972. renderContextData.currentOcclusionQueryBuffer = null;
  56973. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  56974. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  56975. const results = new BigUint64Array( buffer );
  56976. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  56977. if ( results[ i ] === BigInt( 0 ) ) {
  56978. occluded.add( currentOcclusionQueryObjects[ i ] );
  56979. }
  56980. }
  56981. currentOcclusionQueryBuffer.destroy();
  56982. renderContextData.occluded = occluded;
  56983. }
  56984. }
  56985. /**
  56986. * Updates the viewport with the values from the given render context.
  56987. *
  56988. * @param {RenderContext} renderContext - The render context.
  56989. */
  56990. updateViewport( renderContext ) {
  56991. const { currentPass } = this.get( renderContext );
  56992. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  56993. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  56994. }
  56995. /**
  56996. * Updates the scissor with the values from the given render context.
  56997. *
  56998. * @param {RenderContext} renderContext - The render context.
  56999. */
  57000. updateScissor( renderContext ) {
  57001. const { currentPass } = this.get( renderContext );
  57002. const { x, y, width, height } = renderContext.scissorValue;
  57003. currentPass.setScissorRect( x, y, width, height );
  57004. }
  57005. /**
  57006. * Returns the clear color and alpha into a single
  57007. * color object.
  57008. *
  57009. * @return {Color4} The clear color.
  57010. */
  57011. getClearColor() {
  57012. const clearColor = super.getClearColor();
  57013. // only premultiply alpha when alphaMode is "premultiplied"
  57014. if ( this.renderer.alpha === true ) {
  57015. clearColor.r *= clearColor.a;
  57016. clearColor.g *= clearColor.a;
  57017. clearColor.b *= clearColor.a;
  57018. }
  57019. return clearColor;
  57020. }
  57021. /**
  57022. * Performs a clear operation.
  57023. *
  57024. * @param {boolean} color - Whether the color buffer should be cleared or not.
  57025. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  57026. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  57027. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  57028. */
  57029. clear( color, depth, stencil, renderTargetContext = null ) {
  57030. const device = this.device;
  57031. const renderer = this.renderer;
  57032. let colorAttachments = [];
  57033. let depthStencilAttachment;
  57034. let supportsDepth;
  57035. let supportsStencil;
  57036. if ( color ) {
  57037. const clearColor = this.getClearColor();
  57038. _clearValue.r = clearColor.r;
  57039. _clearValue.g = clearColor.g;
  57040. _clearValue.b = clearColor.b;
  57041. _clearValue.a = clearColor.a;
  57042. }
  57043. if ( renderTargetContext === null ) {
  57044. supportsDepth = renderer.depth;
  57045. supportsStencil = renderer.stencil;
  57046. const descriptor = this._getDefaultRenderPassDescriptor();
  57047. if ( color ) {
  57048. colorAttachments = descriptor.colorAttachments;
  57049. const colorAttachment = colorAttachments[ 0 ];
  57050. colorAttachment.clearValue = _clearValue;
  57051. colorAttachment.loadOp = GPULoadOp.Clear;
  57052. colorAttachment.storeOp = GPUStoreOp.Store;
  57053. }
  57054. if ( supportsDepth || supportsStencil ) {
  57055. depthStencilAttachment = descriptor.depthStencilAttachment;
  57056. }
  57057. } else {
  57058. supportsDepth = renderTargetContext.depth;
  57059. supportsStencil = renderTargetContext.stencil;
  57060. const clearConfig = {
  57061. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  57062. clearValue: color ? _clearValue : undefined
  57063. };
  57064. if ( supportsDepth ) {
  57065. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  57066. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  57067. clearConfig.depthStoreOp = GPUStoreOp.Store;
  57068. }
  57069. if ( supportsStencil ) {
  57070. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  57071. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  57072. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  57073. }
  57074. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  57075. colorAttachments = descriptor.colorAttachments;
  57076. depthStencilAttachment = descriptor.depthStencilAttachment;
  57077. }
  57078. if ( supportsDepth && depthStencilAttachment ) {
  57079. if ( depth ) {
  57080. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  57081. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  57082. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  57083. } else {
  57084. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  57085. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  57086. }
  57087. }
  57088. //
  57089. if ( supportsStencil && depthStencilAttachment ) {
  57090. if ( stencil ) {
  57091. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  57092. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  57093. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  57094. } else {
  57095. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  57096. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  57097. }
  57098. }
  57099. //
  57100. const encoder = device.createCommandEncoder( { label: 'clear' } );
  57101. const currentPass = encoder.beginRenderPass( {
  57102. colorAttachments,
  57103. depthStencilAttachment
  57104. } );
  57105. currentPass.end();
  57106. device.queue.submit( [ encoder.finish() ] );
  57107. }
  57108. // compute
  57109. /**
  57110. * This method is executed at the beginning of a compute call and
  57111. * prepares the state for upcoming compute tasks.
  57112. *
  57113. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  57114. */
  57115. beginCompute( computeGroup ) {
  57116. const groupGPU = this.get( computeGroup );
  57117. //
  57118. const descriptor = {
  57119. label: 'computeGroup_' + computeGroup.id
  57120. };
  57121. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  57122. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  57123. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  57124. }
  57125. /**
  57126. * Executes a compute command for the given compute node.
  57127. *
  57128. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  57129. * @param {Node} computeNode - The compute node.
  57130. * @param {Array<BindGroup>} bindings - The bindings.
  57131. * @param {ComputePipeline} pipeline - The compute pipeline.
  57132. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  57133. * - A single number representing count, or
  57134. * - An array [x, y, z] representing dispatch size, or
  57135. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  57136. */
  57137. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  57138. const computeNodeData = this.get( computeNode );
  57139. const { passEncoderGPU } = this.get( computeGroup );
  57140. // pipeline
  57141. const pipelineGPU = this.get( pipeline ).pipeline;
  57142. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  57143. // bind groups
  57144. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  57145. const bindGroup = bindings[ i ];
  57146. const bindingsData = this.get( bindGroup );
  57147. passEncoderGPU.setBindGroup( i, bindingsData.group );
  57148. }
  57149. if ( dispatchSize === null ) {
  57150. dispatchSize = computeNode.dispatchSize || computeNode.count;
  57151. }
  57152. // When the dispatchSize is set with a StorageBuffer from the GPU.
  57153. if ( dispatchSize && dispatchSize.isIndirectStorageBufferAttribute ) {
  57154. const dispatchBuffer = this.get( dispatchSize ).buffer;
  57155. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  57156. return;
  57157. }
  57158. if ( typeof dispatchSize === 'number' ) {
  57159. // If a single number is given, we calculate the dispatch size based on the workgroup size
  57160. const count = dispatchSize;
  57161. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  57162. // cache dispatch size to avoid recalculating it every time
  57163. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  57164. computeNodeData.count = count;
  57165. const workgroupSize = computeNode.workgroupSize;
  57166. let size = workgroupSize[ 0 ];
  57167. for ( let i = 1; i < workgroupSize.length; i ++ )
  57168. size *= workgroupSize[ i ];
  57169. const dispatchCount = Math.ceil( count / size );
  57170. //
  57171. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  57172. dispatchSize = [ dispatchCount, 1, 1 ];
  57173. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  57174. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  57175. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  57176. }
  57177. computeNodeData.dispatchSize = dispatchSize;
  57178. }
  57179. dispatchSize = computeNodeData.dispatchSize;
  57180. }
  57181. //
  57182. passEncoderGPU.dispatchWorkgroups(
  57183. dispatchSize[ 0 ],
  57184. dispatchSize[ 1 ] || 1,
  57185. dispatchSize[ 2 ] || 1
  57186. );
  57187. }
  57188. /**
  57189. * This method is executed at the end of a compute call and
  57190. * finalizes work after compute tasks.
  57191. *
  57192. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  57193. */
  57194. finishCompute( computeGroup ) {
  57195. const groupData = this.get( computeGroup );
  57196. groupData.passEncoderGPU.end();
  57197. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  57198. }
  57199. /**
  57200. * Internal draw function that performs the draw with the given pass encoder.
  57201. *
  57202. * @private
  57203. * @param {RenderObject} renderObject - The render object.
  57204. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  57205. * @param {Object} renderContextData - The render context data object, holding current pass state and occlusion query tracking.
  57206. * @param {GPURenderPipeline} pipelineGPU - The GPU render pipeline.
  57207. * @param {Array<BindGroup>} bindings - The bind groups.
  57208. * @param {Array<BufferAttribute>} vertexBuffers - The vertex buffers.
  57209. * @param {{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} drawParams - The draw parameters.
  57210. * @param {GPURenderPassEncoder|GPURenderBundleEncoder} passEncoderGPU - The GPU pass encoder used for recording draw commands.
  57211. * @param {Object} currentSets - Tracking object for currently set pipeline, attributes, bind groups, and index state.
  57212. */
  57213. _draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, passEncoderGPU, currentSets ) {
  57214. const { object, material, context } = renderObject;
  57215. const index = renderObject.getIndex();
  57216. const hasIndex = ( index !== null );
  57217. // pipeline
  57218. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  57219. currentSets.pipeline = pipelineGPU;
  57220. // bind groups
  57221. const currentBindingGroups = currentSets.bindingGroups;
  57222. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  57223. const bindGroup = bindings[ i ];
  57224. const bindingsData = this.get( bindGroup );
  57225. if ( currentBindingGroups[ i ] !== bindGroup.id ) {
  57226. passEncoderGPU.setBindGroup( i, bindingsData.group );
  57227. currentBindingGroups[ i ] = bindGroup.id;
  57228. }
  57229. }
  57230. // attributes
  57231. // index
  57232. if ( hasIndex === true ) {
  57233. if ( currentSets.index !== index ) {
  57234. const buffer = this.get( index ).buffer;
  57235. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  57236. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  57237. currentSets.index = index;
  57238. }
  57239. }
  57240. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  57241. const vertexBuffer = vertexBuffers[ i ];
  57242. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  57243. const buffer = this.get( vertexBuffer ).buffer;
  57244. passEncoderGPU.setVertexBuffer( i, buffer );
  57245. currentSets.attributes[ i ] = vertexBuffer;
  57246. }
  57247. }
  57248. // stencil
  57249. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  57250. passEncoderGPU.setStencilReference( material.stencilRef );
  57251. renderContextData.currentStencilRef = material.stencilRef;
  57252. }
  57253. if ( object.isBatchedMesh === true ) {
  57254. const starts = object._multiDrawStarts;
  57255. const counts = object._multiDrawCounts;
  57256. const drawCount = object._multiDrawCount;
  57257. let bytesPerElement = ( hasIndex === true ) ? index.array.BYTES_PER_ELEMENT : 1;
  57258. if ( material.wireframe ) {
  57259. bytesPerElement = object.geometry.attributes.position.count > 65535 ? 4 : 2;
  57260. }
  57261. for ( let i = 0; i < drawCount; i ++ ) {
  57262. const count = 1;
  57263. const firstInstance = i;
  57264. if ( hasIndex === true ) {
  57265. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  57266. } else {
  57267. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  57268. }
  57269. info.update( object, counts[ i ], count );
  57270. }
  57271. } else if ( hasIndex === true ) {
  57272. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  57273. const indirect = renderObject.getIndirect();
  57274. if ( indirect !== null ) {
  57275. const buffer = this.get( indirect ).buffer;
  57276. const indirectOffset = renderObject.getIndirectOffset();
  57277. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  57278. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  57279. passEncoderGPU.drawIndexedIndirect( buffer, indirectOffsets[ i ] );
  57280. }
  57281. } else {
  57282. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  57283. }
  57284. info.update( object, indexCount, instanceCount );
  57285. } else {
  57286. const { vertexCount, instanceCount, firstVertex } = drawParams;
  57287. const indirect = renderObject.getIndirect();
  57288. if ( indirect !== null ) {
  57289. const buffer = this.get( indirect ).buffer;
  57290. const indirectOffset = renderObject.getIndirectOffset();
  57291. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  57292. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  57293. passEncoderGPU.drawIndirect( buffer, indirectOffsets[ i ] );
  57294. }
  57295. } else {
  57296. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  57297. }
  57298. info.update( object, vertexCount, instanceCount );
  57299. }
  57300. }
  57301. // render object
  57302. /**
  57303. * Executes a draw command for the given render object.
  57304. *
  57305. * @param {RenderObject} renderObject - The render object to draw.
  57306. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  57307. */
  57308. draw( renderObject, info ) {
  57309. const { object, context, pipeline } = renderObject;
  57310. const renderContextData = this.get( context );
  57311. const pipelineData = this.get( pipeline );
  57312. const pipelineGPU = pipelineData.pipeline;
  57313. // Skip if pipeline has error
  57314. if ( pipelineData.error === true ) return;
  57315. const drawParams = renderObject.getDrawParameters();
  57316. if ( drawParams === null ) return;
  57317. const bindings = renderObject.getBindings();
  57318. // vertex buffers
  57319. const vertexBuffers = renderObject.getVertexBuffers();
  57320. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  57321. const cameraData = this.get( renderObject.camera );
  57322. const cameras = renderObject.camera.cameras;
  57323. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  57324. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  57325. const bindingsData = this.get( cameraIndex );
  57326. const indexesGPU = [];
  57327. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  57328. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  57329. data[ 0 ] = i;
  57330. const { layoutGPU } = bindingsData.layout;
  57331. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, layoutGPU );
  57332. indexesGPU.push( bindGroupIndex );
  57333. }
  57334. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  57335. }
  57336. const pixelRatio = this.renderer.getPixelRatio();
  57337. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  57338. const subCamera = cameras[ i ];
  57339. if ( object.layers.test( subCamera.layers ) ) {
  57340. const vp = subCamera.viewport;
  57341. let pass = renderContextData.currentPass;
  57342. let sets = renderContextData.currentSets;
  57343. if ( renderContextData.bundleEncoders ) {
  57344. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  57345. const bundleSets = renderContextData.bundleSets[ i ];
  57346. pass = bundleEncoder;
  57347. sets = bundleSets;
  57348. }
  57349. if ( vp ) {
  57350. pass.setViewport(
  57351. Math.floor( vp.x * pixelRatio ),
  57352. Math.floor( vp.y * pixelRatio ),
  57353. Math.floor( vp.width * pixelRatio ),
  57354. Math.floor( vp.height * pixelRatio ),
  57355. context.viewportValue.minDepth,
  57356. context.viewportValue.maxDepth
  57357. );
  57358. }
  57359. // Set camera index binding for this layer
  57360. if ( cameraIndex && cameraData.indexesGPU ) {
  57361. const indexPos = bindings.indexOf( cameraIndex );
  57362. pass.setBindGroup( indexPos, cameraData.indexesGPU[ i ] );
  57363. sets.bindingGroups[ indexPos ] = cameraIndex.id;
  57364. }
  57365. this._draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, pass, sets );
  57366. }
  57367. }
  57368. } else {
  57369. // Regular single camera rendering
  57370. if ( renderContextData.currentPass ) {
  57371. // Handle occlusion queries
  57372. if ( renderContextData.occlusionQuerySet !== undefined ) {
  57373. const lastObject = renderContextData.lastOcclusionObject;
  57374. if ( lastObject !== object ) {
  57375. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  57376. renderContextData.currentPass.endOcclusionQuery();
  57377. renderContextData.occlusionQueryIndex ++;
  57378. }
  57379. if ( object.occlusionTest === true ) {
  57380. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  57381. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  57382. }
  57383. renderContextData.lastOcclusionObject = object;
  57384. }
  57385. }
  57386. this._draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, renderContextData.currentPass, renderContextData.currentSets );
  57387. }
  57388. }
  57389. }
  57390. // cache key
  57391. /**
  57392. * Returns `true` if the render pipeline requires an update.
  57393. *
  57394. * @param {RenderObject} renderObject - The render object.
  57395. * @return {boolean} Whether the render pipeline requires an update or not.
  57396. */
  57397. needsRenderUpdate( renderObject ) {
  57398. const data = this.get( renderObject );
  57399. const { object, material } = renderObject;
  57400. const utils = this.utils;
  57401. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  57402. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  57403. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  57404. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  57405. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  57406. let needsUpdate = false;
  57407. if ( data.material !== material || data.materialVersion !== material.version ||
  57408. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  57409. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  57410. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  57411. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  57412. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  57413. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  57414. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  57415. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  57416. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  57417. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  57418. data.primitiveTopology !== primitiveTopology ||
  57419. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  57420. ) {
  57421. data.material = material; data.materialVersion = material.version;
  57422. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  57423. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  57424. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  57425. data.colorWrite = material.colorWrite;
  57426. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  57427. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  57428. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  57429. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  57430. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  57431. data.sampleCount = sampleCount;
  57432. data.colorSpace = colorSpace;
  57433. data.colorFormat = colorFormat;
  57434. data.depthStencilFormat = depthStencilFormat;
  57435. data.primitiveTopology = primitiveTopology;
  57436. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  57437. needsUpdate = true;
  57438. }
  57439. return needsUpdate;
  57440. }
  57441. /**
  57442. * Returns a cache key that is used to identify render pipelines.
  57443. *
  57444. * @param {RenderObject} renderObject - The render object.
  57445. * @return {string} The cache key.
  57446. */
  57447. getRenderCacheKey( renderObject ) {
  57448. const { object, material } = renderObject;
  57449. const utils = this.utils;
  57450. const renderContext = renderObject.context;
  57451. // meshes with negative scale have a different frontFace render pipeline
  57452. // descriptor value so the following must be honored in the cache key
  57453. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  57454. return [
  57455. material.transparent, material.blending, material.premultipliedAlpha,
  57456. material.blendSrc, material.blendDst, material.blendEquation,
  57457. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  57458. material.colorWrite,
  57459. material.depthWrite, material.depthTest, material.depthFunc,
  57460. material.stencilWrite, material.stencilFunc,
  57461. material.stencilFail, material.stencilZFail, material.stencilZPass,
  57462. material.stencilFuncMask, material.stencilWriteMask,
  57463. material.side,
  57464. frontFaceCW,
  57465. utils.getSampleCountRenderContext( renderContext ),
  57466. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  57467. utils.getPrimitiveTopology( object, material ),
  57468. renderObject.getGeometryCacheKey(),
  57469. renderObject.clippingContextCacheKey
  57470. ].join();
  57471. }
  57472. // textures
  57473. /**
  57474. * Updates a GPU sampler for the given texture.
  57475. *
  57476. * @param {Texture} texture - The texture to update the sampler for.
  57477. * @return {string} The current sampler key.
  57478. */
  57479. updateSampler( texture ) {
  57480. return this.textureUtils.updateSampler( texture );
  57481. }
  57482. /**
  57483. * Creates a default texture for the given texture that can be used
  57484. * as a placeholder until the actual texture is ready for usage.
  57485. *
  57486. * @param {Texture} texture - The texture to create a default texture for.
  57487. * @return {boolean} Whether the sampler has been updated or not.
  57488. */
  57489. createDefaultTexture( texture ) {
  57490. return this.textureUtils.createDefaultTexture( texture );
  57491. }
  57492. /**
  57493. * Defines a texture on the GPU for the given texture object.
  57494. *
  57495. * @param {Texture} texture - The texture.
  57496. * @param {Object} [options={}] - Optional configuration parameter.
  57497. */
  57498. createTexture( texture, options ) {
  57499. this.textureUtils.createTexture( texture, options );
  57500. }
  57501. /**
  57502. * Uploads the updated texture data to the GPU.
  57503. *
  57504. * @param {Texture} texture - The texture.
  57505. * @param {Object} [options={}] - Optional configuration parameter.
  57506. */
  57507. updateTexture( texture, options ) {
  57508. this.textureUtils.updateTexture( texture, options );
  57509. }
  57510. /**
  57511. * Generates mipmaps for the given texture.
  57512. *
  57513. * @param {Texture} texture - The texture.
  57514. */
  57515. generateMipmaps( texture ) {
  57516. this.textureUtils.generateMipmaps( texture );
  57517. }
  57518. /**
  57519. * Destroys the GPU data for the given texture object.
  57520. *
  57521. * @param {Texture} texture - The texture.
  57522. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  57523. */
  57524. destroyTexture( texture, isDefaultTexture = false ) {
  57525. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  57526. }
  57527. /**
  57528. * Returns texture data as a typed array.
  57529. *
  57530. * @async
  57531. * @param {Texture} texture - The texture to copy.
  57532. * @param {number} x - The x coordinate of the copy origin.
  57533. * @param {number} y - The y coordinate of the copy origin.
  57534. * @param {number} width - The width of the copy.
  57535. * @param {number} height - The height of the copy.
  57536. * @param {number} faceIndex - The face index.
  57537. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  57538. */
  57539. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  57540. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  57541. }
  57542. /**
  57543. * Inits a time stamp query for the given render context.
  57544. *
  57545. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  57546. * @param {number} uid - Unique id for the context (e.g. render context id).
  57547. * @param {Object} descriptor - The query descriptor.
  57548. */
  57549. initTimestampQuery( type, uid, descriptor ) {
  57550. if ( ! this.trackTimestamp ) return;
  57551. if ( ! this.timestampQueryPool[ type ] ) {
  57552. // TODO: Variable maxQueries?
  57553. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  57554. }
  57555. const timestampQueryPool = this.timestampQueryPool[ type ];
  57556. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  57557. descriptor.timestampWrites = {
  57558. querySet: timestampQueryPool.querySet,
  57559. beginningOfPassWriteIndex: baseOffset,
  57560. endOfPassWriteIndex: baseOffset + 1,
  57561. };
  57562. }
  57563. // node builder
  57564. /**
  57565. * Returns a node builder for the given render object.
  57566. *
  57567. * @param {RenderObject} object - The render object.
  57568. * @param {Renderer} renderer - The renderer.
  57569. * @return {WGSLNodeBuilder} The node builder.
  57570. */
  57571. createNodeBuilder( object, renderer ) {
  57572. return new WGSLNodeBuilder( object, renderer );
  57573. }
  57574. // program
  57575. /**
  57576. * Creates a shader program from the given programmable stage.
  57577. *
  57578. * @param {ProgrammableStage} program - The programmable stage.
  57579. */
  57580. createProgram( program ) {
  57581. const programGPU = this.get( program );
  57582. programGPU.module = {
  57583. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  57584. entryPoint: 'main'
  57585. };
  57586. }
  57587. /**
  57588. * Destroys the shader program of the given programmable stage.
  57589. *
  57590. * @param {ProgrammableStage} program - The programmable stage.
  57591. */
  57592. destroyProgram( program ) {
  57593. this.delete( program );
  57594. }
  57595. // pipelines
  57596. /**
  57597. * Creates a render pipeline for the given render object.
  57598. *
  57599. * @param {RenderObject} renderObject - The render object.
  57600. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  57601. */
  57602. createRenderPipeline( renderObject, promises ) {
  57603. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  57604. }
  57605. /**
  57606. * Creates a compute pipeline for the given compute node.
  57607. *
  57608. * @param {ComputePipeline} computePipeline - The compute pipeline.
  57609. * @param {Array<BindGroup>} bindings - The bindings.
  57610. */
  57611. createComputePipeline( computePipeline, bindings ) {
  57612. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  57613. }
  57614. /**
  57615. * Prepares the state for encoding render bundles.
  57616. *
  57617. * @param {RenderContext} renderContext - The render context.
  57618. */
  57619. beginBundle( renderContext ) {
  57620. const renderContextData = this.get( renderContext );
  57621. renderContextData._currentPass = renderContextData.currentPass;
  57622. renderContextData._currentSets = renderContextData.currentSets;
  57623. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  57624. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  57625. }
  57626. /**
  57627. * After processing render bundles this method finalizes related work.
  57628. *
  57629. * @param {RenderContext} renderContext - The render context.
  57630. * @param {RenderBundle} bundle - The render bundle.
  57631. */
  57632. finishBundle( renderContext, bundle ) {
  57633. const renderContextData = this.get( renderContext );
  57634. const bundleEncoder = renderContextData.currentPass;
  57635. const bundleGPU = bundleEncoder.finish();
  57636. this.get( bundle ).bundleGPU = bundleGPU;
  57637. // restore render pass state
  57638. renderContextData.currentSets = renderContextData._currentSets;
  57639. renderContextData.currentPass = renderContextData._currentPass;
  57640. }
  57641. /**
  57642. * Adds a render bundle to the render context data.
  57643. *
  57644. * @param {RenderContext} renderContext - The render context.
  57645. * @param {RenderBundle} bundle - The render bundle to add.
  57646. */
  57647. addBundle( renderContext, bundle ) {
  57648. const renderContextData = this.get( renderContext );
  57649. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  57650. }
  57651. // bindings
  57652. /**
  57653. * Creates bindings from the given bind group definition.
  57654. *
  57655. * @param {BindGroup} bindGroup - The bind group.
  57656. * @param {Array<BindGroup>} bindings - Array of bind groups.
  57657. * @param {number} cacheIndex - The cache index.
  57658. * @param {number} version - The version.
  57659. */
  57660. createBindings( bindGroup, bindings, cacheIndex, version ) {
  57661. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  57662. }
  57663. /**
  57664. * Updates the given bind group definition.
  57665. *
  57666. * @param {BindGroup} bindGroup - The bind group.
  57667. * @param {Array<BindGroup>} bindings - Array of bind groups.
  57668. * @param {number} cacheIndex - The cache index.
  57669. * @param {number} version - The version.
  57670. */
  57671. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  57672. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  57673. }
  57674. /**
  57675. * Updates a buffer binding.
  57676. *
  57677. * @param {Buffer} binding - The buffer binding to update.
  57678. */
  57679. updateBinding( binding ) {
  57680. this.bindingUtils.updateBinding( binding );
  57681. }
  57682. /**
  57683. * Delete data associated with the current bind group.
  57684. *
  57685. * @param {BindGroup} bindGroup - The bind group.
  57686. */
  57687. deleteBindGroupData( bindGroup ) {
  57688. this.bindingUtils.deleteBindGroupData( bindGroup );
  57689. }
  57690. // attributes
  57691. /**
  57692. * Creates the buffer of an indexed shader attribute.
  57693. *
  57694. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  57695. */
  57696. createIndexAttribute( attribute ) {
  57697. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  57698. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  57699. usage |= GPUBufferUsage.STORAGE;
  57700. }
  57701. this.attributeUtils.createAttribute( attribute, usage );
  57702. }
  57703. /**
  57704. * Creates the GPU buffer of a shader attribute.
  57705. *
  57706. * @param {BufferAttribute} attribute - The buffer attribute.
  57707. */
  57708. createAttribute( attribute ) {
  57709. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  57710. }
  57711. /**
  57712. * Creates the GPU buffer of a storage attribute.
  57713. *
  57714. * @param {BufferAttribute} attribute - The buffer attribute.
  57715. */
  57716. createStorageAttribute( attribute ) {
  57717. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  57718. }
  57719. /**
  57720. * Creates the GPU buffer of an indirect storage attribute.
  57721. *
  57722. * @param {BufferAttribute} attribute - The buffer attribute.
  57723. */
  57724. createIndirectStorageAttribute( attribute ) {
  57725. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  57726. }
  57727. /**
  57728. * Updates the GPU buffer of a shader attribute.
  57729. *
  57730. * @param {BufferAttribute} attribute - The buffer attribute to update.
  57731. */
  57732. updateAttribute( attribute ) {
  57733. this.attributeUtils.updateAttribute( attribute );
  57734. }
  57735. /**
  57736. * Destroys the GPU buffer of a shader attribute.
  57737. *
  57738. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  57739. */
  57740. destroyAttribute( attribute ) {
  57741. this.attributeUtils.destroyAttribute( attribute );
  57742. }
  57743. // canvas
  57744. /**
  57745. * Triggers an update of the default render pass descriptor.
  57746. */
  57747. updateSize() {
  57748. this.delete( this.renderer.getCanvasTarget() );
  57749. }
  57750. // utils public
  57751. /**
  57752. * Checks if the given feature is supported by the backend.
  57753. *
  57754. * @param {string} name - The feature's name.
  57755. * @return {boolean} Whether the feature is supported or not.
  57756. */
  57757. hasFeature( name ) {
  57758. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  57759. return this.device.features.has( name );
  57760. }
  57761. /**
  57762. * Copies data of the given source texture to the given destination texture.
  57763. *
  57764. * @param {Texture} srcTexture - The source texture.
  57765. * @param {Texture} dstTexture - The destination texture.
  57766. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  57767. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  57768. * @param {number} [srcLevel=0] - The mipmap level to copy.
  57769. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  57770. */
  57771. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  57772. let dstX = 0;
  57773. let dstY = 0;
  57774. let dstZ = 0;
  57775. let srcX = 0;
  57776. let srcY = 0;
  57777. let srcZ = 0;
  57778. let srcWidth = srcTexture.image.width;
  57779. let srcHeight = srcTexture.image.height;
  57780. let srcDepth = 1;
  57781. if ( srcRegion !== null ) {
  57782. if ( srcRegion.isBox3 === true ) {
  57783. srcX = srcRegion.min.x;
  57784. srcY = srcRegion.min.y;
  57785. srcZ = srcRegion.min.z;
  57786. srcWidth = srcRegion.max.x - srcRegion.min.x;
  57787. srcHeight = srcRegion.max.y - srcRegion.min.y;
  57788. srcDepth = srcRegion.max.z - srcRegion.min.z;
  57789. } else {
  57790. // Assume it's a Box2
  57791. srcX = srcRegion.min.x;
  57792. srcY = srcRegion.min.y;
  57793. srcWidth = srcRegion.max.x - srcRegion.min.x;
  57794. srcHeight = srcRegion.max.y - srcRegion.min.y;
  57795. srcDepth = 1;
  57796. }
  57797. }
  57798. if ( dstPosition !== null ) {
  57799. dstX = dstPosition.x;
  57800. dstY = dstPosition.y;
  57801. dstZ = dstPosition.z || 0;
  57802. }
  57803. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  57804. const sourceGPU = this.get( srcTexture ).texture;
  57805. const destinationGPU = this.get( dstTexture ).texture;
  57806. encoder.copyTextureToTexture(
  57807. {
  57808. texture: sourceGPU,
  57809. mipLevel: srcLevel,
  57810. origin: { x: srcX, y: srcY, z: srcZ }
  57811. },
  57812. {
  57813. texture: destinationGPU,
  57814. mipLevel: dstLevel,
  57815. origin: { x: dstX, y: dstY, z: dstZ }
  57816. },
  57817. [
  57818. srcWidth,
  57819. srcHeight,
  57820. srcDepth
  57821. ]
  57822. );
  57823. this.device.queue.submit( [ encoder.finish() ] );
  57824. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  57825. this.textureUtils.generateMipmaps( dstTexture );
  57826. }
  57827. }
  57828. /**
  57829. * Copies the current bound framebuffer to the given texture.
  57830. *
  57831. * @param {Texture} texture - The destination texture.
  57832. * @param {RenderContext} renderContext - The render context.
  57833. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  57834. */
  57835. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  57836. const renderContextData = this.get( renderContext );
  57837. let sourceGPU = null;
  57838. if ( renderContext.renderTarget ) {
  57839. if ( texture.isDepthTexture ) {
  57840. sourceGPU = this.get( renderContext.depthTexture ).texture;
  57841. } else {
  57842. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  57843. }
  57844. } else {
  57845. if ( texture.isDepthTexture ) {
  57846. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  57847. } else {
  57848. sourceGPU = this.context.getCurrentTexture();
  57849. }
  57850. }
  57851. const destinationGPU = this.get( texture ).texture;
  57852. if ( sourceGPU.format !== destinationGPU.format ) {
  57853. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  57854. return;
  57855. }
  57856. let encoder;
  57857. if ( renderContextData.currentPass ) {
  57858. renderContextData.currentPass.end();
  57859. encoder = renderContextData.encoder;
  57860. } else {
  57861. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  57862. }
  57863. encoder.copyTextureToTexture(
  57864. {
  57865. texture: sourceGPU,
  57866. origin: [ rectangle.x, rectangle.y, 0 ],
  57867. },
  57868. {
  57869. texture: destinationGPU
  57870. },
  57871. [
  57872. rectangle.z,
  57873. rectangle.w
  57874. ]
  57875. );
  57876. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  57877. // might be out-of-sync, see #31768
  57878. if ( texture.generateMipmaps ) {
  57879. this.textureUtils.generateMipmaps( texture, encoder );
  57880. }
  57881. if ( renderContextData.currentPass ) {
  57882. const { descriptor } = renderContextData;
  57883. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  57884. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  57885. }
  57886. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  57887. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  57888. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  57889. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  57890. if ( renderContext.viewport ) {
  57891. this.updateViewport( renderContext );
  57892. }
  57893. if ( renderContext.scissor ) {
  57894. this.updateScissor( renderContext );
  57895. }
  57896. } else {
  57897. this.device.queue.submit( [ encoder.finish() ] );
  57898. }
  57899. }
  57900. /**
  57901. * Checks if the given compatibility is supported by the backend.
  57902. *
  57903. * @param {string} name - The compatibility name.
  57904. * @return {boolean} Whether the compatibility is supported or not.
  57905. */
  57906. hasCompatibility( name ) {
  57907. if ( this._compatibility[ name ] !== undefined ) {
  57908. return this._compatibility[ name ];
  57909. }
  57910. return super.hasCompatibility( name );
  57911. }
  57912. dispose() {
  57913. this.bindingUtils.dispose();
  57914. this.textureUtils.dispose();
  57915. if ( this.occludedResolveCache ) {
  57916. for ( const buffer of this.occludedResolveCache.values() ) {
  57917. buffer.destroy();
  57918. }
  57919. this.occludedResolveCache.clear();
  57920. }
  57921. if ( this.timestampQueryPool ) {
  57922. for ( const queryPool of Object.values( this.timestampQueryPool ) ) {
  57923. if ( queryPool !== null ) queryPool.dispose();
  57924. }
  57925. }
  57926. if ( this.parameters.device === undefined && this.device !== null ) {
  57927. this.device.destroy();
  57928. }
  57929. }
  57930. }
  57931. /**
  57932. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  57933. *
  57934. * @augments SpotLight
  57935. */
  57936. class IESSpotLight extends SpotLight {
  57937. /**
  57938. * Constructs a new IES spot light.
  57939. *
  57940. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  57941. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  57942. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  57943. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  57944. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  57945. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  57946. */
  57947. constructor( color, intensity, distance, angle, penumbra, decay ) {
  57948. super( color, intensity, distance, angle, penumbra, decay );
  57949. /**
  57950. * The IES map. It's a lookup table that stores normalized attenuation factors
  57951. * (0.0 to 1.0) that represent the light's intensity at a specific angle.
  57952. *
  57953. * @type {?Texture}
  57954. * @default null
  57955. */
  57956. this.iesMap = null;
  57957. }
  57958. copy( source, recursive ) {
  57959. super.copy( source, recursive );
  57960. this.iesMap = source.iesMap;
  57961. return this;
  57962. }
  57963. }
  57964. /**
  57965. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  57966. *
  57967. * @augments SpotLight
  57968. */
  57969. class ProjectorLight extends SpotLight {
  57970. /**
  57971. * Constructs a new projector light.
  57972. *
  57973. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  57974. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  57975. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  57976. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  57977. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  57978. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  57979. */
  57980. constructor( color, intensity, distance, angle, penumbra, decay ) {
  57981. super( color, intensity, distance, angle, penumbra, decay );
  57982. /**
  57983. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  57984. *
  57985. * @type {?number}
  57986. * @default null
  57987. */
  57988. this.aspect = null;
  57989. }
  57990. copy( source, recursive ) {
  57991. super.copy( source, recursive );
  57992. this.aspect = source.aspect;
  57993. return this;
  57994. }
  57995. }
  57996. /**
  57997. * This version of a node library represents the standard version
  57998. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  57999. * techniques and materials to node-based implementations.
  58000. *
  58001. * @private
  58002. * @augments NodeLibrary
  58003. */
  58004. class StandardNodeLibrary extends NodeLibrary {
  58005. /**
  58006. * Constructs a new standard node library.
  58007. */
  58008. constructor() {
  58009. super();
  58010. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  58011. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  58012. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  58013. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  58014. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  58015. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  58016. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  58017. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  58018. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  58019. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  58020. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  58021. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  58022. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  58023. this.addLight( PointLightNode, PointLight );
  58024. this.addLight( DirectionalLightNode, DirectionalLight );
  58025. this.addLight( RectAreaLightNode, RectAreaLight );
  58026. this.addLight( SpotLightNode, SpotLight );
  58027. this.addLight( AmbientLightNode, AmbientLight );
  58028. this.addLight( HemisphereLightNode, HemisphereLight );
  58029. this.addLight( LightProbeNode, LightProbe );
  58030. this.addLight( IESSpotLightNode, IESSpotLight );
  58031. this.addLight( ProjectorLightNode, ProjectorLight );
  58032. this.addToneMapping( linearToneMapping, LinearToneMapping );
  58033. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  58034. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  58035. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  58036. this.addToneMapping( agxToneMapping, AgXToneMapping );
  58037. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  58038. }
  58039. }
  58040. /*
  58041. const debugHandler = {
  58042. get: function ( target, name ) {
  58043. // Add |update
  58044. if ( /^(create|destroy)/.test( name ) ) log( 'WebGPUBackend.' + name );
  58045. return target[ name ];
  58046. }
  58047. };
  58048. */
  58049. /**
  58050. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  58051. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  58052. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  58053. *
  58054. * @augments Renderer
  58055. */
  58056. class WebGPURenderer extends Renderer {
  58057. /**
  58058. * WebGPURenderer options.
  58059. *
  58060. * @typedef {Object} WebGPURenderer~Options
  58061. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  58062. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  58063. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  58064. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  58065. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  58066. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  58067. * @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.
  58068. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  58069. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  58070. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  58071. * @property {number} [outputBufferType=HalfFloatType] - Defines the type of output buffers. The default `HalfFloatType` is recommend for best
  58072. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  58073. */
  58074. /**
  58075. * Constructs a new WebGPU renderer.
  58076. *
  58077. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  58078. */
  58079. constructor( parameters = {} ) {
  58080. let BackendClass;
  58081. if ( parameters.forceWebGL ) {
  58082. BackendClass = WebGLBackend;
  58083. } else {
  58084. BackendClass = WebGPUBackend;
  58085. parameters.getFallback = () => {
  58086. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  58087. return new WebGLBackend( parameters );
  58088. };
  58089. }
  58090. const backend = new BackendClass( parameters );
  58091. //super( new Proxy( backend, debugHandler ) );
  58092. super( backend, parameters );
  58093. /**
  58094. * The generic default value is overwritten with the
  58095. * standard node library for type mapping.
  58096. *
  58097. * @type {StandardNodeLibrary}
  58098. */
  58099. this.library = new StandardNodeLibrary();
  58100. /**
  58101. * This flag can be used for type testing.
  58102. *
  58103. * @type {boolean}
  58104. * @readonly
  58105. * @default true
  58106. */
  58107. this.isWebGPURenderer = true;
  58108. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  58109. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  58110. }
  58111. }
  58112. }
  58113. /**
  58114. * A specialized group which enables applications access to the
  58115. * Render Bundle API of WebGPU. The group with all its descendant nodes
  58116. * are considered as one render bundle and processed as such by
  58117. * the renderer.
  58118. *
  58119. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  58120. * With a WebGL backend, the group can technically be rendered but without
  58121. * any performance improvements.
  58122. *
  58123. * @augments Group
  58124. */
  58125. class BundleGroup extends Group {
  58126. /**
  58127. * Constructs a new bundle group.
  58128. */
  58129. constructor() {
  58130. super();
  58131. /**
  58132. * This flag can be used for type testing.
  58133. *
  58134. * @type {boolean}
  58135. * @readonly
  58136. * @default true
  58137. */
  58138. this.isBundleGroup = true;
  58139. /**
  58140. * This property is only relevant for detecting types
  58141. * during serialization/deserialization. It should always
  58142. * match the class name.
  58143. *
  58144. * @type {string}
  58145. * @readonly
  58146. * @default 'BundleGroup'
  58147. */
  58148. this.type = 'BundleGroup';
  58149. /**
  58150. * Whether the bundle is static or not. When set to `true`, the structure
  58151. * is assumed to be static and does not change. E.g. no new objects are
  58152. * added to the group.
  58153. *
  58154. * If a change is required, an update can still be forced by setting the
  58155. * `needsUpdate` flag to `true`.
  58156. *
  58157. * @type {boolean}
  58158. * @default true
  58159. */
  58160. this.static = true;
  58161. /**
  58162. * The bundle group's version.
  58163. *
  58164. * @type {number}
  58165. * @readonly
  58166. * @default 0
  58167. */
  58168. this.version = 0;
  58169. }
  58170. /**
  58171. * Set this property to `true` when the bundle group has changed.
  58172. *
  58173. * @type {boolean}
  58174. * @default false
  58175. * @param {boolean} value
  58176. */
  58177. set needsUpdate( value ) {
  58178. if ( value === true ) this.version ++;
  58179. }
  58180. }
  58181. /**
  58182. * This module is responsible to manage the rendering pipeline setups in apps.
  58183. * You usually create a single instance of this class and use it to define
  58184. * the output of your render pipeline and post processing effect chain.
  58185. * ```js
  58186. * const renderPipeline = new RenderPipeline( renderer );
  58187. *
  58188. * const scenePass = pass( scene, camera );
  58189. *
  58190. * renderPipeline.outputNode = scenePass;
  58191. * ```
  58192. *
  58193. * Note: This module can only be used with `WebGPURenderer`.
  58194. */
  58195. class RenderPipeline {
  58196. /**
  58197. * Constructs a new render pipeline management module.
  58198. *
  58199. * @param {Renderer} renderer - A reference to the renderer.
  58200. * @param {Node<vec4>} outputNode - An optional output node.
  58201. */
  58202. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  58203. /**
  58204. * A reference to the renderer.
  58205. *
  58206. * @type {Renderer}
  58207. */
  58208. this.renderer = renderer;
  58209. /**
  58210. * A node which defines the final output of the rendering
  58211. * pipeline. This is usually the last node in a chain
  58212. * of effect nodes.
  58213. *
  58214. * @type {Node<vec4>}
  58215. */
  58216. this.outputNode = outputNode;
  58217. /**
  58218. * Whether the default output tone mapping and color
  58219. * space transformation should be enabled or not.
  58220. *
  58221. * This is enabled by default but it must be disabled for
  58222. * effects that expect to be executed after tone mapping and color
  58223. * space conversion. A typical example is FXAA which
  58224. * requires sRGB input.
  58225. *
  58226. * When set to `false`, the app must control the output
  58227. * transformation with `RenderOutputNode`.
  58228. *
  58229. * ```js
  58230. * const outputPass = renderOutput( scenePass );
  58231. * ```
  58232. *
  58233. * @type {boolean}
  58234. */
  58235. this.outputColorTransform = true;
  58236. /**
  58237. * Must be set to `true` when the output node changes.
  58238. *
  58239. * @type {Node<vec4>}
  58240. */
  58241. this.needsUpdate = true;
  58242. const material = new NodeMaterial();
  58243. material.name = 'RenderPipeline';
  58244. /**
  58245. * The full screen quad that is used to render
  58246. * the effects.
  58247. *
  58248. * @private
  58249. * @type {QuadMesh}
  58250. */
  58251. this._quadMesh = new QuadMesh( material );
  58252. this._quadMesh.name = 'Render Pipeline';
  58253. /**
  58254. * The context of the render pipeline stack.
  58255. *
  58256. * @private
  58257. * @type {?Object}
  58258. * @default null
  58259. */
  58260. this._context = null;
  58261. /**
  58262. * The current tone mapping.
  58263. *
  58264. * @private
  58265. * @type {ToneMapping}
  58266. */
  58267. this._toneMapping = renderer.toneMapping;
  58268. /**
  58269. * The current output color space.
  58270. *
  58271. * @private
  58272. * @type {ColorSpace}
  58273. */
  58274. this._outputColorSpace = renderer.outputColorSpace;
  58275. }
  58276. /**
  58277. * When `RenderPipeline` is used to apply rendering pipeline and post processing effects,
  58278. * the application must use this version of `render()` inside
  58279. * its animation loop (not the one from the renderer).
  58280. */
  58281. render() {
  58282. const renderer = this.renderer;
  58283. this._update();
  58284. if ( this._context.onBeforeRenderPipeline !== null ) this._context.onBeforeRenderPipeline();
  58285. const toneMapping = renderer.toneMapping;
  58286. const outputColorSpace = renderer.outputColorSpace;
  58287. renderer.toneMapping = NoToneMapping;
  58288. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  58289. //
  58290. const currentXR = renderer.xr.enabled;
  58291. renderer.xr.enabled = false;
  58292. this._quadMesh.render( renderer );
  58293. renderer.xr.enabled = currentXR;
  58294. //
  58295. renderer.toneMapping = toneMapping;
  58296. renderer.outputColorSpace = outputColorSpace;
  58297. if ( this._context.onAfterRenderPipeline !== null ) this._context.onAfterRenderPipeline();
  58298. }
  58299. /**
  58300. * Returns the current context of the render pipeline stack.
  58301. *
  58302. * @readonly
  58303. * @type {?Object}
  58304. */
  58305. get context() {
  58306. return this._context;
  58307. }
  58308. /**
  58309. * Frees internal resources.
  58310. */
  58311. dispose() {
  58312. this._quadMesh.material.dispose();
  58313. }
  58314. /**
  58315. * Updates the state of the module.
  58316. *
  58317. * @private
  58318. */
  58319. _update() {
  58320. if ( this._toneMapping !== this.renderer.toneMapping ) {
  58321. this._toneMapping = this.renderer.toneMapping;
  58322. this.needsUpdate = true;
  58323. }
  58324. if ( this._outputColorSpace !== this.renderer.outputColorSpace ) {
  58325. this._outputColorSpace = this.renderer.outputColorSpace;
  58326. this.needsUpdate = true;
  58327. }
  58328. if ( this.needsUpdate === true ) {
  58329. const toneMapping = this._toneMapping;
  58330. const outputColorSpace = this._outputColorSpace;
  58331. const context = {
  58332. renderPipeline: this,
  58333. onBeforeRenderPipeline: null,
  58334. onAfterRenderPipeline: null
  58335. };
  58336. let outputNode = this.outputNode;
  58337. if ( this.outputColorTransform === true ) {
  58338. outputNode = outputNode.context( context );
  58339. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  58340. } else {
  58341. context.toneMapping = toneMapping;
  58342. context.outputColorSpace = outputColorSpace;
  58343. outputNode = outputNode.context( context );
  58344. }
  58345. this._context = context;
  58346. this._quadMesh.material.fragmentNode = outputNode;
  58347. this._quadMesh.material.needsUpdate = true;
  58348. this.needsUpdate = false;
  58349. }
  58350. }
  58351. /**
  58352. * When `RenderPipeline` is used to apply rendering pipeline and post processing effects,
  58353. * the application must use this version of `renderAsync()` inside
  58354. * its animation loop (not the one from the renderer).
  58355. *
  58356. * @async
  58357. * @deprecated
  58358. * @return {Promise} A Promise that resolves when the render has been finished.
  58359. */
  58360. async renderAsync() {
  58361. warnOnce( 'RenderPipeline: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  58362. await this.renderer.init();
  58363. this.render();
  58364. }
  58365. }
  58366. /**
  58367. * @deprecated since r183. Use {@link RenderPipeline} instead. PostProcessing has been renamed to RenderPipeline.
  58368. *
  58369. * This class is a wrapper for backward compatibility and will be removed in a future version.
  58370. */
  58371. class PostProcessing extends RenderPipeline {
  58372. /**
  58373. * Constructs a new post processing management module.
  58374. *
  58375. * @param {Renderer} renderer - A reference to the renderer.
  58376. * @param {Node<vec4>} outputNode - An optional output node.
  58377. * @deprecated since r183. Use {@link RenderPipeline} instead.
  58378. */
  58379. constructor( renderer, outputNode ) {
  58380. warnOnce( 'PostProcessing: "PostProcessing" has been renamed to "RenderPipeline". Please update your code to use "THREE.RenderPipeline" instead.' ); // @deprecated, r183
  58381. super( renderer, outputNode );
  58382. }
  58383. }
  58384. /**
  58385. * This special type of texture is intended for compute shaders.
  58386. * It can be used to compute the data of a texture with a compute shader.
  58387. *
  58388. * Note: This type of texture can only be used with `WebGPURenderer`
  58389. * and a WebGPU backend.
  58390. *
  58391. * @augments Texture
  58392. */
  58393. class StorageTexture extends Texture {
  58394. /**
  58395. * Constructs a new storage texture.
  58396. *
  58397. * @param {number} [width=1] - The storage texture's width.
  58398. * @param {number} [height=1] - The storage texture's height.
  58399. */
  58400. constructor( width = 1, height = 1 ) {
  58401. super();
  58402. /**
  58403. * The image object which just represents the texture's dimension.
  58404. *
  58405. * @type {{width: number, height: number}}
  58406. */
  58407. this.image = { width, height };
  58408. /**
  58409. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  58410. *
  58411. * @type {number}
  58412. */
  58413. this.magFilter = LinearFilter;
  58414. /**
  58415. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  58416. *
  58417. * @type {number}
  58418. */
  58419. this.minFilter = LinearFilter;
  58420. /**
  58421. * This flag can be used for type testing.
  58422. *
  58423. * @type {boolean}
  58424. * @readonly
  58425. * @default true
  58426. */
  58427. this.isStorageTexture = true;
  58428. /**
  58429. * When `true`, mipmaps will be auto-generated after compute writes.
  58430. * When `false`, mipmaps must be written manually via compute shaders.
  58431. *
  58432. * @type {boolean}
  58433. * @default true
  58434. */
  58435. this.mipmapsAutoUpdate = true;
  58436. }
  58437. /**
  58438. * Sets the size of the storage texture.
  58439. *
  58440. * @param {number} width - The new width of the storage texture.
  58441. * @param {number} height - The new height of the storage texture.
  58442. */
  58443. setSize( width, height ) {
  58444. if ( this.image.width !== width || this.image.height !== height ) {
  58445. this.image.width = width;
  58446. this.image.height = height;
  58447. this.dispose();
  58448. }
  58449. }
  58450. }
  58451. /**
  58452. * This special type of texture is intended for compute shaders.
  58453. * It can be used to compute the data of a texture with a compute shader.
  58454. *
  58455. * Note: This type of texture can only be used with `WebGPURenderer`
  58456. * and a WebGPU backend.
  58457. *
  58458. * @augments Texture
  58459. */
  58460. class Storage3DTexture extends Texture {
  58461. /**
  58462. * Constructs a new storage texture.
  58463. *
  58464. * @param {number} [width=1] - The storage texture's width.
  58465. * @param {number} [height=1] - The storage texture's height.
  58466. * @param {number} [depth=1] - The storage texture's depth.
  58467. */
  58468. constructor( width = 1, height = 1, depth = 1 ) {
  58469. super();
  58470. //inherited from texture. Must be false for 3DTexture
  58471. this.isArrayTexture = false;
  58472. /**
  58473. * The image object which just represents the texture's dimension.
  58474. *
  58475. * @type {{width: number, height: number, depth: number}}
  58476. */
  58477. this.image = { width, height, depth };
  58478. /**
  58479. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  58480. *
  58481. * @type {number}
  58482. */
  58483. this.magFilter = LinearFilter;
  58484. /**
  58485. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  58486. *
  58487. * @type {number}
  58488. */
  58489. this.minFilter = LinearFilter;
  58490. /**
  58491. * This defines how the texture is wrapped in the depth direction and corresponds to
  58492. * *W* in UVW mapping.
  58493. *
  58494. * @type {number}
  58495. */
  58496. this.wrapR = ClampToEdgeWrapping;
  58497. /**
  58498. * This flag can be used for type testing.
  58499. *
  58500. * @type {boolean}
  58501. * @readonly
  58502. * @default true
  58503. */
  58504. this.isStorageTexture = true;
  58505. /**
  58506. * Indicates whether this texture is a 3D texture.
  58507. *
  58508. * @type {boolean}
  58509. *
  58510. */
  58511. this.is3DTexture = true;
  58512. }
  58513. /**
  58514. * Sets the size of the storage 3d texture.
  58515. *
  58516. * @param {number} width - The new width of the storage texture.
  58517. * @param {number} height - The new height of the storage texture.
  58518. * @param {number} depth - The new depth of the storage texture.
  58519. */
  58520. setSize( width, height, depth ) {
  58521. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  58522. this.image.width = width;
  58523. this.image.height = height;
  58524. this.image.depth = depth;
  58525. this.dispose();
  58526. }
  58527. }
  58528. }
  58529. /**
  58530. * This special type of texture is intended for compute shaders.
  58531. * It can be used to compute the data of a texture with a compute shader.
  58532. *
  58533. * Note: This type of texture can only be used with `WebGPURenderer`
  58534. * and a WebGPU backend.
  58535. *
  58536. * @augments Texture
  58537. */
  58538. class StorageArrayTexture extends Texture {
  58539. /**
  58540. * Constructs a new storage texture.
  58541. *
  58542. * @param {number} [width=1] - The storage texture's width.
  58543. * @param {number} [height=1] - The storage texture's height.
  58544. * @param {number} [depth=1] - The storage texture's depth.
  58545. */
  58546. constructor( width = 1, height = 1, depth = 1 ) {
  58547. super();
  58548. //inherited from texture
  58549. this.isArrayTexture = true;
  58550. /**
  58551. * The image object which just represents the texture's dimension.
  58552. *
  58553. * @type {{width: number, height: number, depth: number}}
  58554. */
  58555. this.image = { width, height, depth };
  58556. /**
  58557. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  58558. *
  58559. * @type {number}
  58560. */
  58561. this.magFilter = LinearFilter;
  58562. /**
  58563. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  58564. *
  58565. * @type {number}
  58566. */
  58567. this.minFilter = LinearFilter;
  58568. /**
  58569. * This flag can be used for type testing.
  58570. *
  58571. * @type {boolean}
  58572. * @readonly
  58573. * @default true
  58574. */
  58575. this.isStorageTexture = true;
  58576. }
  58577. /**
  58578. * Sets the size of the storage array texture.
  58579. *
  58580. * @param {number} width - The new width of the storage texture.
  58581. * @param {number} height - The new height of the storage texture.
  58582. * @param {number} depth - The new depth of the storage texture.
  58583. */
  58584. setSize( width, height, depth ) {
  58585. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  58586. this.image.width = width;
  58587. this.image.height = height;
  58588. this.image.depth = depth;
  58589. this.dispose();
  58590. }
  58591. }
  58592. }
  58593. /**
  58594. * This special type of buffer attribute is intended for compute shaders.
  58595. * It can be used to encode draw parameters for indirect draw calls.
  58596. *
  58597. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  58598. * and a WebGPU backend.
  58599. *
  58600. * @augments StorageBufferAttribute
  58601. */
  58602. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  58603. /**
  58604. * Constructs a new storage buffer attribute.
  58605. *
  58606. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  58607. * The subsequent parameter is then obsolete.
  58608. * @param {number} itemSize - The item size.
  58609. */
  58610. constructor( count, itemSize ) {
  58611. super( count, itemSize, Uint32Array );
  58612. /**
  58613. * This flag can be used for type testing.
  58614. *
  58615. * @type {boolean}
  58616. * @readonly
  58617. * @default true
  58618. */
  58619. this.isIndirectStorageBufferAttribute = true;
  58620. }
  58621. }
  58622. /**
  58623. * A loader for loading node objects in the three.js JSON Object/Scene format.
  58624. *
  58625. * @augments Loader
  58626. */
  58627. class NodeLoader extends Loader {
  58628. /**
  58629. * Constructs a new node loader.
  58630. *
  58631. * @param {LoadingManager} [manager] - A reference to a loading manager.
  58632. */
  58633. constructor( manager ) {
  58634. super( manager );
  58635. /**
  58636. * Represents a dictionary of textures.
  58637. *
  58638. * @type {Object<string,Texture>}
  58639. */
  58640. this.textures = {};
  58641. /**
  58642. * Represents a dictionary of node types.
  58643. *
  58644. * @type {Object<string,Node.constructor>}
  58645. */
  58646. this.nodes = {};
  58647. }
  58648. /**
  58649. * Loads the node definitions from the given URL.
  58650. *
  58651. * @param {string} url - The path/URL of the file to be loaded.
  58652. * @param {Function} onLoad - Will be called when load completes.
  58653. * @param {Function} onProgress - Will be called while load progresses.
  58654. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  58655. */
  58656. load( url, onLoad, onProgress, onError ) {
  58657. const loader = new FileLoader( this.manager );
  58658. loader.setPath( this.path );
  58659. loader.setRequestHeader( this.requestHeader );
  58660. loader.setWithCredentials( this.withCredentials );
  58661. loader.load( url, ( text ) => {
  58662. try {
  58663. onLoad( this.parse( JSON.parse( text ) ) );
  58664. } catch ( e ) {
  58665. if ( onError ) {
  58666. onError( e );
  58667. } else {
  58668. error( e );
  58669. }
  58670. this.manager.itemError( url );
  58671. }
  58672. }, onProgress, onError );
  58673. }
  58674. /**
  58675. * Parse the node dependencies for the loaded node.
  58676. *
  58677. * @param {Array<Object>} [json] - The JSON definition
  58678. * @return {Object<string,Node>} A dictionary with node dependencies.
  58679. */
  58680. parseNodes( json ) {
  58681. const nodes = {};
  58682. if ( json !== undefined ) {
  58683. for ( const nodeJSON of json ) {
  58684. const { uuid, type } = nodeJSON;
  58685. nodes[ uuid ] = this.createNodeFromType( type );
  58686. nodes[ uuid ].uuid = uuid;
  58687. }
  58688. const meta = { nodes, textures: this.textures };
  58689. for ( const nodeJSON of json ) {
  58690. nodeJSON.meta = meta;
  58691. const node = nodes[ nodeJSON.uuid ];
  58692. node.deserialize( nodeJSON );
  58693. delete nodeJSON.meta;
  58694. }
  58695. }
  58696. return nodes;
  58697. }
  58698. /**
  58699. * Parses the node from the given JSON.
  58700. *
  58701. * @param {Object} json - The JSON definition
  58702. * @param {string} json.type - The node type.
  58703. * @param {string} json.uuid - The node UUID.
  58704. * @param {Array<Object>} [json.nodes] - The node dependencies.
  58705. * @param {Object} [json.meta] - The meta data.
  58706. * @return {Node} The parsed node.
  58707. */
  58708. parse( json ) {
  58709. const node = this.createNodeFromType( json.type );
  58710. node.uuid = json.uuid;
  58711. const nodes = this.parseNodes( json.nodes );
  58712. const meta = { nodes, textures: this.textures };
  58713. json.meta = meta;
  58714. node.deserialize( json );
  58715. delete json.meta;
  58716. return node;
  58717. }
  58718. /**
  58719. * Defines the dictionary of textures.
  58720. *
  58721. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  58722. * @return {NodeLoader} A reference to this loader.
  58723. */
  58724. setTextures( value ) {
  58725. this.textures = value;
  58726. return this;
  58727. }
  58728. /**
  58729. * Defines the dictionary of node types.
  58730. *
  58731. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  58732. * @return {NodeLoader} A reference to this loader.
  58733. */
  58734. setNodes( value ) {
  58735. this.nodes = value;
  58736. return this;
  58737. }
  58738. /**
  58739. * Creates a node object from the given type.
  58740. *
  58741. * @param {string} type - The node type.
  58742. * @return {Node} The created node instance.
  58743. */
  58744. createNodeFromType( type ) {
  58745. if ( this.nodes[ type ] === undefined ) {
  58746. error( 'NodeLoader: Node type not found:', type );
  58747. return float();
  58748. }
  58749. return new this.nodes[ type ]();
  58750. }
  58751. }
  58752. /**
  58753. * A special type of material loader for loading node materials.
  58754. *
  58755. * @augments MaterialLoader
  58756. */
  58757. class NodeMaterialLoader extends MaterialLoader {
  58758. /**
  58759. * Constructs a new node material loader.
  58760. *
  58761. * @param {LoadingManager} [manager] - A reference to a loading manager.
  58762. */
  58763. constructor( manager ) {
  58764. super( manager );
  58765. /**
  58766. * Represents a dictionary of node types.
  58767. *
  58768. * @type {Object<string,Node.constructor>}
  58769. */
  58770. this.nodes = {};
  58771. /**
  58772. * Represents a dictionary of node material types.
  58773. *
  58774. * @type {Object<string,NodeMaterial.constructor>}
  58775. */
  58776. this.nodeMaterials = {};
  58777. }
  58778. /**
  58779. * Parses the node material from the given JSON.
  58780. *
  58781. * @param {Object} json - The JSON definition
  58782. * @return {NodeMaterial}. The parsed material.
  58783. */
  58784. parse( json ) {
  58785. const material = super.parse( json );
  58786. const nodes = this.nodes;
  58787. const inputNodes = json.inputNodes;
  58788. for ( const property in inputNodes ) {
  58789. const uuid = inputNodes[ property ];
  58790. material[ property ] = nodes[ uuid ];
  58791. }
  58792. return material;
  58793. }
  58794. /**
  58795. * Defines the dictionary of node types.
  58796. *
  58797. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  58798. * @return {NodeLoader} A reference to this loader.
  58799. */
  58800. setNodes( value ) {
  58801. this.nodes = value;
  58802. return this;
  58803. }
  58804. /**
  58805. * Defines the dictionary of node material types.
  58806. *
  58807. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  58808. * @return {NodeLoader} A reference to this loader.
  58809. */
  58810. setNodeMaterials( value ) {
  58811. this.nodeMaterials = value;
  58812. return this;
  58813. }
  58814. /**
  58815. * Creates a node material from the given type.
  58816. *
  58817. * @param {string} type - The node material type.
  58818. * @return {Node} The created node material instance.
  58819. */
  58820. createMaterialFromType( type ) {
  58821. const materialClass = this.nodeMaterials[ type ];
  58822. if ( materialClass !== undefined ) {
  58823. return new materialClass();
  58824. }
  58825. return super.createMaterialFromType( type );
  58826. }
  58827. }
  58828. /**
  58829. * A special type of object loader for loading 3D objects using
  58830. * node materials.
  58831. *
  58832. * @augments ObjectLoader
  58833. */
  58834. class NodeObjectLoader extends ObjectLoader {
  58835. /**
  58836. * Constructs a new node object loader.
  58837. *
  58838. * @param {LoadingManager} [manager] - A reference to a loading manager.
  58839. */
  58840. constructor( manager ) {
  58841. super( manager );
  58842. /**
  58843. * Represents a dictionary of node types.
  58844. *
  58845. * @type {Object<string,Node.constructor>}
  58846. */
  58847. this.nodes = {};
  58848. /**
  58849. * Represents a dictionary of node material types.
  58850. *
  58851. * @type {Object<string,NodeMaterial.constructor>}
  58852. */
  58853. this.nodeMaterials = {};
  58854. /**
  58855. * A reference to hold the `nodes` JSON property.
  58856. *
  58857. * @private
  58858. * @type {?Object[]}
  58859. */
  58860. this._nodesJSON = null;
  58861. }
  58862. /**
  58863. * Defines the dictionary of node types.
  58864. *
  58865. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  58866. * @return {NodeObjectLoader} A reference to this loader.
  58867. */
  58868. setNodes( value ) {
  58869. this.nodes = value;
  58870. return this;
  58871. }
  58872. /**
  58873. * Defines the dictionary of node material types.
  58874. *
  58875. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  58876. * @return {NodeObjectLoader} A reference to this loader.
  58877. */
  58878. setNodeMaterials( value ) {
  58879. this.nodeMaterials = value;
  58880. return this;
  58881. }
  58882. /**
  58883. * Parses the node objects from the given JSON.
  58884. *
  58885. * @param {Object} json - The JSON definition
  58886. * @param {Function} onLoad - The onLoad callback function.
  58887. * @return {Object3D}. The parsed 3D object.
  58888. */
  58889. parse( json, onLoad ) {
  58890. this._nodesJSON = json.nodes;
  58891. const data = super.parse( json, onLoad );
  58892. this._nodesJSON = null; // dispose
  58893. return data;
  58894. }
  58895. /**
  58896. * Parses the node objects from the given JSON and textures.
  58897. *
  58898. * @param {Object[]} json - The JSON definition
  58899. * @param {Object<string,Texture>} textures - The texture library.
  58900. * @return {Object<string,Node>}. The parsed nodes.
  58901. */
  58902. parseNodes( json, textures ) {
  58903. if ( json !== undefined ) {
  58904. const loader = new NodeLoader();
  58905. loader.setNodes( this.nodes );
  58906. loader.setTextures( textures );
  58907. return loader.parseNodes( json );
  58908. }
  58909. return {};
  58910. }
  58911. /**
  58912. * Parses the node objects from the given JSON and textures.
  58913. *
  58914. * @param {Object} json - The JSON definition
  58915. * @param {Object<string,Texture>} textures - The texture library.
  58916. * @return {Object<string,NodeMaterial>}. The parsed materials.
  58917. */
  58918. parseMaterials( json, textures ) {
  58919. const materials = {};
  58920. if ( json !== undefined ) {
  58921. const nodes = this.parseNodes( this._nodesJSON, textures );
  58922. const loader = new NodeMaterialLoader();
  58923. loader.setTextures( textures );
  58924. loader.setNodes( nodes );
  58925. loader.setNodeMaterials( this.nodeMaterials );
  58926. for ( let i = 0, l = json.length; i < l; i ++ ) {
  58927. const data = json[ i ];
  58928. materials[ data.uuid ] = loader.parse( data );
  58929. }
  58930. }
  58931. return materials;
  58932. }
  58933. }
  58934. /**
  58935. * This version of a node library represents a basic version
  58936. * just focusing on lights and tone mapping techniques.
  58937. *
  58938. * @private
  58939. * @augments NodeLibrary
  58940. */
  58941. class BasicNodeLibrary extends NodeLibrary {
  58942. /**
  58943. * Constructs a new basic node library.
  58944. */
  58945. constructor() {
  58946. super();
  58947. this.addLight( PointLightNode, PointLight );
  58948. this.addLight( DirectionalLightNode, DirectionalLight );
  58949. this.addLight( RectAreaLightNode, RectAreaLight );
  58950. this.addLight( SpotLightNode, SpotLight );
  58951. this.addLight( AmbientLightNode, AmbientLight );
  58952. this.addLight( HemisphereLightNode, HemisphereLight );
  58953. this.addLight( LightProbeNode, LightProbe );
  58954. this.addLight( IESSpotLightNode, IESSpotLight );
  58955. this.addLight( ProjectorLightNode, ProjectorLight );
  58956. this.addToneMapping( linearToneMapping, LinearToneMapping );
  58957. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  58958. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  58959. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  58960. this.addToneMapping( agxToneMapping, AgXToneMapping );
  58961. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  58962. }
  58963. }
  58964. /**
  58965. * In earlier three.js versions, clipping was defined globally
  58966. * on the renderer or on material level. This special version of
  58967. * `THREE.Group` allows to encode the clipping state into the scene
  58968. * graph. Meaning if you create an instance of this group, all
  58969. * descendant 3D objects will be affected by the respective clipping
  58970. * planes.
  58971. *
  58972. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  58973. *
  58974. * @augments Group
  58975. */
  58976. class ClippingGroup extends Group {
  58977. /**
  58978. * Constructs a new clipping group.
  58979. */
  58980. constructor() {
  58981. super();
  58982. /**
  58983. * This flag can be used for type testing.
  58984. *
  58985. * @type {boolean}
  58986. * @readonly
  58987. * @default true
  58988. */
  58989. this.isClippingGroup = true;
  58990. /**
  58991. * An array with clipping planes.
  58992. *
  58993. * @type {Array<Plane>}
  58994. */
  58995. this.clippingPlanes = [];
  58996. /**
  58997. * Whether clipping should be enabled or not.
  58998. *
  58999. * @type {boolean}
  59000. * @default true
  59001. */
  59002. this.enabled = true;
  59003. /**
  59004. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  59005. *
  59006. * @type {boolean}
  59007. * @default false
  59008. */
  59009. this.clipIntersection = false;
  59010. /**
  59011. * Whether shadows should be clipped or not.
  59012. *
  59013. * @type {boolean}
  59014. * @default false
  59015. */
  59016. this.clipShadows = false;
  59017. }
  59018. }
  59019. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AtomicFunctionNode, AttributeNode, BackSide, BarrierNode, BasicEnvironmentNode, BasicLightMapNode, BasicNodeLibrary, BasicShadowMap, BatchNode, BitcastNode, BitcountNode, BlendMode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BuiltinNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CanvasTarget, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, ClippingNode, CodeNode, Color, ColorManagement, ColorSpaceNode, Compatibility, ComputeBuiltinNode, ComputeNode, ConditionalNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeDepthTexture, CubeMapNode, CubeReflectionMapping, CubeRefractionMapping, CubeRenderTarget, 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, EquirectangularReflectionMapping, EquirectangularRefractionMapping, EventDispatcher, EventNode, ExpressionNode, FileLoader, FlipNode, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeBuilder, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InputNode, InspectorBase, InspectorNode, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, IsolateNode, 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, Material, MaterialBlending, MaterialLoader, MaterialNode, MaterialReferenceNode, MathNode, 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, NoNormalPacking, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeError, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalGAPacking, NormalMapNode, NormalRGPacking, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OperatorNode, OrthographicCamera, OutputStructNode, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, PMREMNode, PackFloatNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointShadowNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, R11_EAC_Format, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, 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, ReferenceBaseNode, ReferenceNode, ReflectorNode, ReinhardToneMapping, RenderOutputNode, RenderPipeline, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_Format, SRGBColorSpace, SRGBTransfer, SampleNode, Scene, ScreenNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StackTrace, StaticDrawUsage, Storage3DTexture, StorageArrayElementNode, StorageArrayTexture, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubgroupFunctionNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, TimestampQuery, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnpackFloatNode, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VelocityNode, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLBackend, WebGLCapabilities, WebGLCoordinateSystem, WebGPUBackend, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, WorkgroupInfoNode, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, error, log$1 as log, shaderStages, vectorComponents, warn, warnOnce };
粤ICP备19079148号