three.webgpu.nodes.js 1.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966
  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, NearestFilter, Sphere, BackSide, DoubleSide, Euler, 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, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, NormalBlending, SrcAlphaFactor, OneMinusSrcAlphaFactor, AddEquation, MaterialBlending, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, VSMShadowMap, GreaterEqualCompare, LessEqualCompare, PCFShadowMap, PCFSoftShadowMap, BasicShadowMap, CubeDepthTexture, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, FrustumArray, Frustum, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, 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, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, UnsignedInt101111Type, AlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, 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, GreaterCompare, 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, 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. * This class is used by {@link WebGPURenderer} as management component.
  74. * It's primary purpose is to determine whether render objects require a
  75. * refresh right before they are going to be rendered or not.
  76. */
  77. class NodeMaterialObserver {
  78. /**
  79. * Constructs a new node material observer.
  80. *
  81. * @param {NodeBuilder} builder - The node builder.
  82. */
  83. constructor( builder ) {
  84. /**
  85. * A node material can be used by more than one render object so the
  86. * monitor must maintain a list of render objects.
  87. *
  88. * @type {WeakMap<RenderObject,Object>}
  89. */
  90. this.renderObjects = new WeakMap();
  91. /**
  92. * Whether the material uses node objects or not.
  93. *
  94. * @type {boolean}
  95. */
  96. this.hasNode = this.containsNode( builder );
  97. /**
  98. * Whether the node builder's 3D object is animated or not.
  99. *
  100. * @type {boolean}
  101. */
  102. this.hasAnimation = builder.object.isSkinnedMesh === true;
  103. /**
  104. * A list of all possible material uniforms
  105. *
  106. * @type {Array<string>}
  107. */
  108. this.refreshUniforms = refreshUniforms;
  109. /**
  110. * Holds the current render ID from the node frame.
  111. *
  112. * @type {number}
  113. * @default 0
  114. */
  115. this.renderId = 0;
  116. }
  117. /**
  118. * Returns `true` if the given render object is verified for the first time of this observer.
  119. *
  120. * @param {RenderObject} renderObject - The render object.
  121. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  122. */
  123. firstInitialization( renderObject ) {
  124. const hasInitialized = this.renderObjects.has( renderObject );
  125. if ( hasInitialized === false ) {
  126. this.getRenderObjectData( renderObject );
  127. return true;
  128. }
  129. return false;
  130. }
  131. /**
  132. * Returns `true` if the current rendering produces motion vectors.
  133. *
  134. * @param {Renderer} renderer - The renderer.
  135. * @return {boolean} Whether the current rendering produces motion vectors or not.
  136. */
  137. needsVelocity( renderer ) {
  138. const mrt = renderer.getMRT();
  139. return ( mrt !== null && mrt.has( 'velocity' ) );
  140. }
  141. /**
  142. * Returns monitoring data for the given render object.
  143. *
  144. * @param {RenderObject} renderObject - The render object.
  145. * @return {Object} The monitoring data.
  146. */
  147. getRenderObjectData( renderObject ) {
  148. let data = this.renderObjects.get( renderObject );
  149. if ( data === undefined ) {
  150. const { geometry, material, object } = renderObject;
  151. data = {
  152. material: this.getMaterialData( material ),
  153. geometry: {
  154. id: geometry.id,
  155. attributes: this.getAttributesData( geometry.attributes ),
  156. indexId: geometry.index ? geometry.index.id : null,
  157. indexVersion: geometry.index ? geometry.index.version : null,
  158. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  159. },
  160. worldMatrix: object.matrixWorld.clone()
  161. };
  162. if ( object.center ) {
  163. data.center = object.center.clone();
  164. }
  165. if ( object.morphTargetInfluences ) {
  166. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  167. }
  168. if ( renderObject.bundle !== null ) {
  169. data.version = renderObject.bundle.version;
  170. }
  171. if ( data.material.transmission > 0 ) {
  172. const { width, height } = renderObject.context;
  173. data.bufferWidth = width;
  174. data.bufferHeight = height;
  175. }
  176. data.lights = this.getLightsData( renderObject.lightsNode.getLights() );
  177. this.renderObjects.set( renderObject, data );
  178. }
  179. return data;
  180. }
  181. /**
  182. * Returns an attribute data structure holding the attributes versions for
  183. * monitoring.
  184. *
  185. * @param {Object} attributes - The geometry attributes.
  186. * @return {Object} An object for monitoring the versions of attributes.
  187. */
  188. getAttributesData( attributes ) {
  189. const attributesData = {};
  190. for ( const name in attributes ) {
  191. const attribute = attributes[ name ];
  192. attributesData[ name ] = {
  193. id: attribute.id,
  194. version: attribute.version,
  195. };
  196. }
  197. return attributesData;
  198. }
  199. /**
  200. * Returns `true` if the node builder's material uses
  201. * node properties.
  202. *
  203. * @param {NodeBuilder} builder - The current node builder.
  204. * @return {boolean} Whether the node builder's material uses node properties or not.
  205. */
  206. containsNode( builder ) {
  207. const material = builder.material;
  208. for ( const property in material ) {
  209. if ( material[ property ] && material[ property ].isNode )
  210. return true;
  211. }
  212. if ( builder.context.modelViewMatrix || builder.context.modelNormalViewMatrix || builder.context.getAO || builder.context.getShadow )
  213. return true;
  214. return false;
  215. }
  216. /**
  217. * Returns a material data structure holding the material property values for
  218. * monitoring.
  219. *
  220. * @param {Material} material - The material.
  221. * @return {Object} An object for monitoring material properties.
  222. */
  223. getMaterialData( material ) {
  224. const data = {};
  225. for ( const property of this.refreshUniforms ) {
  226. const value = material[ property ];
  227. if ( value === null || value === undefined ) continue;
  228. if ( typeof value === 'object' && value.clone !== undefined ) {
  229. if ( value.isTexture === true ) {
  230. data[ property ] = { id: value.id, version: value.version };
  231. } else {
  232. data[ property ] = value.clone();
  233. }
  234. } else {
  235. data[ property ] = value;
  236. }
  237. }
  238. return data;
  239. }
  240. /**
  241. * Returns `true` if the given render object has not changed its state.
  242. *
  243. * @param {RenderObject} renderObject - The render object.
  244. * @param {Array<Light>} lightsData - The current material lights.
  245. * @return {boolean} Whether the given render object has changed its state or not.
  246. */
  247. equals( renderObject, lightsData ) {
  248. const { object, material, geometry } = renderObject;
  249. const renderObjectData = this.getRenderObjectData( renderObject );
  250. // world matrix
  251. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  252. renderObjectData.worldMatrix.copy( object.matrixWorld );
  253. return false;
  254. }
  255. // material
  256. const materialData = renderObjectData.material;
  257. for ( const property in materialData ) {
  258. const value = materialData[ property ];
  259. const mtlValue = material[ property ];
  260. if ( value.equals !== undefined ) {
  261. if ( value.equals( mtlValue ) === false ) {
  262. value.copy( mtlValue );
  263. return false;
  264. }
  265. } else if ( mtlValue.isTexture === true ) {
  266. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  267. value.id = mtlValue.id;
  268. value.version = mtlValue.version;
  269. return false;
  270. }
  271. } else if ( value !== mtlValue ) {
  272. materialData[ property ] = mtlValue;
  273. return false;
  274. }
  275. }
  276. if ( materialData.transmission > 0 ) {
  277. const { width, height } = renderObject.context;
  278. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  279. renderObjectData.bufferWidth = width;
  280. renderObjectData.bufferHeight = height;
  281. return false;
  282. }
  283. }
  284. // geometry
  285. const storedGeometryData = renderObjectData.geometry;
  286. const attributes = geometry.attributes;
  287. const storedAttributes = storedGeometryData.attributes;
  288. const storedAttributeNames = Object.keys( storedAttributes );
  289. const currentAttributeNames = Object.keys( attributes );
  290. if ( storedGeometryData.id !== geometry.id ) {
  291. storedGeometryData.id = geometry.id;
  292. return false;
  293. }
  294. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  295. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  296. return false;
  297. }
  298. // compare each attribute
  299. for ( const name of storedAttributeNames ) {
  300. const storedAttributeData = storedAttributes[ name ];
  301. const attribute = attributes[ name ];
  302. if ( attribute === undefined ) {
  303. // attribute was removed
  304. delete storedAttributes[ name ];
  305. return false;
  306. }
  307. if ( storedAttributeData.id !== attribute.id || storedAttributeData.version !== attribute.version ) {
  308. storedAttributeData.id = attribute.id;
  309. storedAttributeData.version = attribute.version;
  310. return false;
  311. }
  312. }
  313. // check index
  314. const index = geometry.index;
  315. const storedIndexId = storedGeometryData.id;
  316. const storedIndexVersion = storedGeometryData.indexVersion;
  317. const currentIndexId = index ? index.id : null;
  318. const currentIndexVersion = index ? index.version : null;
  319. if ( storedIndexId !== currentIndexId || storedIndexVersion !== currentIndexVersion ) {
  320. storedGeometryData.id = currentIndexId;
  321. storedGeometryData.indexVersion = currentIndexVersion;
  322. return false;
  323. }
  324. // check drawRange
  325. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  326. storedGeometryData.drawRange.start = geometry.drawRange.start;
  327. storedGeometryData.drawRange.count = geometry.drawRange.count;
  328. return false;
  329. }
  330. // morph targets
  331. if ( renderObjectData.morphTargetInfluences ) {
  332. let morphChanged = false;
  333. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  334. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  335. renderObjectData.morphTargetInfluences[ i ] = object.morphTargetInfluences[ i ];
  336. morphChanged = true;
  337. }
  338. }
  339. if ( morphChanged ) return false;
  340. }
  341. // lights
  342. if ( renderObjectData.lights ) {
  343. for ( let i = 0; i < lightsData.length; i ++ ) {
  344. if ( renderObjectData.lights[ i ].map !== lightsData[ i ].map ) {
  345. return false;
  346. }
  347. }
  348. }
  349. // center
  350. if ( renderObjectData.center ) {
  351. if ( renderObjectData.center.equals( object.center ) === false ) {
  352. renderObjectData.center.copy( object.center );
  353. return true;
  354. }
  355. }
  356. // bundle
  357. if ( renderObject.bundle !== null ) {
  358. renderObjectData.version = renderObject.bundle.version;
  359. }
  360. return true;
  361. }
  362. /**
  363. * Returns the lights data for the given material lights.
  364. *
  365. * @param {Array<Light>} materialLights - The material lights.
  366. * @return {Array<Object>} The lights data for the given material lights.
  367. */
  368. getLightsData( materialLights ) {
  369. const lights = [];
  370. for ( const light of materialLights ) {
  371. if ( light.isSpotLight === true && light.map !== null ) {
  372. // only add lights that have a map
  373. lights.push( { map: light.map.version } );
  374. }
  375. }
  376. return lights;
  377. }
  378. /**
  379. * Returns the lights for the given lights node and render ID.
  380. *
  381. * @param {LightsNode} lightsNode - The lights node.
  382. * @param {number} renderId - The render ID.
  383. * @return {Array<Object>} The lights for the given lights node and render ID.
  384. */
  385. getLights( lightsNode, renderId ) {
  386. if ( _lightsCache.has( lightsNode ) ) {
  387. const cached = _lightsCache.get( lightsNode );
  388. if ( cached.renderId === renderId ) {
  389. return cached.lightsData;
  390. }
  391. }
  392. const lightsData = this.getLightsData( lightsNode.getLights() );
  393. _lightsCache.set( lightsNode, { renderId, lightsData } );
  394. return lightsData;
  395. }
  396. /**
  397. * Checks if the given render object requires a refresh.
  398. *
  399. * @param {RenderObject} renderObject - The render object.
  400. * @param {NodeFrame} nodeFrame - The current node frame.
  401. * @return {boolean} Whether the given render object requires a refresh or not.
  402. */
  403. needsRefresh( renderObject, nodeFrame ) {
  404. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  405. return true;
  406. const { renderId } = nodeFrame;
  407. if ( this.renderId !== renderId ) {
  408. this.renderId = renderId;
  409. return true;
  410. }
  411. const isStatic = renderObject.object.static === true;
  412. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  413. if ( isStatic || isBundle )
  414. return false;
  415. const lightsData = this.getLights( renderObject.lightsNode, renderId );
  416. const notEqual = this.equals( renderObject, lightsData ) !== true;
  417. return notEqual;
  418. }
  419. }
  420. // Pre-compiled RegExp patterns for ignored files
  421. const IGNORED_FILES = [
  422. /^StackTrace\.js$/,
  423. /^TSLCore\.js$/,
  424. /^.*Node\.js$/,
  425. /^three\.webgpu.*\.js$/
  426. ];
  427. /**
  428. * Parses the stack trace and filters out ignored files.
  429. * Returns an array with function name, file, line, and column.
  430. */
  431. function getFilteredStack( stack ) {
  432. // Pattern to extract function name, file, line, and column from different browsers
  433. // Chrome: "at functionName (file.js:1:2)" or "at file.js:1:2"
  434. // Firefox: "functionName@file.js:1:2"
  435. const regex = /(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;
  436. return stack.split( '\n' )
  437. .map( line => {
  438. const match = line.match( regex );
  439. if ( ! match ) return null; // Skip if line format is invalid
  440. // Chrome: match[1], Firefox: match[2]
  441. const fn = match[ 1 ] || match[ 2 ] || '';
  442. const file = match[ 3 ].split( '?' )[ 0 ]; // Clean file name (Vite/HMR)
  443. const lineNum = parseInt( match[ 4 ], 10 );
  444. const column = parseInt( match[ 5 ], 10 );
  445. // Extract only the filename from full path
  446. const fileName = file.split( '/' ).pop();
  447. return {
  448. fn: fn,
  449. file: fileName,
  450. line: lineNum,
  451. column: column
  452. };
  453. } )
  454. .filter( frame => {
  455. // Only keep frames that are valid and not in the ignore list
  456. return frame && ! IGNORED_FILES.some( regex => regex.test( frame.file ) );
  457. } );
  458. }
  459. /**
  460. * Class representing a stack trace for debugging purposes.
  461. */
  462. class StackTrace {
  463. /**
  464. * Creates a StackTrace instance by capturing and filtering the current stack trace.
  465. *
  466. * @param {Error|string|null} stackMessage - An optional stack trace to use instead of capturing a new one.
  467. */
  468. constructor( stackMessage = null ) {
  469. /**
  470. * This flag can be used for type testing.
  471. *
  472. * @type {boolean}
  473. * @readonly
  474. * @default true
  475. */
  476. this.isStackTrace = true;
  477. /**
  478. * The stack trace.
  479. *
  480. * @type {Array<{fn: string, file: string, line: number, column: number}>}
  481. */
  482. this.stack = getFilteredStack( stackMessage ? stackMessage : new Error().stack );
  483. }
  484. /**
  485. * Returns a formatted location string of the top stack frame.
  486. *
  487. * @returns {string} The formatted stack trace message.
  488. */
  489. getLocation() {
  490. if ( this.stack.length === 0 ) {
  491. return '[Unknown location]';
  492. }
  493. const mainStack = this.stack[ 0 ];
  494. const fn = mainStack.fn;
  495. const fnName = fn ? `"${ fn }()" at ` : '';
  496. return `${fnName}"${mainStack.file}:${mainStack.line}"`; // :${mainStack.column}
  497. }
  498. /**
  499. * Returns the full error message including the stack trace.
  500. *
  501. * @param {string} message - The error message.
  502. * @returns {string} The full error message with stack trace.
  503. */
  504. getError( message ) {
  505. if ( this.stack.length === 0 ) {
  506. return message;
  507. }
  508. // Output: "Error: message\n at functionName (file.js:line:column)"
  509. const stackString = this.stack.map( frame => {
  510. const location = `${ frame.file }:${ frame.line }:${ frame.column }`;
  511. if ( frame.fn ) {
  512. return ` at ${ frame.fn } (${ location })`;
  513. }
  514. return ` at ${ location }`;
  515. } ).join( '\n' );
  516. return `${ message }\n${ stackString }`;
  517. }
  518. }
  519. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  520. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  521. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  522. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  523. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  524. function cyrb53( value, seed = 0 ) {
  525. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  526. if ( value instanceof Array ) {
  527. for ( let i = 0, val; i < value.length; i ++ ) {
  528. val = value[ i ];
  529. h1 = Math.imul( h1 ^ val, 2654435761 );
  530. h2 = Math.imul( h2 ^ val, 1597334677 );
  531. }
  532. } else {
  533. for ( let i = 0, ch; i < value.length; i ++ ) {
  534. ch = value.charCodeAt( i );
  535. h1 = Math.imul( h1 ^ ch, 2654435761 );
  536. h2 = Math.imul( h2 ^ ch, 1597334677 );
  537. }
  538. }
  539. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  540. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  541. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  542. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  543. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  544. }
  545. /**
  546. * Computes a hash for the given string.
  547. *
  548. * @private
  549. * @method
  550. * @param {string} str - The string to be hashed.
  551. * @return {number} The hash.
  552. */
  553. const hashString = ( str ) => cyrb53( str );
  554. /**
  555. * Computes a hash for the given array.
  556. *
  557. * @private
  558. * @method
  559. * @param {Array<number>} array - The array to be hashed.
  560. * @return {number} The hash.
  561. */
  562. const hashArray = ( array ) => cyrb53( array );
  563. /**
  564. * Computes a hash for the given list of parameters.
  565. *
  566. * @private
  567. * @method
  568. * @param {...number} params - A list of parameters.
  569. * @return {number} The hash.
  570. */
  571. const hash$1 = ( ...params ) => cyrb53( params );
  572. const typeFromLength = /*@__PURE__*/ new Map( [
  573. [ 1, 'float' ],
  574. [ 2, 'vec2' ],
  575. [ 3, 'vec3' ],
  576. [ 4, 'vec4' ],
  577. [ 9, 'mat3' ],
  578. [ 16, 'mat4' ]
  579. ] );
  580. const dataFromObject = /*@__PURE__*/ new WeakMap();
  581. /**
  582. * Returns the data type for the given the length.
  583. *
  584. * @private
  585. * @method
  586. * @param {number} length - The length.
  587. * @return {string} The data type.
  588. */
  589. function getTypeFromLength( length ) {
  590. return typeFromLength.get( length );
  591. }
  592. /**
  593. * Returns the typed array for the given data type.
  594. *
  595. * @private
  596. * @method
  597. * @param {string} type - The data type.
  598. * @return {TypedArray} The typed array.
  599. */
  600. function getTypedArrayFromType( type ) {
  601. // Handle component type for vectors and matrices
  602. if ( /[iu]?vec\d/.test( type ) ) {
  603. // Handle int vectors
  604. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  605. // Handle uint vectors
  606. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  607. // Default to float vectors
  608. return Float32Array;
  609. }
  610. // Handle matrices (always float)
  611. if ( /mat\d/.test( type ) ) return Float32Array;
  612. // Basic types
  613. if ( /float/.test( type ) ) return Float32Array;
  614. if ( /uint/.test( type ) ) return Uint32Array;
  615. if ( /int/.test( type ) ) return Int32Array;
  616. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  617. }
  618. /**
  619. * Returns the length for the given data type.
  620. *
  621. * @private
  622. * @method
  623. * @param {string} type - The data type.
  624. * @return {number} The length.
  625. */
  626. function getLengthFromType( type ) {
  627. if ( /float|int|uint/.test( type ) ) return 1;
  628. if ( /vec2/.test( type ) ) return 2;
  629. if ( /vec3/.test( type ) ) return 3;
  630. if ( /vec4/.test( type ) ) return 4;
  631. if ( /mat2/.test( type ) ) return 4;
  632. if ( /mat3/.test( type ) ) return 9;
  633. if ( /mat4/.test( type ) ) return 16;
  634. error( `TSL: Unsupported type: ${ type }`, new StackTrace() );
  635. }
  636. /**
  637. * Returns the gpu memory length for the given data type.
  638. *
  639. * @private
  640. * @method
  641. * @param {string} type - The data type.
  642. * @return {number} The length.
  643. */
  644. function getMemoryLengthFromType( type ) {
  645. if ( /float|int|uint/.test( type ) ) return 1;
  646. if ( /vec2/.test( type ) ) return 2;
  647. if ( /vec3/.test( type ) ) return 3;
  648. if ( /vec4/.test( type ) ) return 4;
  649. if ( /mat2/.test( type ) ) return 4;
  650. if ( /mat3/.test( type ) ) return 12;
  651. if ( /mat4/.test( type ) ) return 16;
  652. error( `TSL: Unsupported type: ${ type }`, new StackTrace() );
  653. }
  654. /**
  655. * Returns the alignment requirement for the given data type.
  656. *
  657. * @private
  658. * @method
  659. * @param {string} type - The data type.
  660. * @return {number} The alignment requirement in bytes.
  661. */
  662. function getAlignmentFromType( type ) {
  663. if ( /float|int|uint/.test( type ) ) return 4;
  664. if ( /vec2/.test( type ) ) return 8;
  665. if ( /vec3/.test( type ) ) return 16;
  666. if ( /vec4/.test( type ) ) return 16;
  667. if ( /mat2/.test( type ) ) return 8;
  668. if ( /mat3/.test( type ) ) return 16;
  669. if ( /mat4/.test( type ) ) return 16;
  670. error( `TSL: Unsupported type: ${ type }`, new StackTrace() );
  671. }
  672. /**
  673. * Returns the data type for the given value.
  674. *
  675. * @private
  676. * @method
  677. * @param {any} value - The value.
  678. * @return {?string} The data type.
  679. */
  680. function getValueType( value ) {
  681. if ( value === undefined || value === null ) return null;
  682. const typeOf = typeof value;
  683. if ( value.isNode === true ) {
  684. return 'node';
  685. } else if ( typeOf === 'number' ) {
  686. return 'float';
  687. } else if ( typeOf === 'boolean' ) {
  688. return 'bool';
  689. } else if ( typeOf === 'string' ) {
  690. return 'string';
  691. } else if ( typeOf === 'function' ) {
  692. return 'shader';
  693. } else if ( value.isVector2 === true ) {
  694. return 'vec2';
  695. } else if ( value.isVector3 === true ) {
  696. return 'vec3';
  697. } else if ( value.isVector4 === true ) {
  698. return 'vec4';
  699. } else if ( value.isMatrix2 === true ) {
  700. return 'mat2';
  701. } else if ( value.isMatrix3 === true ) {
  702. return 'mat3';
  703. } else if ( value.isMatrix4 === true ) {
  704. return 'mat4';
  705. } else if ( value.isColor === true ) {
  706. return 'color';
  707. } else if ( value instanceof ArrayBuffer ) {
  708. return 'ArrayBuffer';
  709. }
  710. return null;
  711. }
  712. /**
  713. * Returns the value/object for the given data type and parameters.
  714. *
  715. * @private
  716. * @method
  717. * @param {string} type - The given type.
  718. * @param {...any} params - A parameter list.
  719. * @return {any} The value/object.
  720. */
  721. function getValueFromType( type, ...params ) {
  722. const last4 = type ? type.slice( -4 ) : undefined;
  723. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  724. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  725. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  726. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  727. }
  728. if ( type === 'color' ) {
  729. return new Color( ...params );
  730. } else if ( last4 === 'vec2' ) {
  731. return new Vector2( ...params );
  732. } else if ( last4 === 'vec3' ) {
  733. return new Vector3( ...params );
  734. } else if ( last4 === 'vec4' ) {
  735. return new Vector4( ...params );
  736. } else if ( last4 === 'mat2' ) {
  737. return new Matrix2( ...params );
  738. } else if ( last4 === 'mat3' ) {
  739. return new Matrix3( ...params );
  740. } else if ( last4 === 'mat4' ) {
  741. return new Matrix4( ...params );
  742. } else if ( type === 'bool' ) {
  743. return params[ 0 ] || false;
  744. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  745. return params[ 0 ] || 0;
  746. } else if ( type === 'string' ) {
  747. return params[ 0 ] || '';
  748. } else if ( type === 'ArrayBuffer' ) {
  749. return base64ToArrayBuffer( params[ 0 ] );
  750. }
  751. return null;
  752. }
  753. /**
  754. * Gets the object data that can be shared between different rendering steps.
  755. *
  756. * @private
  757. * @param {Object} object - The object to get the data for.
  758. * @return {Object} The object data.
  759. */
  760. function getDataFromObject( object ) {
  761. let data = dataFromObject.get( object );
  762. if ( data === undefined ) {
  763. data = {};
  764. dataFromObject.set( object, data );
  765. }
  766. return data;
  767. }
  768. /**
  769. * Converts the given array buffer to a Base64 string.
  770. *
  771. * @private
  772. * @method
  773. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  774. * @return {string} The Base64 string.
  775. */
  776. function arrayBufferToBase64( arrayBuffer ) {
  777. let chars = '';
  778. const array = new Uint8Array( arrayBuffer );
  779. for ( let i = 0; i < array.length; i ++ ) {
  780. chars += String.fromCharCode( array[ i ] );
  781. }
  782. return btoa( chars );
  783. }
  784. /**
  785. * Converts the given Base64 string to an array buffer.
  786. *
  787. * @private
  788. * @method
  789. * @param {string} base64 - The Base64 string.
  790. * @return {ArrayBuffer} The array buffer.
  791. */
  792. function base64ToArrayBuffer( base64 ) {
  793. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  794. }
  795. var NodeUtils = /*#__PURE__*/Object.freeze({
  796. __proto__: null,
  797. arrayBufferToBase64: arrayBufferToBase64,
  798. base64ToArrayBuffer: base64ToArrayBuffer,
  799. getAlignmentFromType: getAlignmentFromType,
  800. getDataFromObject: getDataFromObject,
  801. getLengthFromType: getLengthFromType,
  802. getMemoryLengthFromType: getMemoryLengthFromType,
  803. getTypeFromLength: getTypeFromLength,
  804. getTypedArrayFromType: getTypedArrayFromType,
  805. getValueFromType: getValueFromType,
  806. getValueType: getValueType,
  807. hash: hash$1,
  808. hashArray: hashArray,
  809. hashString: hashString
  810. });
  811. /**
  812. * Possible shader stages.
  813. *
  814. * @property {string} VERTEX The vertex shader stage.
  815. * @property {string} FRAGMENT The fragment shader stage.
  816. */
  817. const NodeShaderStage = {
  818. VERTEX: 'vertex',
  819. FRAGMENT: 'fragment'
  820. };
  821. /**
  822. * Update types of a node.
  823. *
  824. * @property {string} NONE The update method is not executed.
  825. * @property {string} FRAME The update method is executed per frame.
  826. * @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.
  827. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  828. */
  829. const NodeUpdateType = {
  830. NONE: 'none',
  831. FRAME: 'frame',
  832. RENDER: 'render',
  833. OBJECT: 'object'
  834. };
  835. /**
  836. * Data types of a node.
  837. *
  838. * @property {string} BOOLEAN Boolean type.
  839. * @property {string} INTEGER Integer type.
  840. * @property {string} FLOAT Float type.
  841. * @property {string} VECTOR2 Two-dimensional vector type.
  842. * @property {string} VECTOR3 Three-dimensional vector type.
  843. * @property {string} VECTOR4 Four-dimensional vector type.
  844. * @property {string} MATRIX2 2x2 matrix type.
  845. * @property {string} MATRIX3 3x3 matrix type.
  846. * @property {string} MATRIX4 4x4 matrix type.
  847. */
  848. const NodeType = {
  849. BOOLEAN: 'bool',
  850. INTEGER: 'int',
  851. FLOAT: 'float',
  852. VECTOR2: 'vec2',
  853. VECTOR3: 'vec3',
  854. VECTOR4: 'vec4',
  855. MATRIX2: 'mat2',
  856. MATRIX3: 'mat3',
  857. MATRIX4: 'mat4'
  858. };
  859. /**
  860. * Access types of a node. These are relevant for compute and storage usage.
  861. *
  862. * @property {string} READ_ONLY Read-only access
  863. * @property {string} WRITE_ONLY Write-only access.
  864. * @property {string} READ_WRITE Read and write access.
  865. */
  866. const NodeAccess = {
  867. READ_ONLY: 'readOnly',
  868. WRITE_ONLY: 'writeOnly',
  869. READ_WRITE: 'readWrite',
  870. };
  871. const defaultShaderStages = [ 'fragment', 'vertex' ];
  872. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  873. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  874. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  875. const _parentBuildStage = {
  876. analyze: 'setup',
  877. generate: 'analyze'
  878. };
  879. let _nodeId = 0;
  880. /**
  881. * Base class for all nodes.
  882. *
  883. * @augments EventDispatcher
  884. */
  885. class Node extends EventDispatcher {
  886. static get type() {
  887. return 'Node';
  888. }
  889. /**
  890. * Constructs a new node.
  891. *
  892. * @param {?string} nodeType - The node type.
  893. */
  894. constructor( nodeType = null ) {
  895. super();
  896. /**
  897. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  898. *
  899. * @type {?string}
  900. * @default null
  901. */
  902. this.nodeType = nodeType;
  903. /**
  904. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  905. *
  906. * @type {string}
  907. * @default 'none'
  908. */
  909. this.updateType = NodeUpdateType.NONE;
  910. /**
  911. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  912. *
  913. * @type {string}
  914. * @default 'none'
  915. */
  916. this.updateBeforeType = NodeUpdateType.NONE;
  917. /**
  918. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  919. *
  920. * @type {string}
  921. * @default 'none'
  922. */
  923. this.updateAfterType = NodeUpdateType.NONE;
  924. /**
  925. * The UUID of the node.
  926. *
  927. * @type {string}
  928. * @readonly
  929. */
  930. this.uuid = MathUtils.generateUUID();
  931. /**
  932. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  933. *
  934. * @type {number}
  935. * @readonly
  936. * @default 0
  937. */
  938. this.version = 0;
  939. /**
  940. * The name of the node.
  941. *
  942. * @type {string}
  943. * @default ''
  944. */
  945. this.name = '';
  946. /**
  947. * Whether this node is global or not. This property is relevant for the internal
  948. * node caching system. All nodes which should be declared just once should
  949. * set this flag to `true` (a typical example is {@link AttributeNode}).
  950. *
  951. * @type {boolean}
  952. * @default false
  953. */
  954. this.global = false;
  955. /**
  956. * Create a list of parents for this node during the build process.
  957. *
  958. * @type {boolean}
  959. * @default false
  960. */
  961. this.parents = false;
  962. /**
  963. * This flag can be used for type testing.
  964. *
  965. * @type {boolean}
  966. * @readonly
  967. * @default true
  968. */
  969. this.isNode = true;
  970. // private
  971. this._beforeNodes = null;
  972. /**
  973. * The cache key of this node.
  974. *
  975. * @private
  976. * @type {?number}
  977. * @default null
  978. */
  979. this._cacheKey = null;
  980. /**
  981. * The cache key's version.
  982. *
  983. * @private
  984. * @type {number}
  985. * @default 0
  986. */
  987. this._cacheKeyVersion = 0;
  988. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  989. /**
  990. * The stack trace of the node for debugging purposes.
  991. *
  992. * @type {?string}
  993. * @default null
  994. */
  995. this.stackTrace = null;
  996. if ( Node.captureStackTrace === true ) {
  997. this.stackTrace = new StackTrace();
  998. }
  999. }
  1000. /**
  1001. * Set this property to `true` when the node should be regenerated.
  1002. *
  1003. * @type {boolean}
  1004. * @default false
  1005. * @param {boolean} value
  1006. */
  1007. set needsUpdate( value ) {
  1008. if ( value === true ) {
  1009. this.version ++;
  1010. }
  1011. }
  1012. /**
  1013. * The type of the class. The value is usually the constructor name.
  1014. *
  1015. * @type {string}
  1016. * @readonly
  1017. */
  1018. get type() {
  1019. return this.constructor.type;
  1020. }
  1021. /**
  1022. * Convenient method for defining {@link Node#update}.
  1023. *
  1024. * @param {Function} callback - The update method.
  1025. * @param {string} updateType - The update type.
  1026. * @return {Node} A reference to this node.
  1027. */
  1028. onUpdate( callback, updateType ) {
  1029. this.updateType = updateType;
  1030. this.update = callback.bind( this );
  1031. return this;
  1032. }
  1033. /**
  1034. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1035. * this method automatically sets the update type to `FRAME`.
  1036. *
  1037. * @param {Function} callback - The update method.
  1038. * @return {Node} A reference to this node.
  1039. */
  1040. onFrameUpdate( callback ) {
  1041. return this.onUpdate( callback, NodeUpdateType.FRAME );
  1042. }
  1043. /**
  1044. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1045. * this method automatically sets the update type to `RENDER`.
  1046. *
  1047. * @param {Function} callback - The update method.
  1048. * @return {Node} A reference to this node.
  1049. */
  1050. onRenderUpdate( callback ) {
  1051. return this.onUpdate( callback, NodeUpdateType.RENDER );
  1052. }
  1053. /**
  1054. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  1055. * this method automatically sets the update type to `OBJECT`.
  1056. *
  1057. * @param {Function} callback - The update method.
  1058. * @return {Node} A reference to this node.
  1059. */
  1060. onObjectUpdate( callback ) {
  1061. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  1062. }
  1063. /**
  1064. * Convenient method for defining {@link Node#updateReference}.
  1065. *
  1066. * @param {Function} callback - The update method.
  1067. * @return {Node} A reference to this node.
  1068. */
  1069. onReference( callback ) {
  1070. this.updateReference = callback.bind( this );
  1071. return this;
  1072. }
  1073. /**
  1074. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  1075. * to such objects based on a given state (e.g. the current node frame or builder).
  1076. *
  1077. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  1078. * @return {any} The updated reference.
  1079. */
  1080. updateReference( /*state*/ ) {
  1081. return this;
  1082. }
  1083. /**
  1084. * By default this method returns the value of the {@link Node#global} flag. This method
  1085. * can be overwritten in derived classes if an analytical way is required to determine the
  1086. * global cache referring to the current shader-stage.
  1087. *
  1088. * @param {NodeBuilder} builder - The current node builder.
  1089. * @return {boolean} Whether this node is global or not.
  1090. */
  1091. isGlobal( /*builder*/ ) {
  1092. return this.global;
  1093. }
  1094. /**
  1095. * Generator function that can be used to iterate over the child nodes.
  1096. *
  1097. * @generator
  1098. * @yields {Node} A child node.
  1099. */
  1100. * getChildren() {
  1101. for ( const { childNode } of this._getChildren() ) {
  1102. yield childNode;
  1103. }
  1104. }
  1105. /**
  1106. * Calling this method dispatches the `dispose` event. This event can be used
  1107. * to register event listeners for clean up tasks.
  1108. */
  1109. dispose() {
  1110. this.dispatchEvent( { type: 'dispose' } );
  1111. }
  1112. /**
  1113. * Callback for {@link Node#traverse}.
  1114. *
  1115. * @callback traverseCallback
  1116. * @param {Node} node - The current node.
  1117. */
  1118. /**
  1119. * Can be used to traverse through the node's hierarchy.
  1120. *
  1121. * @param {traverseCallback} callback - A callback that is executed per node.
  1122. */
  1123. traverse( callback ) {
  1124. callback( this );
  1125. for ( const childNode of this.getChildren() ) {
  1126. childNode.traverse( callback );
  1127. }
  1128. }
  1129. /**
  1130. * Returns the child nodes of this node.
  1131. *
  1132. * @private
  1133. * @param {Set<Node>} [ignores=new Set()] - A set of nodes to ignore during the search to avoid circular references.
  1134. * @returns {Array<Object>} An array of objects describing the child nodes.
  1135. */
  1136. _getChildren( ignores = new Set() ) {
  1137. const children = [];
  1138. // avoid circular references
  1139. ignores.add( this );
  1140. for ( const property of Object.getOwnPropertyNames( this ) ) {
  1141. const object = this[ property ];
  1142. // Ignore private properties and ignored nodes.
  1143. if ( property.startsWith( '_' ) === true || ignores.has( object ) ) continue;
  1144. if ( Array.isArray( object ) === true ) {
  1145. for ( let i = 0; i < object.length; i ++ ) {
  1146. const child = object[ i ];
  1147. if ( child && child.isNode === true ) {
  1148. children.push( { property, index: i, childNode: child } );
  1149. }
  1150. }
  1151. } else if ( object && object.isNode === true ) {
  1152. children.push( { property, childNode: object } );
  1153. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  1154. for ( const subProperty in object ) {
  1155. // Ignore private sub-properties.
  1156. if ( subProperty.startsWith( '_' ) === true ) continue;
  1157. const child = object[ subProperty ];
  1158. if ( child && child.isNode === true ) {
  1159. children.push( { property, index: subProperty, childNode: child } );
  1160. }
  1161. }
  1162. }
  1163. }
  1164. //
  1165. return children;
  1166. }
  1167. /**
  1168. * Returns the cache key for this node.
  1169. *
  1170. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1171. * @param {Set<Node>} [ignores=null] - A set of nodes to ignore during the computation of the cache key.
  1172. * @return {number} The cache key of the node.
  1173. */
  1174. getCacheKey( force = false, ignores = null ) {
  1175. force = force || this.version !== this._cacheKeyVersion;
  1176. if ( force === true || this._cacheKey === null ) {
  1177. if ( ignores === null ) ignores = new Set();
  1178. //
  1179. const values = [];
  1180. for ( const { property, childNode } of this._getChildren( ignores ) ) {
  1181. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey( force, ignores ) );
  1182. }
  1183. //
  1184. this._cacheKey = hash$1( hashArray( values ), this.customCacheKey() );
  1185. this._cacheKeyVersion = this.version;
  1186. }
  1187. return this._cacheKey;
  1188. }
  1189. /**
  1190. * Generate a custom cache key for this node.
  1191. *
  1192. * @return {number} The cache key of the node.
  1193. */
  1194. customCacheKey() {
  1195. return this.id;
  1196. }
  1197. /**
  1198. * Returns the references to this node which is by default `this`.
  1199. *
  1200. * @return {Node} A reference to this node.
  1201. */
  1202. getScope() {
  1203. return this;
  1204. }
  1205. /**
  1206. * Returns the hash of the node which is used to identify the node. By default it's
  1207. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1208. * depending on their implementation.
  1209. *
  1210. * @param {NodeBuilder} builder - The current node builder.
  1211. * @return {string} The hash.
  1212. */
  1213. getHash( /*builder*/ ) {
  1214. return this.uuid;
  1215. }
  1216. /**
  1217. * Returns the update type of {@link Node#update}.
  1218. *
  1219. * @return {NodeUpdateType} The update type.
  1220. */
  1221. getUpdateType() {
  1222. return this.updateType;
  1223. }
  1224. /**
  1225. * Returns the update type of {@link Node#updateBefore}.
  1226. *
  1227. * @return {NodeUpdateType} The update type.
  1228. */
  1229. getUpdateBeforeType() {
  1230. return this.updateBeforeType;
  1231. }
  1232. /**
  1233. * Returns the update type of {@link Node#updateAfter}.
  1234. *
  1235. * @return {NodeUpdateType} The update type.
  1236. */
  1237. getUpdateAfterType() {
  1238. return this.updateAfterType;
  1239. }
  1240. /**
  1241. * Certain types are composed of multiple elements. For example a `vec3`
  1242. * is composed of three `float` values. This method returns the type of
  1243. * these elements.
  1244. *
  1245. * @param {NodeBuilder} builder - The current node builder.
  1246. * @return {string} The type of the node.
  1247. */
  1248. getElementType( builder ) {
  1249. const type = this.getNodeType( builder );
  1250. const elementType = builder.getElementType( type );
  1251. return elementType;
  1252. }
  1253. /**
  1254. * Returns the node member type for the given name.
  1255. *
  1256. * @param {NodeBuilder} builder - The current node builder.
  1257. * @param {string} name - The name of the member.
  1258. * @return {string} The type of the node.
  1259. */
  1260. getMemberType( /*builder, name*/ ) {
  1261. return 'void';
  1262. }
  1263. /**
  1264. * Returns the node's type.
  1265. *
  1266. * @param {NodeBuilder} builder - The current node builder.
  1267. * @return {string} The type of the node.
  1268. */
  1269. getNodeType( builder ) {
  1270. const nodeProperties = builder.getNodeProperties( this );
  1271. if ( nodeProperties.outputNode ) {
  1272. return nodeProperties.outputNode.getNodeType( builder );
  1273. }
  1274. return this.nodeType;
  1275. }
  1276. /**
  1277. * This method is used during the build process of a node and ensures
  1278. * equal nodes are not built multiple times but just once. For example if
  1279. * `attribute( 'uv' )` is used multiple times by the user, the build
  1280. * process makes sure to process just the first node.
  1281. *
  1282. * @param {NodeBuilder} builder - The current node builder.
  1283. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1284. */
  1285. getShared( builder ) {
  1286. const hash = this.getHash( builder );
  1287. const nodeFromHash = builder.getNodeFromHash( hash );
  1288. return nodeFromHash || this;
  1289. }
  1290. /**
  1291. * Returns the number of elements in the node array.
  1292. *
  1293. * @param {NodeBuilder} builder - The current node builder.
  1294. * @return {?number} The number of elements in the node array.
  1295. */
  1296. getArrayCount( /*builder*/ ) {
  1297. return null;
  1298. }
  1299. /**
  1300. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1301. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1302. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1303. *
  1304. * @param {NodeBuilder} builder - The current node builder.
  1305. * @return {?Node} The output node.
  1306. */
  1307. setup( builder ) {
  1308. const nodeProperties = builder.getNodeProperties( this );
  1309. let index = 0;
  1310. for ( const childNode of this.getChildren() ) {
  1311. nodeProperties[ 'node' + index ++ ] = childNode;
  1312. }
  1313. // return a outputNode if exists or null
  1314. return nodeProperties.outputNode || null;
  1315. }
  1316. /**
  1317. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1318. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1319. *
  1320. * @param {NodeBuilder} builder - The current node builder.
  1321. * @param {?Node} output - The target output node.
  1322. */
  1323. analyze( builder, output = null ) {
  1324. const usageCount = builder.increaseUsage( this );
  1325. if ( this.parents === true ) {
  1326. const nodeData = builder.getDataFromNode( this, 'any' );
  1327. nodeData.stages = nodeData.stages || {};
  1328. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1329. nodeData.stages[ builder.shaderStage ].push( output );
  1330. }
  1331. if ( usageCount === 1 ) {
  1332. // node flow children
  1333. const nodeProperties = builder.getNodeProperties( this );
  1334. for ( const childNode of Object.values( nodeProperties ) ) {
  1335. if ( childNode && childNode.isNode === true ) {
  1336. childNode.build( builder, this );
  1337. }
  1338. }
  1339. }
  1340. }
  1341. /**
  1342. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1343. * This state builds the output node and returns the resulting shader string.
  1344. *
  1345. * @param {NodeBuilder} builder - The current node builder.
  1346. * @param {?string} [output] - Can be used to define the output type.
  1347. * @return {?string} The generated shader string.
  1348. */
  1349. generate( builder, output ) {
  1350. const { outputNode } = builder.getNodeProperties( this );
  1351. if ( outputNode && outputNode.isNode === true ) {
  1352. return outputNode.build( builder, output );
  1353. }
  1354. }
  1355. /**
  1356. * The method can be implemented to update the node's internal state before it is used to render an object.
  1357. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1358. *
  1359. * @abstract
  1360. * @param {NodeFrame} frame - A reference to the current node frame.
  1361. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1362. */
  1363. updateBefore( /*frame*/ ) {
  1364. warn( 'Abstract function.' );
  1365. }
  1366. /**
  1367. * The method can be implemented to update the node's internal state after it was used to render an object.
  1368. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1369. *
  1370. * @abstract
  1371. * @param {NodeFrame} frame - A reference to the current node frame.
  1372. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1373. */
  1374. updateAfter( /*frame*/ ) {
  1375. warn( 'Abstract function.' );
  1376. }
  1377. /**
  1378. * The method can be implemented to update the node's internal state when it is used to render an object.
  1379. * The {@link Node#updateType} property defines how often the update is executed.
  1380. *
  1381. * @abstract
  1382. * @param {NodeFrame} frame - A reference to the current node frame.
  1383. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1384. */
  1385. update( /*frame*/ ) {
  1386. warn( 'Abstract function.' );
  1387. }
  1388. before( node ) {
  1389. if ( this._beforeNodes === null ) this._beforeNodes = [];
  1390. this._beforeNodes.push( node );
  1391. return this;
  1392. }
  1393. /**
  1394. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1395. * - **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.
  1396. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1397. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1398. *
  1399. * @param {NodeBuilder} builder - The current node builder.
  1400. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1401. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1402. */
  1403. build( builder, output = null ) {
  1404. const refNode = this.getShared( builder );
  1405. if ( this !== refNode ) {
  1406. return refNode.build( builder, output );
  1407. }
  1408. //
  1409. if ( this._beforeNodes !== null ) {
  1410. const currentBeforeNodes = this._beforeNodes;
  1411. this._beforeNodes = null;
  1412. for ( const beforeNode of currentBeforeNodes ) {
  1413. beforeNode.build( builder, output );
  1414. }
  1415. this._beforeNodes = currentBeforeNodes;
  1416. }
  1417. //
  1418. const nodeData = builder.getDataFromNode( this );
  1419. nodeData.buildStages = nodeData.buildStages || {};
  1420. nodeData.buildStages[ builder.buildStage ] = true;
  1421. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1422. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1423. // force parent build stage (setup or analyze)
  1424. const previousBuildStage = builder.getBuildStage();
  1425. builder.setBuildStage( parentBuildStage );
  1426. this.build( builder );
  1427. builder.setBuildStage( previousBuildStage );
  1428. }
  1429. //
  1430. builder.addChain( this );
  1431. /* Build stages expected results:
  1432. - "setup" -> Node
  1433. - "analyze" -> null
  1434. - "generate" -> String
  1435. */
  1436. let result = null;
  1437. const buildStage = builder.getBuildStage();
  1438. if ( buildStage === 'setup' ) {
  1439. builder.addNode( this );
  1440. this.updateReference( builder );
  1441. const properties = builder.getNodeProperties( this );
  1442. if ( properties.initialized !== true ) {
  1443. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1444. properties.initialized = true;
  1445. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1446. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1447. // !! no outputNode !!
  1448. //outputNode = builder.stack;
  1449. }*/
  1450. for ( const childNode of Object.values( properties ) ) {
  1451. if ( childNode && childNode.isNode === true ) {
  1452. if ( childNode.parents === true ) {
  1453. const childProperties = builder.getNodeProperties( childNode );
  1454. childProperties.parents = childProperties.parents || [];
  1455. childProperties.parents.push( this );
  1456. }
  1457. childNode.build( builder );
  1458. }
  1459. }
  1460. builder.addSequentialNode( this );
  1461. }
  1462. result = properties.outputNode;
  1463. } else if ( buildStage === 'analyze' ) {
  1464. this.analyze( builder, output );
  1465. } else if ( buildStage === 'generate' ) {
  1466. // If generate has just one argument, it means the output type is not required.
  1467. // This means that the node does not handle output conversions internally,
  1468. // so the value is stored in a cache and the builder handles the conversion
  1469. // for all requested output types.
  1470. const isGenerateOnce = this.generate.length < 2;
  1471. if ( isGenerateOnce ) {
  1472. const type = this.getNodeType( builder );
  1473. const nodeData = builder.getDataFromNode( this );
  1474. result = nodeData.snippet;
  1475. if ( result === undefined ) {
  1476. if ( nodeData.generated === undefined ) {
  1477. nodeData.generated = true;
  1478. result = this.generate( builder ) || '';
  1479. nodeData.snippet = result;
  1480. } else {
  1481. warn( 'Node: Recursion detected.', this );
  1482. result = '/* Recursion detected. */';
  1483. }
  1484. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1485. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1486. }
  1487. result = builder.format( result, type, output );
  1488. } else {
  1489. result = this.generate( builder, output ) || '';
  1490. }
  1491. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1492. // if no snippet is generated, return a default value
  1493. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1494. result = builder.generateConst( output );
  1495. }
  1496. }
  1497. builder.removeChain( this );
  1498. return result;
  1499. }
  1500. /**
  1501. * Returns the child nodes as a JSON object.
  1502. *
  1503. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1504. */
  1505. getSerializeChildren() {
  1506. return this._getChildren();
  1507. }
  1508. /**
  1509. * Serializes the node to JSON.
  1510. *
  1511. * @param {Object} json - The output JSON object.
  1512. */
  1513. serialize( json ) {
  1514. const nodeChildren = this.getSerializeChildren();
  1515. const inputNodes = {};
  1516. for ( const { property, index, childNode } of nodeChildren ) {
  1517. if ( index !== undefined ) {
  1518. if ( inputNodes[ property ] === undefined ) {
  1519. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1520. }
  1521. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1522. } else {
  1523. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1524. }
  1525. }
  1526. if ( Object.keys( inputNodes ).length > 0 ) {
  1527. json.inputNodes = inputNodes;
  1528. }
  1529. }
  1530. /**
  1531. * Deserializes the node from the given JSON.
  1532. *
  1533. * @param {Object} json - The JSON object.
  1534. */
  1535. deserialize( json ) {
  1536. if ( json.inputNodes !== undefined ) {
  1537. const nodes = json.meta.nodes;
  1538. for ( const property in json.inputNodes ) {
  1539. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1540. const inputArray = [];
  1541. for ( const uuid of json.inputNodes[ property ] ) {
  1542. inputArray.push( nodes[ uuid ] );
  1543. }
  1544. this[ property ] = inputArray;
  1545. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1546. const inputObject = {};
  1547. for ( const subProperty in json.inputNodes[ property ] ) {
  1548. const uuid = json.inputNodes[ property ][ subProperty ];
  1549. inputObject[ subProperty ] = nodes[ uuid ];
  1550. }
  1551. this[ property ] = inputObject;
  1552. } else {
  1553. const uuid = json.inputNodes[ property ];
  1554. this[ property ] = nodes[ uuid ];
  1555. }
  1556. }
  1557. }
  1558. }
  1559. /**
  1560. * Serializes the node into the three.js JSON Object/Scene format.
  1561. *
  1562. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1563. * @return {Object} The serialized node.
  1564. */
  1565. toJSON( meta ) {
  1566. const { uuid, type } = this;
  1567. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1568. if ( isRoot ) {
  1569. meta = {
  1570. textures: {},
  1571. images: {},
  1572. nodes: {}
  1573. };
  1574. }
  1575. // serialize
  1576. let data = meta.nodes[ uuid ];
  1577. if ( data === undefined ) {
  1578. data = {
  1579. uuid,
  1580. type,
  1581. meta,
  1582. metadata: {
  1583. version: 4.7,
  1584. type: 'Node',
  1585. generator: 'Node.toJSON'
  1586. }
  1587. };
  1588. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1589. this.serialize( data );
  1590. delete data.meta;
  1591. }
  1592. // TODO: Copied from Object3D.toJSON
  1593. function extractFromCache( cache ) {
  1594. const values = [];
  1595. for ( const key in cache ) {
  1596. const data = cache[ key ];
  1597. delete data.metadata;
  1598. values.push( data );
  1599. }
  1600. return values;
  1601. }
  1602. if ( isRoot ) {
  1603. const textures = extractFromCache( meta.textures );
  1604. const images = extractFromCache( meta.images );
  1605. const nodes = extractFromCache( meta.nodes );
  1606. if ( textures.length > 0 ) data.textures = textures;
  1607. if ( images.length > 0 ) data.images = images;
  1608. if ( nodes.length > 0 ) data.nodes = nodes;
  1609. }
  1610. return data;
  1611. }
  1612. }
  1613. /**
  1614. * Enables or disables the automatic capturing of stack traces for nodes.
  1615. *
  1616. * @type {boolean}
  1617. * @default false
  1618. */
  1619. Node.captureStackTrace = false;
  1620. /**
  1621. * Base class for representing element access on an array-like
  1622. * node data structures.
  1623. *
  1624. * @augments Node
  1625. */
  1626. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1627. static get type() {
  1628. return 'ArrayElementNode';
  1629. }
  1630. /**
  1631. * Constructs an array element node.
  1632. *
  1633. * @param {Node} node - The array-like node.
  1634. * @param {Node} indexNode - The index node that defines the element access.
  1635. */
  1636. constructor( node, indexNode ) {
  1637. super();
  1638. /**
  1639. * The array-like node.
  1640. *
  1641. * @type {Node}
  1642. */
  1643. this.node = node;
  1644. /**
  1645. * The index node that defines the element access.
  1646. *
  1647. * @type {Node}
  1648. */
  1649. this.indexNode = indexNode;
  1650. /**
  1651. * This flag can be used for type testing.
  1652. *
  1653. * @type {boolean}
  1654. * @readonly
  1655. * @default true
  1656. */
  1657. this.isArrayElementNode = true;
  1658. }
  1659. /**
  1660. * This method is overwritten since the node type is inferred from the array-like node.
  1661. *
  1662. * @param {NodeBuilder} builder - The current node builder.
  1663. * @return {string} The node type.
  1664. */
  1665. getNodeType( builder ) {
  1666. return this.node.getElementType( builder );
  1667. }
  1668. /**
  1669. * This method is overwritten since the member type is inferred from the array-like node.
  1670. *
  1671. * @param {NodeBuilder} builder - The current node builder.
  1672. * @param {string} name - The member name.
  1673. * @return {string} The member type.
  1674. */
  1675. getMemberType( builder, name ) {
  1676. return this.node.getMemberType( builder, name );
  1677. }
  1678. generate( builder ) {
  1679. const indexType = this.indexNode.getNodeType( builder );
  1680. const nodeSnippet = this.node.build( builder );
  1681. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1682. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1683. }
  1684. }
  1685. /**
  1686. * This module is part of the TSL core and usually not used in app level code.
  1687. * It represents a convert operation during the shader generation process
  1688. * meaning it converts the data type of a node to a target data type.
  1689. *
  1690. * @augments Node
  1691. */
  1692. class ConvertNode extends Node {
  1693. static get type() {
  1694. return 'ConvertNode';
  1695. }
  1696. /**
  1697. * Constructs a new convert node.
  1698. *
  1699. * @param {Node} node - The node which type should be converted.
  1700. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1701. */
  1702. constructor( node, convertTo ) {
  1703. super();
  1704. /**
  1705. * The node which type should be converted.
  1706. *
  1707. * @type {Node}
  1708. */
  1709. this.node = node;
  1710. /**
  1711. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1712. *
  1713. * @type {string}
  1714. */
  1715. this.convertTo = convertTo;
  1716. }
  1717. /**
  1718. * This method is overwritten since the implementation tries to infer the best
  1719. * matching type from the {@link ConvertNode#convertTo} property.
  1720. *
  1721. * @param {NodeBuilder} builder - The current node builder.
  1722. * @return {string} The node type.
  1723. */
  1724. getNodeType( builder ) {
  1725. const requestType = this.node.getNodeType( builder );
  1726. let convertTo = null;
  1727. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1728. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1729. convertTo = overloadingType;
  1730. }
  1731. }
  1732. return convertTo;
  1733. }
  1734. serialize( data ) {
  1735. super.serialize( data );
  1736. data.convertTo = this.convertTo;
  1737. }
  1738. deserialize( data ) {
  1739. super.deserialize( data );
  1740. this.convertTo = data.convertTo;
  1741. }
  1742. generate( builder, output ) {
  1743. const node = this.node;
  1744. const type = this.getNodeType( builder );
  1745. const snippet = node.build( builder, type );
  1746. return builder.format( snippet, type, output );
  1747. }
  1748. }
  1749. /**
  1750. * This module uses cache management to create temporary variables
  1751. * if the node is used more than once to prevent duplicate calculations.
  1752. *
  1753. * The class acts as a base class for many other nodes types.
  1754. *
  1755. * @augments Node
  1756. */
  1757. class TempNode extends Node {
  1758. static get type() {
  1759. return 'TempNode';
  1760. }
  1761. /**
  1762. * Constructs a temp node.
  1763. *
  1764. * @param {?string} nodeType - The node type.
  1765. */
  1766. constructor( nodeType = null ) {
  1767. super( nodeType );
  1768. /**
  1769. * This flag can be used for type testing.
  1770. *
  1771. * @type {boolean}
  1772. * @readonly
  1773. * @default true
  1774. */
  1775. this.isTempNode = true;
  1776. }
  1777. /**
  1778. * Whether this node is used more than once in context of other nodes.
  1779. *
  1780. * @param {NodeBuilder} builder - The node builder.
  1781. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1782. */
  1783. hasDependencies( builder ) {
  1784. return builder.getDataFromNode( this ).usageCount > 1;
  1785. }
  1786. build( builder, output ) {
  1787. const buildStage = builder.getBuildStage();
  1788. if ( buildStage === 'generate' ) {
  1789. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1790. const nodeData = builder.getDataFromNode( this );
  1791. if ( nodeData.propertyName !== undefined ) {
  1792. return builder.format( nodeData.propertyName, type, output );
  1793. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1794. const snippet = super.build( builder, type );
  1795. const nodeVar = builder.getVarFromNode( this, null, type );
  1796. const propertyName = builder.getPropertyName( nodeVar );
  1797. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1798. nodeData.snippet = snippet;
  1799. nodeData.propertyName = propertyName;
  1800. return builder.format( nodeData.propertyName, type, output );
  1801. }
  1802. }
  1803. return super.build( builder, output );
  1804. }
  1805. }
  1806. /**
  1807. * This module is part of the TSL core and usually not used in app level code.
  1808. * It represents a join operation during the shader generation process.
  1809. * For example in can compose/join two single floats into a `vec2` type.
  1810. *
  1811. * @augments TempNode
  1812. */
  1813. class JoinNode extends TempNode {
  1814. static get type() {
  1815. return 'JoinNode';
  1816. }
  1817. /**
  1818. * Constructs a new join node.
  1819. *
  1820. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1821. * @param {?string} [nodeType=null] - The node type.
  1822. */
  1823. constructor( nodes = [], nodeType = null ) {
  1824. super( nodeType );
  1825. /**
  1826. * An array of nodes that should be joined.
  1827. *
  1828. * @type {Array<Node>}
  1829. */
  1830. this.nodes = nodes;
  1831. }
  1832. /**
  1833. * This method is overwritten since the node type must be inferred from the
  1834. * joined data length if not explicitly defined.
  1835. *
  1836. * @param {NodeBuilder} builder - The current node builder.
  1837. * @return {string} The node type.
  1838. */
  1839. getNodeType( builder ) {
  1840. if ( this.nodeType !== null ) {
  1841. return builder.getVectorType( this.nodeType );
  1842. }
  1843. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1844. }
  1845. generate( builder, output ) {
  1846. const type = this.getNodeType( builder );
  1847. const maxLength = builder.getTypeLength( type );
  1848. const nodes = this.nodes;
  1849. const primitiveType = builder.getComponentType( type );
  1850. const snippetValues = [];
  1851. let length = 0;
  1852. for ( const input of nodes ) {
  1853. if ( length >= maxLength ) {
  1854. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.`, this.stackTrace );
  1855. break;
  1856. }
  1857. let inputType = input.getNodeType( builder );
  1858. let inputTypeLength = builder.getTypeLength( inputType );
  1859. let inputSnippet;
  1860. if ( length + inputTypeLength > maxLength ) {
  1861. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.`, this.stackTrace );
  1862. inputTypeLength = maxLength - length;
  1863. inputType = builder.getTypeFromLength( inputTypeLength );
  1864. }
  1865. length += inputTypeLength;
  1866. inputSnippet = input.build( builder, inputType );
  1867. const inputPrimitiveType = builder.getComponentType( inputType );
  1868. if ( inputPrimitiveType !== primitiveType ) {
  1869. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1870. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1871. }
  1872. snippetValues.push( inputSnippet );
  1873. }
  1874. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1875. return builder.format( snippet, type, output );
  1876. }
  1877. }
  1878. const _stringVectorComponents = vectorComponents.join( '' );
  1879. /**
  1880. * This module is part of the TSL core and usually not used in app level code.
  1881. * `SplitNode` represents a property access operation which means it is
  1882. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1883. * For example:
  1884. * ```js
  1885. * const redValue = color.r;
  1886. * ```
  1887. *
  1888. * @augments Node
  1889. */
  1890. class SplitNode extends Node {
  1891. static get type() {
  1892. return 'SplitNode';
  1893. }
  1894. /**
  1895. * Constructs a new split node.
  1896. *
  1897. * @param {Node} node - The node that should be accessed.
  1898. * @param {string} [components='x'] - The components that should be accessed.
  1899. */
  1900. constructor( node, components = 'x' ) {
  1901. super();
  1902. /**
  1903. * The node that should be accessed.
  1904. *
  1905. * @type {Node}
  1906. */
  1907. this.node = node;
  1908. /**
  1909. * The components that should be accessed.
  1910. *
  1911. * @type {string}
  1912. */
  1913. this.components = components;
  1914. /**
  1915. * This flag can be used for type testing.
  1916. *
  1917. * @type {boolean}
  1918. * @readonly
  1919. * @default true
  1920. */
  1921. this.isSplitNode = true;
  1922. }
  1923. /**
  1924. * Returns the vector length which is computed based on the requested components.
  1925. *
  1926. * @return {number} The vector length.
  1927. */
  1928. getVectorLength() {
  1929. let vectorLength = this.components.length;
  1930. for ( const c of this.components ) {
  1931. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1932. }
  1933. return vectorLength;
  1934. }
  1935. /**
  1936. * Returns the component type of the node's type.
  1937. *
  1938. * @param {NodeBuilder} builder - The current node builder.
  1939. * @return {string} The component type.
  1940. */
  1941. getComponentType( builder ) {
  1942. return builder.getComponentType( this.node.getNodeType( builder ) );
  1943. }
  1944. /**
  1945. * This method is overwritten since the node type is inferred from requested components.
  1946. *
  1947. * @param {NodeBuilder} builder - The current node builder.
  1948. * @return {string} The node type.
  1949. */
  1950. getNodeType( builder ) {
  1951. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1952. }
  1953. /**
  1954. * Returns the scope of the node.
  1955. *
  1956. * @return {Node} The scope of the node.
  1957. */
  1958. getScope() {
  1959. return this.node.getScope();
  1960. }
  1961. generate( builder, output ) {
  1962. const node = this.node;
  1963. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1964. let snippet = null;
  1965. if ( nodeTypeLength > 1 ) {
  1966. let type = null;
  1967. const componentsLength = this.getVectorLength();
  1968. if ( componentsLength >= nodeTypeLength ) {
  1969. // needed expand the input node
  1970. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1971. }
  1972. const nodeSnippet = node.build( builder, type );
  1973. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1974. // unnecessary swizzle
  1975. snippet = builder.format( nodeSnippet, type, output );
  1976. } else {
  1977. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1978. }
  1979. } else {
  1980. // ignore .components if .node returns float/integer
  1981. snippet = node.build( builder, output );
  1982. }
  1983. return snippet;
  1984. }
  1985. serialize( data ) {
  1986. super.serialize( data );
  1987. data.components = this.components;
  1988. }
  1989. deserialize( data ) {
  1990. super.deserialize( data );
  1991. this.components = data.components;
  1992. }
  1993. }
  1994. /**
  1995. * This module is part of the TSL core and usually not used in app level code.
  1996. * `SetNode` represents a set operation which means it is used to implement any
  1997. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1998. * For example:
  1999. * ```js
  2000. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  2001. * ```
  2002. *
  2003. * @augments TempNode
  2004. */
  2005. class SetNode extends TempNode {
  2006. static get type() {
  2007. return 'SetNode';
  2008. }
  2009. /**
  2010. * Constructs a new set node.
  2011. *
  2012. * @param {Node} sourceNode - The node that should be updated.
  2013. * @param {string} components - The components that should be updated.
  2014. * @param {Node} targetNode - The value node.
  2015. */
  2016. constructor( sourceNode, components, targetNode ) {
  2017. super();
  2018. /**
  2019. * The node that should be updated.
  2020. *
  2021. * @type {Node}
  2022. */
  2023. this.sourceNode = sourceNode;
  2024. /**
  2025. * The components that should be updated.
  2026. *
  2027. * @type {string}
  2028. */
  2029. this.components = components;
  2030. /**
  2031. * The value node.
  2032. *
  2033. * @type {Node}
  2034. */
  2035. this.targetNode = targetNode;
  2036. }
  2037. /**
  2038. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  2039. *
  2040. * @param {NodeBuilder} builder - The current node builder.
  2041. * @return {string} The node type.
  2042. */
  2043. getNodeType( builder ) {
  2044. return this.sourceNode.getNodeType( builder );
  2045. }
  2046. generate( builder ) {
  2047. const { sourceNode, components, targetNode } = this;
  2048. const sourceType = this.getNodeType( builder );
  2049. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  2050. const targetType = builder.getTypeFromLength( components.length, componentType );
  2051. const targetSnippet = targetNode.build( builder, targetType );
  2052. const sourceSnippet = sourceNode.build( builder, sourceType );
  2053. const length = builder.getTypeLength( sourceType );
  2054. const snippetValues = [];
  2055. for ( let i = 0; i < length; i ++ ) {
  2056. const component = vectorComponents[ i ];
  2057. if ( component === components[ 0 ] ) {
  2058. snippetValues.push( targetSnippet );
  2059. i += components.length - 1;
  2060. } else {
  2061. snippetValues.push( sourceSnippet + '.' + component );
  2062. }
  2063. }
  2064. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2065. }
  2066. }
  2067. /**
  2068. * This module is part of the TSL core and usually not used in app level code.
  2069. * It represents a flip operation during the shader generation process
  2070. * meaning it flips normalized values with the following formula:
  2071. * ```
  2072. * x = 1 - x;
  2073. * ```
  2074. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  2075. * `flipSTPQ()` method invocations on node objects. For example:
  2076. * ```js
  2077. * uvNode = uvNode.flipY();
  2078. * ```
  2079. *
  2080. * @augments TempNode
  2081. */
  2082. class FlipNode extends TempNode {
  2083. static get type() {
  2084. return 'FlipNode';
  2085. }
  2086. /**
  2087. * Constructs a new flip node.
  2088. *
  2089. * @param {Node} sourceNode - The node which component(s) should be flipped.
  2090. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  2091. */
  2092. constructor( sourceNode, components ) {
  2093. super();
  2094. /**
  2095. * The node which component(s) should be flipped.
  2096. *
  2097. * @type {Node}
  2098. */
  2099. this.sourceNode = sourceNode;
  2100. /**
  2101. * The components that should be flipped e.g. `'x'` or `'xy'`.
  2102. *
  2103. * @type {string}
  2104. */
  2105. this.components = components;
  2106. }
  2107. /**
  2108. * This method is overwritten since the node type is inferred from the source node.
  2109. *
  2110. * @param {NodeBuilder} builder - The current node builder.
  2111. * @return {string} The node type.
  2112. */
  2113. getNodeType( builder ) {
  2114. return this.sourceNode.getNodeType( builder );
  2115. }
  2116. generate( builder ) {
  2117. const { components, sourceNode } = this;
  2118. const sourceType = this.getNodeType( builder );
  2119. const sourceSnippet = sourceNode.build( builder );
  2120. const sourceCache = builder.getVarFromNode( this );
  2121. const sourceProperty = builder.getPropertyName( sourceCache );
  2122. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  2123. const length = builder.getTypeLength( sourceType );
  2124. const snippetValues = [];
  2125. let componentIndex = 0;
  2126. for ( let i = 0; i < length; i ++ ) {
  2127. const component = vectorComponents[ i ];
  2128. if ( component === components[ componentIndex ] ) {
  2129. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  2130. componentIndex ++;
  2131. } else {
  2132. snippetValues.push( sourceProperty + '.' + component );
  2133. }
  2134. }
  2135. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2136. }
  2137. }
  2138. /**
  2139. * Base class for representing data input nodes.
  2140. *
  2141. * @augments Node
  2142. */
  2143. class InputNode extends Node {
  2144. static get type() {
  2145. return 'InputNode';
  2146. }
  2147. /**
  2148. * Constructs a new input node.
  2149. *
  2150. * @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).
  2151. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2152. */
  2153. constructor( value, nodeType = null ) {
  2154. super( nodeType );
  2155. /**
  2156. * This flag can be used for type testing.
  2157. *
  2158. * @type {boolean}
  2159. * @readonly
  2160. * @default true
  2161. */
  2162. this.isInputNode = true;
  2163. /**
  2164. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2165. *
  2166. * @type {any}
  2167. */
  2168. this.value = value;
  2169. /**
  2170. * The precision of the value in the shader.
  2171. *
  2172. * @type {?('low'|'medium'|'high')}
  2173. * @default null
  2174. */
  2175. this.precision = null;
  2176. }
  2177. getNodeType( /*builder*/ ) {
  2178. if ( this.nodeType === null ) {
  2179. return getValueType( this.value );
  2180. }
  2181. return this.nodeType;
  2182. }
  2183. /**
  2184. * Returns the input type of the node which is by default the node type. Derived modules
  2185. * might overwrite this method and use a fixed type or compute one analytically.
  2186. *
  2187. * A typical example for different input and node types are textures. The input type of a
  2188. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2189. *
  2190. * @param {NodeBuilder} builder - The current node builder.
  2191. * @return {string} The input type.
  2192. */
  2193. getInputType( builder ) {
  2194. return this.getNodeType( builder );
  2195. }
  2196. /**
  2197. * Sets the precision to the given value. The method can be
  2198. * overwritten in derived classes if the final precision must be computed
  2199. * analytically.
  2200. *
  2201. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2202. * @return {InputNode} A reference to this node.
  2203. */
  2204. setPrecision( precision ) {
  2205. this.precision = precision;
  2206. return this;
  2207. }
  2208. serialize( data ) {
  2209. super.serialize( data );
  2210. data.value = this.value;
  2211. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2212. data.valueType = getValueType( this.value );
  2213. data.nodeType = this.nodeType;
  2214. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2215. data.precision = this.precision;
  2216. }
  2217. deserialize( data ) {
  2218. super.deserialize( data );
  2219. this.nodeType = data.nodeType;
  2220. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2221. this.precision = data.precision || null;
  2222. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2223. }
  2224. generate( /*builder, output*/ ) {
  2225. warn( 'Abstract function.' );
  2226. }
  2227. }
  2228. const _regNum = /float|u?int/;
  2229. /**
  2230. * Class for representing a constant value in the shader.
  2231. *
  2232. * @augments InputNode
  2233. */
  2234. class ConstNode extends InputNode {
  2235. static get type() {
  2236. return 'ConstNode';
  2237. }
  2238. /**
  2239. * Constructs a new input node.
  2240. *
  2241. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2242. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2243. */
  2244. constructor( value, nodeType = null ) {
  2245. super( value, nodeType );
  2246. /**
  2247. * This flag can be used for type testing.
  2248. *
  2249. * @type {boolean}
  2250. * @readonly
  2251. * @default true
  2252. */
  2253. this.isConstNode = true;
  2254. }
  2255. /**
  2256. * Generates the shader string of the value with the current node builder.
  2257. *
  2258. * @param {NodeBuilder} builder - The current node builder.
  2259. * @return {string} The generated value as a shader string.
  2260. */
  2261. generateConst( builder ) {
  2262. return builder.generateConst( this.getNodeType( builder ), this.value );
  2263. }
  2264. generate( builder, output ) {
  2265. const type = this.getNodeType( builder );
  2266. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2267. return builder.generateConst( output, this.value );
  2268. }
  2269. return builder.format( this.generateConst( builder ), type, output );
  2270. }
  2271. }
  2272. /**
  2273. * Base class for representing member access on an object-like
  2274. * node data structures.
  2275. *
  2276. * @augments Node
  2277. */
  2278. class MemberNode extends Node {
  2279. static get type() {
  2280. return 'MemberNode';
  2281. }
  2282. /**
  2283. * Constructs a member node.
  2284. *
  2285. * @param {Node} structNode - The struct node.
  2286. * @param {string} property - The property name.
  2287. */
  2288. constructor( structNode, property ) {
  2289. super();
  2290. /**
  2291. * The struct node.
  2292. *
  2293. * @type {Node}
  2294. */
  2295. this.structNode = structNode;
  2296. /**
  2297. * The property name.
  2298. *
  2299. * @type {Node}
  2300. */
  2301. this.property = property;
  2302. /**
  2303. * This flag can be used for type testing.
  2304. *
  2305. * @type {boolean}
  2306. * @readonly
  2307. * @default true
  2308. */
  2309. this.isMemberNode = true;
  2310. }
  2311. hasMember( builder ) {
  2312. if ( this.structNode.isMemberNode ) {
  2313. if ( this.structNode.hasMember( builder ) === false ) {
  2314. return false;
  2315. }
  2316. }
  2317. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2318. }
  2319. getNodeType( builder ) {
  2320. if ( this.hasMember( builder ) === false ) {
  2321. // default type if member does not exist
  2322. return 'float';
  2323. }
  2324. return this.structNode.getMemberType( builder, this.property );
  2325. }
  2326. getMemberType( builder, name ) {
  2327. if ( this.hasMember( builder ) === false ) {
  2328. // default type if member does not exist
  2329. return 'float';
  2330. }
  2331. const type = this.getNodeType( builder );
  2332. const struct = builder.getStructTypeNode( type );
  2333. return struct.getMemberType( builder, name );
  2334. }
  2335. generate( builder ) {
  2336. if ( this.hasMember( builder ) === false ) {
  2337. warn( `TSL: Member "${ this.property }" does not exist in struct.`, this.stackTrace );
  2338. const type = this.getNodeType( builder );
  2339. return builder.generateConst( type );
  2340. }
  2341. const propertyName = this.structNode.build( builder );
  2342. return propertyName + '.' + this.property;
  2343. }
  2344. }
  2345. let currentStack = null;
  2346. const NodeElements = new Map();
  2347. // Extend Node Class for TSL using prototype
  2348. function addMethodChaining( name, nodeElement ) {
  2349. // No require StackTrace because this is internal API
  2350. if ( NodeElements.has( name ) ) {
  2351. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2352. return;
  2353. }
  2354. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2355. NodeElements.set( name, nodeElement );
  2356. if ( name !== 'assign' ) {
  2357. // Changing Node prototype to add method chaining
  2358. Node.prototype[ name ] = function ( ...params ) {
  2359. //if ( name === 'toVarIntent' ) return this;
  2360. return this.isStackNode ? this.addToStack( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2361. };
  2362. // Adding assign method chaining
  2363. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2364. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2365. };
  2366. }
  2367. }
  2368. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2369. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2370. Node.prototype.assign = function ( ...params ) {
  2371. if ( this.isStackNode !== true ) {
  2372. if ( currentStack !== null ) {
  2373. currentStack.assign( this, ...params );
  2374. } else {
  2375. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().', new StackTrace() );
  2376. }
  2377. return this;
  2378. } else {
  2379. const nodeElement = NodeElements.get( 'assign' );
  2380. return this.addToStack( nodeElement( ...params ) );
  2381. }
  2382. };
  2383. Node.prototype.toVarIntent = function () {
  2384. return this;
  2385. };
  2386. Node.prototype.get = function ( value ) {
  2387. return new MemberNode( this, value );
  2388. };
  2389. // Cache prototype for TSL
  2390. const proto = {};
  2391. // Set swizzle properties for xyzw, rgba, and stpq.
  2392. function setProtoSwizzle( property, altA, altB ) {
  2393. // swizzle properties
  2394. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2395. get() {
  2396. this._cache = this._cache || {};
  2397. //
  2398. let split = this._cache[ property ];
  2399. if ( split === undefined ) {
  2400. split = new SplitNode( this, property );
  2401. this._cache[ property ] = split;
  2402. }
  2403. return split;
  2404. },
  2405. set( value ) {
  2406. this[ property ].assign( nodeObject( value ) );
  2407. }
  2408. };
  2409. // set properties ( swizzle ) and sort to xyzw sequence
  2410. const propUpper = property.toUpperCase();
  2411. const altAUpper = altA.toUpperCase();
  2412. const altBUpper = altB.toUpperCase();
  2413. // Set methods for swizzle properties
  2414. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2415. const swizzle = parseSwizzleAndSort( property );
  2416. return new SetNode( this, swizzle, nodeObject( value ) );
  2417. };
  2418. // Set methods for flip properties
  2419. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2420. const swizzle = parseSwizzleAndSort( property );
  2421. return new FlipNode( this, swizzle );
  2422. };
  2423. }
  2424. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2425. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2426. const swizzleC = [ 's', 't', 'p', 'q' ];
  2427. for ( let a = 0; a < 4; a ++ ) {
  2428. let prop = swizzleA[ a ];
  2429. let altA = swizzleB[ a ];
  2430. let altB = swizzleC[ a ];
  2431. setProtoSwizzle( prop, altA, altB );
  2432. for ( let b = 0; b < 4; b ++ ) {
  2433. prop = swizzleA[ a ] + swizzleA[ b ];
  2434. altA = swizzleB[ a ] + swizzleB[ b ];
  2435. altB = swizzleC[ a ] + swizzleC[ b ];
  2436. setProtoSwizzle( prop, altA, altB );
  2437. for ( let c = 0; c < 4; c ++ ) {
  2438. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2439. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2440. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2441. setProtoSwizzle( prop, altA, altB );
  2442. for ( let d = 0; d < 4; d ++ ) {
  2443. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2444. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2445. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2446. setProtoSwizzle( prop, altA, altB );
  2447. }
  2448. }
  2449. }
  2450. }
  2451. // Set/get static properties for array elements (0-31).
  2452. for ( let i = 0; i < 32; i ++ ) {
  2453. proto[ i ] = {
  2454. get() {
  2455. this._cache = this._cache || {};
  2456. //
  2457. let element = this._cache[ i ];
  2458. if ( element === undefined ) {
  2459. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2460. this._cache[ i ] = element;
  2461. }
  2462. return element;
  2463. },
  2464. set( value ) {
  2465. this[ i ].assign( nodeObject( value ) );
  2466. }
  2467. };
  2468. }
  2469. /*
  2470. // Set properties for width, height, and depth.
  2471. function setProtoProperty( property, target ) {
  2472. proto[ property ] = {
  2473. get() {
  2474. this._cache = this._cache || {};
  2475. //
  2476. let split = this._cache[ target ];
  2477. if ( split === undefined ) {
  2478. split = new SplitNode( this, target );
  2479. this._cache[ target ] = split;
  2480. }
  2481. return split;
  2482. },
  2483. set( value ) {
  2484. this[ target ].assign( nodeObject( value ) );
  2485. }
  2486. };
  2487. }
  2488. setProtoProperty( 'width', 'x' );
  2489. setProtoProperty( 'height', 'y' );
  2490. setProtoProperty( 'depth', 'z' );
  2491. */
  2492. Object.defineProperties( Node.prototype, proto );
  2493. // --- FINISH ---
  2494. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2495. const ShaderNodeObject = function ( obj, altType = null ) {
  2496. const type = getValueType( obj );
  2497. if ( type === 'node' ) {
  2498. return obj;
  2499. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2500. return nodeObject( getConstNode( obj, altType ) );
  2501. } else if ( type === 'shader' ) {
  2502. return obj.isFn ? obj : Fn( obj );
  2503. }
  2504. return obj;
  2505. };
  2506. const ShaderNodeObjects = function ( objects, altType = null ) {
  2507. for ( const name in objects ) {
  2508. objects[ name ] = nodeObject( objects[ name ], altType );
  2509. }
  2510. return objects;
  2511. };
  2512. const ShaderNodeArray = function ( array, altType = null ) {
  2513. const len = array.length;
  2514. for ( let i = 0; i < len; i ++ ) {
  2515. array[ i ] = nodeObject( array[ i ], altType );
  2516. }
  2517. return array;
  2518. };
  2519. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2520. function assignNode( node ) {
  2521. if ( settings !== null ) {
  2522. node = nodeObject( Object.assign( node, settings ) );
  2523. if ( settings.intent === true ) {
  2524. node = node.toVarIntent();
  2525. }
  2526. } else {
  2527. node = nodeObject( node );
  2528. }
  2529. return node;
  2530. }
  2531. let fn, name = scope, minParams, maxParams;
  2532. function verifyParamsLimit( params ) {
  2533. let tslName;
  2534. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2535. else tslName = NodeClass.type;
  2536. if ( minParams !== undefined && params.length < minParams ) {
  2537. error( `TSL: "${ tslName }" parameter length is less than minimum required.`, new StackTrace() );
  2538. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2539. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2540. error( `TSL: "${ tslName }" parameter length exceeds limit.`, new StackTrace() );
  2541. return params.slice( 0, maxParams );
  2542. }
  2543. return params;
  2544. }
  2545. if ( scope === null ) {
  2546. fn = ( ...params ) => {
  2547. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2548. };
  2549. } else if ( factor !== null ) {
  2550. factor = nodeObject( factor );
  2551. fn = ( ...params ) => {
  2552. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2553. };
  2554. } else {
  2555. fn = ( ...params ) => {
  2556. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2557. };
  2558. }
  2559. fn.setParameterLength = ( ...params ) => {
  2560. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2561. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2562. return fn;
  2563. };
  2564. fn.setName = ( value ) => {
  2565. name = value;
  2566. return fn;
  2567. };
  2568. return fn;
  2569. };
  2570. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2571. return new NodeClass( ...nodeArray( params ) );
  2572. };
  2573. class ShaderCallNodeInternal extends Node {
  2574. constructor( shaderNode, rawInputs ) {
  2575. super();
  2576. this.shaderNode = shaderNode;
  2577. this.rawInputs = rawInputs;
  2578. this.isShaderCallNodeInternal = true;
  2579. }
  2580. getNodeType( builder ) {
  2581. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2582. }
  2583. getElementType( builder ) {
  2584. return this.getOutputNode( builder ).getElementType( builder );
  2585. }
  2586. getMemberType( builder, name ) {
  2587. return this.getOutputNode( builder ).getMemberType( builder, name );
  2588. }
  2589. call( builder ) {
  2590. const { shaderNode, rawInputs } = this;
  2591. const properties = builder.getNodeProperties( shaderNode );
  2592. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2593. const subBuildProperty = subBuild || 'default';
  2594. if ( properties[ subBuildProperty ] ) {
  2595. return properties[ subBuildProperty ];
  2596. }
  2597. //
  2598. const previousSubBuildFn = builder.subBuildFn;
  2599. const previousFnCall = builder.fnCall;
  2600. builder.subBuildFn = subBuild;
  2601. builder.fnCall = this;
  2602. let result = null;
  2603. if ( shaderNode.layout ) {
  2604. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2605. if ( functionNodesCacheMap === undefined ) {
  2606. functionNodesCacheMap = new WeakMap();
  2607. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2608. }
  2609. let functionNode = functionNodesCacheMap.get( shaderNode );
  2610. if ( functionNode === undefined ) {
  2611. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2612. functionNodesCacheMap.set( shaderNode, functionNode );
  2613. }
  2614. builder.addInclude( functionNode );
  2615. //
  2616. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2617. result = nodeObject( functionNode.call( inputs ) );
  2618. } else {
  2619. const secureNodeBuilder = new Proxy( builder, {
  2620. get: ( target, property, receiver ) => {
  2621. let value;
  2622. if ( Symbol.iterator === property ) {
  2623. value = function* () {
  2624. yield undefined;
  2625. };
  2626. } else {
  2627. value = Reflect.get( target, property, receiver );
  2628. }
  2629. return value;
  2630. }
  2631. } );
  2632. //
  2633. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2634. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2635. const jsFunc = shaderNode.jsFunc;
  2636. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2637. result = nodeObject( outputNode );
  2638. }
  2639. builder.subBuildFn = previousSubBuildFn;
  2640. builder.fnCall = previousFnCall;
  2641. if ( shaderNode.once ) {
  2642. properties[ subBuildProperty ] = result;
  2643. }
  2644. return result;
  2645. }
  2646. setupOutput( builder ) {
  2647. builder.addStack();
  2648. builder.stack.outputNode = this.call( builder );
  2649. return builder.removeStack();
  2650. }
  2651. getOutputNode( builder ) {
  2652. const properties = builder.getNodeProperties( this );
  2653. const subBuildOutput = builder.getSubBuildOutput( this );
  2654. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2655. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2656. return properties[ subBuildOutput ];
  2657. }
  2658. build( builder, output = null ) {
  2659. let result = null;
  2660. const buildStage = builder.getBuildStage();
  2661. const properties = builder.getNodeProperties( this );
  2662. const subBuildOutput = builder.getSubBuildOutput( this );
  2663. const outputNode = this.getOutputNode( builder );
  2664. const previousFnCall = builder.fnCall;
  2665. builder.fnCall = this;
  2666. if ( buildStage === 'setup' ) {
  2667. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2668. if ( properties[ subBuildInitialized ] !== true ) {
  2669. properties[ subBuildInitialized ] = true;
  2670. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2671. properties[ subBuildOutput ].build( builder );
  2672. // If the shaderNode has subBuilds, add them to the chaining nodes
  2673. // so they can be built later in the build process.
  2674. if ( this.shaderNode.subBuilds ) {
  2675. for ( const node of builder.chaining ) {
  2676. const nodeData = builder.getDataFromNode( node, 'any' );
  2677. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2678. for ( const subBuild of this.shaderNode.subBuilds ) {
  2679. nodeData.subBuilds.add( subBuild );
  2680. }
  2681. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2682. }
  2683. }
  2684. }
  2685. result = properties[ subBuildOutput ];
  2686. } else if ( buildStage === 'analyze' ) {
  2687. outputNode.build( builder, output );
  2688. } else if ( buildStage === 'generate' ) {
  2689. result = outputNode.build( builder, output ) || '';
  2690. }
  2691. builder.fnCall = previousFnCall;
  2692. return result;
  2693. }
  2694. }
  2695. function getLayoutParameters( params ) {
  2696. let output;
  2697. nodeObjects( params );
  2698. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2699. if ( isArrayAsParameter ) {
  2700. output = [ ...params ];
  2701. } else {
  2702. output = params[ 0 ];
  2703. }
  2704. return output;
  2705. }
  2706. function getProxyParameters( params ) {
  2707. let index = 0;
  2708. nodeObjects( params );
  2709. return new Proxy( params, {
  2710. get: ( target, property, receiver ) => {
  2711. let value;
  2712. if ( property === 'length' ) {
  2713. value = params.length;
  2714. return value;
  2715. }
  2716. if ( Symbol.iterator === property ) {
  2717. value = function* () {
  2718. for ( const inputNode of params ) {
  2719. yield nodeObject( inputNode );
  2720. }
  2721. };
  2722. } else {
  2723. if ( params.length > 0 ) {
  2724. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2725. const objectTarget = params[ 0 ];
  2726. if ( objectTarget[ property ] === undefined ) {
  2727. value = objectTarget[ index ++ ];
  2728. } else {
  2729. value = Reflect.get( objectTarget, property, receiver );
  2730. }
  2731. } else if ( params[ 0 ] instanceof Node ) {
  2732. if ( params[ property ] === undefined ) {
  2733. value = params[ index ++ ];
  2734. } else {
  2735. value = Reflect.get( params, property, receiver );
  2736. }
  2737. }
  2738. } else {
  2739. value = Reflect.get( target, property, receiver );
  2740. }
  2741. value = nodeObject( value );
  2742. }
  2743. return value;
  2744. }
  2745. } );
  2746. }
  2747. class ShaderNodeInternal extends Node {
  2748. constructor( jsFunc, nodeType ) {
  2749. super( nodeType );
  2750. this.jsFunc = jsFunc;
  2751. this.layout = null;
  2752. this.global = true;
  2753. this.once = false;
  2754. }
  2755. setLayout( layout ) {
  2756. this.layout = layout;
  2757. return this;
  2758. }
  2759. getLayout() {
  2760. return this.layout;
  2761. }
  2762. call( rawInputs = null ) {
  2763. return new ShaderCallNodeInternal( this, rawInputs );
  2764. }
  2765. setup() {
  2766. return this.call();
  2767. }
  2768. }
  2769. const bools = [ false, true ];
  2770. const uints = [ 0, 1, 2, 3 ];
  2771. const ints = [ -1, -2 ];
  2772. 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 ];
  2773. const boolsCacheMap = new Map();
  2774. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2775. const uintsCacheMap = new Map();
  2776. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2777. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2778. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2779. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2780. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2781. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2782. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2783. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2784. const getConstNode = ( value, type ) => {
  2785. if ( constNodesCacheMap.has( value ) ) {
  2786. return constNodesCacheMap.get( value );
  2787. } else if ( value.isNode === true ) {
  2788. return value;
  2789. } else {
  2790. return new ConstNode( value, type );
  2791. }
  2792. };
  2793. const ConvertType = function ( type, cacheMap = null ) {
  2794. return ( ...params ) => {
  2795. for ( const param of params ) {
  2796. if ( param === undefined ) {
  2797. error( `TSL: Invalid parameter for the type "${ type }".`, new StackTrace() );
  2798. return new ConstNode( 0, type );
  2799. }
  2800. }
  2801. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2802. const paramType = typeof param;
  2803. return paramType !== 'object' && paramType !== 'function';
  2804. } ) ) ) {
  2805. params = [ getValueFromType( type, ...params ) ];
  2806. }
  2807. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2808. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2809. }
  2810. if ( params.length === 1 ) {
  2811. const node = getConstNode( params[ 0 ], type );
  2812. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2813. return nodeObjectIntent( new ConvertNode( node, type ) );
  2814. }
  2815. const nodes = params.map( param => getConstNode( param ) );
  2816. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2817. };
  2818. };
  2819. // exports
  2820. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2821. // utils
  2822. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2823. // shader node base
  2824. function ShaderNode( jsFunc, nodeType ) {
  2825. return new ShaderNodeInternal( jsFunc, nodeType );
  2826. }
  2827. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2828. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2829. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2830. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2831. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2832. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2833. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { ...settings, intent: true } );
  2834. let fnId = 0;
  2835. class FnNode extends Node {
  2836. constructor( jsFunc, layout = null ) {
  2837. super();
  2838. let nodeType = null;
  2839. if ( layout !== null ) {
  2840. if ( typeof layout === 'object' ) {
  2841. nodeType = layout.return;
  2842. } else {
  2843. if ( typeof layout === 'string' ) {
  2844. nodeType = layout;
  2845. } else {
  2846. error( 'TSL: Invalid layout type.', new StackTrace() );
  2847. }
  2848. layout = null;
  2849. }
  2850. }
  2851. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2852. if ( layout !== null ) {
  2853. this.setLayout( layout );
  2854. }
  2855. this.isFn = true;
  2856. }
  2857. setLayout( layout ) {
  2858. const nodeType = this.shaderNode.nodeType;
  2859. if ( typeof layout.inputs !== 'object' ) {
  2860. const fullLayout = {
  2861. name: 'fn' + fnId ++,
  2862. type: nodeType,
  2863. inputs: []
  2864. };
  2865. for ( const name in layout ) {
  2866. if ( name === 'return' ) continue;
  2867. fullLayout.inputs.push( {
  2868. name: name,
  2869. type: layout[ name ]
  2870. } );
  2871. }
  2872. layout = fullLayout;
  2873. }
  2874. this.shaderNode.setLayout( layout );
  2875. return this;
  2876. }
  2877. getNodeType( builder ) {
  2878. return this.shaderNode.getNodeType( builder ) || 'float';
  2879. }
  2880. call( ...params ) {
  2881. const fnCall = this.shaderNode.call( params );
  2882. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2883. return fnCall.toVarIntent();
  2884. }
  2885. once( subBuilds = null ) {
  2886. this.shaderNode.once = true;
  2887. this.shaderNode.subBuilds = subBuilds;
  2888. return this;
  2889. }
  2890. generate( builder ) {
  2891. const type = this.getNodeType( builder );
  2892. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".', this.stackTrace );
  2893. return builder.generateConst( type );
  2894. }
  2895. }
  2896. function Fn( jsFunc, layout = null ) {
  2897. const instance = new FnNode( jsFunc, layout );
  2898. return new Proxy( () => {}, {
  2899. apply( target, thisArg, params ) {
  2900. return instance.call( ...params );
  2901. },
  2902. get( target, prop, receiver ) {
  2903. return Reflect.get( instance, prop, receiver );
  2904. },
  2905. set( target, prop, value, receiver ) {
  2906. return Reflect.set( instance, prop, value, receiver );
  2907. }
  2908. } );
  2909. }
  2910. //
  2911. const setCurrentStack = ( stack ) => {
  2912. currentStack = stack;
  2913. };
  2914. const getCurrentStack = () => currentStack;
  2915. /**
  2916. * Represent a conditional node using if/else statements.
  2917. *
  2918. * ```js
  2919. * If( condition, function )
  2920. * .ElseIf( condition, function )
  2921. * .Else( function )
  2922. * ```
  2923. * @tsl
  2924. * @function
  2925. * @param {...any} params - The parameters for the conditional node.
  2926. * @returns {StackNode} The conditional node.
  2927. */
  2928. const If = ( ...params ) => currentStack.If( ...params );
  2929. /**
  2930. * Represent a conditional node using switch/case statements.
  2931. *
  2932. * ```js
  2933. * Switch( value )
  2934. * .Case( 1, function )
  2935. * .Case( 2, 3, 4, function )
  2936. * .Default( function )
  2937. * ```
  2938. * @tsl
  2939. * @function
  2940. * @param {...any} params - The parameters for the conditional node.
  2941. * @returns {StackNode} The conditional node.
  2942. */
  2943. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2944. /**
  2945. * Add the given node to the current stack.
  2946. *
  2947. * @param {Node} node - The node to add.
  2948. * @returns {Node} The node that was added to the stack.
  2949. */
  2950. function Stack( node ) {
  2951. if ( currentStack ) currentStack.addToStack( node );
  2952. return node;
  2953. }
  2954. addMethodChaining( 'toStack', Stack );
  2955. // types
  2956. const color = new ConvertType( 'color' );
  2957. const float = new ConvertType( 'float', cacheMaps.float );
  2958. const int = new ConvertType( 'int', cacheMaps.ints );
  2959. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2960. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2961. const vec2 = new ConvertType( 'vec2' );
  2962. const ivec2 = new ConvertType( 'ivec2' );
  2963. const uvec2 = new ConvertType( 'uvec2' );
  2964. const bvec2 = new ConvertType( 'bvec2' );
  2965. const vec3 = new ConvertType( 'vec3' );
  2966. const ivec3 = new ConvertType( 'ivec3' );
  2967. const uvec3 = new ConvertType( 'uvec3' );
  2968. const bvec3 = new ConvertType( 'bvec3' );
  2969. const vec4 = new ConvertType( 'vec4' );
  2970. const ivec4 = new ConvertType( 'ivec4' );
  2971. const uvec4 = new ConvertType( 'uvec4' );
  2972. const bvec4 = new ConvertType( 'bvec4' );
  2973. const mat2 = new ConvertType( 'mat2' );
  2974. const mat3 = new ConvertType( 'mat3' );
  2975. const mat4 = new ConvertType( 'mat4' );
  2976. const string = ( value = '' ) => new ConstNode( value, 'string' );
  2977. const arrayBuffer = ( value ) => new ConstNode( value, 'ArrayBuffer' );
  2978. addMethodChaining( 'toColor', color );
  2979. addMethodChaining( 'toFloat', float );
  2980. addMethodChaining( 'toInt', int );
  2981. addMethodChaining( 'toUint', uint );
  2982. addMethodChaining( 'toBool', bool );
  2983. addMethodChaining( 'toVec2', vec2 );
  2984. addMethodChaining( 'toIVec2', ivec2 );
  2985. addMethodChaining( 'toUVec2', uvec2 );
  2986. addMethodChaining( 'toBVec2', bvec2 );
  2987. addMethodChaining( 'toVec3', vec3 );
  2988. addMethodChaining( 'toIVec3', ivec3 );
  2989. addMethodChaining( 'toUVec3', uvec3 );
  2990. addMethodChaining( 'toBVec3', bvec3 );
  2991. addMethodChaining( 'toVec4', vec4 );
  2992. addMethodChaining( 'toIVec4', ivec4 );
  2993. addMethodChaining( 'toUVec4', uvec4 );
  2994. addMethodChaining( 'toBVec4', bvec4 );
  2995. addMethodChaining( 'toMat2', mat2 );
  2996. addMethodChaining( 'toMat3', mat3 );
  2997. addMethodChaining( 'toMat4', mat4 );
  2998. // basic nodes
  2999. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  3000. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  3001. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  3002. addMethodChaining( 'element', element );
  3003. addMethodChaining( 'convert', convert );
  3004. // deprecated
  3005. /**
  3006. * @tsl
  3007. * @function
  3008. * @deprecated since r176. Use {@link Stack} instead.
  3009. *
  3010. * @param {Node} node - The node to add.
  3011. * @returns {Function}
  3012. */
  3013. const append = ( node ) => { // @deprecated, r176
  3014. warn( 'TSL: append() has been renamed to Stack().', new StackTrace() );
  3015. return Stack( node );
  3016. };
  3017. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  3018. warn( 'TSL: .append() has been renamed to .toStack().', new StackTrace() );
  3019. return Stack( node );
  3020. } );
  3021. /**
  3022. * This class represents a shader property. It can be used
  3023. * to explicitly define a property and assign a value to it.
  3024. *
  3025. * ```js
  3026. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  3027. *```
  3028. * `PropertyNode` is used by the engine to predefined common material properties
  3029. * for TSL code.
  3030. *
  3031. * @augments Node
  3032. */
  3033. class PropertyNode extends Node {
  3034. static get type() {
  3035. return 'PropertyNode';
  3036. }
  3037. /**
  3038. * Constructs a new property node.
  3039. *
  3040. * @param {string} nodeType - The type of the node.
  3041. * @param {?string} [name=null] - The name of the property in the shader.
  3042. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  3043. */
  3044. constructor( nodeType, name = null, varying = false ) {
  3045. super( nodeType );
  3046. /**
  3047. * The name of the property in the shader. If no name is defined,
  3048. * the node system auto-generates one.
  3049. *
  3050. * @type {?string}
  3051. * @default null
  3052. */
  3053. this.name = name;
  3054. /**
  3055. * Whether this property is a varying or not.
  3056. *
  3057. * @type {boolean}
  3058. * @default false
  3059. */
  3060. this.varying = varying;
  3061. /**
  3062. * This flag can be used for type testing.
  3063. *
  3064. * @type {boolean}
  3065. * @readonly
  3066. * @default true
  3067. */
  3068. this.isPropertyNode = true;
  3069. /**
  3070. * This flag is used for global cache.
  3071. *
  3072. * @type {boolean}
  3073. * @default true
  3074. */
  3075. this.global = true;
  3076. }
  3077. customCacheKey() {
  3078. return hashString( this.type + ':' + ( this.name || '' ) + ':' + ( this.varying ? '1' : '0' ) );
  3079. }
  3080. getHash( builder ) {
  3081. return this.name || super.getHash( builder );
  3082. }
  3083. generate( builder ) {
  3084. let nodeVar;
  3085. if ( this.varying === true ) {
  3086. nodeVar = builder.getVaryingFromNode( this, this.name );
  3087. nodeVar.needsInterpolation = true;
  3088. } else {
  3089. nodeVar = builder.getVarFromNode( this, this.name );
  3090. }
  3091. return builder.getPropertyName( nodeVar );
  3092. }
  3093. }
  3094. /**
  3095. * TSL function for creating a property node.
  3096. *
  3097. * @tsl
  3098. * @function
  3099. * @param {string} type - The type of the node.
  3100. * @param {?string} [name=null] - The name of the property in the shader.
  3101. * @returns {PropertyNode}
  3102. */
  3103. const property = ( type, name ) => new PropertyNode( type, name );
  3104. /**
  3105. * TSL function for creating a varying property node.
  3106. *
  3107. * @tsl
  3108. * @function
  3109. * @param {string} type - The type of the node.
  3110. * @param {?string} [name=null] - The name of the varying in the shader.
  3111. * @returns {PropertyNode}
  3112. */
  3113. const varyingProperty = ( type, name ) => new PropertyNode( type, name, true );
  3114. /**
  3115. * TSL object that represents the shader variable `DiffuseColor`.
  3116. *
  3117. * @tsl
  3118. * @type {PropertyNode<vec4>}
  3119. */
  3120. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  3121. /**
  3122. * TSL object that represents the shader variable `DiffuseContribution`.
  3123. *
  3124. * @tsl
  3125. * @type {PropertyNode<vec3>}
  3126. */
  3127. const diffuseContribution = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'DiffuseContribution' );
  3128. /**
  3129. * TSL object that represents the shader variable `EmissiveColor`.
  3130. *
  3131. * @tsl
  3132. * @type {PropertyNode<vec3>}
  3133. */
  3134. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  3135. /**
  3136. * TSL object that represents the shader variable `Roughness`.
  3137. *
  3138. * @tsl
  3139. * @type {PropertyNode<float>}
  3140. */
  3141. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  3142. /**
  3143. * TSL object that represents the shader variable `Metalness`.
  3144. *
  3145. * @tsl
  3146. * @type {PropertyNode<float>}
  3147. */
  3148. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3149. /**
  3150. * TSL object that represents the shader variable `Clearcoat`.
  3151. *
  3152. * @tsl
  3153. * @type {PropertyNode<float>}
  3154. */
  3155. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3156. /**
  3157. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3158. *
  3159. * @tsl
  3160. * @type {PropertyNode<float>}
  3161. */
  3162. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3163. /**
  3164. * TSL object that represents the shader variable `Sheen`.
  3165. *
  3166. * @tsl
  3167. * @type {PropertyNode<vec3>}
  3168. */
  3169. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3170. /**
  3171. * TSL object that represents the shader variable `SheenRoughness`.
  3172. *
  3173. * @tsl
  3174. * @type {PropertyNode<float>}
  3175. */
  3176. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3177. /**
  3178. * TSL object that represents the shader variable `Iridescence`.
  3179. *
  3180. * @tsl
  3181. * @type {PropertyNode<float>}
  3182. */
  3183. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3184. /**
  3185. * TSL object that represents the shader variable `IridescenceIOR`.
  3186. *
  3187. * @tsl
  3188. * @type {PropertyNode<float>}
  3189. */
  3190. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3191. /**
  3192. * TSL object that represents the shader variable `IridescenceThickness`.
  3193. *
  3194. * @tsl
  3195. * @type {PropertyNode<float>}
  3196. */
  3197. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3198. /**
  3199. * TSL object that represents the shader variable `AlphaT`.
  3200. *
  3201. * @tsl
  3202. * @type {PropertyNode<float>}
  3203. */
  3204. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3205. /**
  3206. * TSL object that represents the shader variable `Anisotropy`.
  3207. *
  3208. * @tsl
  3209. * @type {PropertyNode<float>}
  3210. */
  3211. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3212. /**
  3213. * TSL object that represents the shader variable `AnisotropyT`.
  3214. *
  3215. * @tsl
  3216. * @type {PropertyNode<vec3>}
  3217. */
  3218. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3219. /**
  3220. * TSL object that represents the shader variable `AnisotropyB`.
  3221. *
  3222. * @tsl
  3223. * @type {PropertyNode<vec3>}
  3224. */
  3225. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3226. /**
  3227. * TSL object that represents the shader variable `SpecularColor`.
  3228. *
  3229. * @tsl
  3230. * @type {PropertyNode<color>}
  3231. */
  3232. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3233. /**
  3234. * TSL object that represents the shader variable `SpecularColorBlended`.
  3235. *
  3236. * @tsl
  3237. * @type {PropertyNode<color>}
  3238. */
  3239. const specularColorBlended = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColorBlended' );
  3240. /**
  3241. * TSL object that represents the shader variable `SpecularF90`.
  3242. *
  3243. * @tsl
  3244. * @type {PropertyNode<float>}
  3245. */
  3246. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3247. /**
  3248. * TSL object that represents the shader variable `Shininess`.
  3249. *
  3250. * @tsl
  3251. * @type {PropertyNode<float>}
  3252. */
  3253. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3254. /**
  3255. * TSL object that represents the shader variable `Output`.
  3256. *
  3257. * @tsl
  3258. * @type {PropertyNode<vec4>}
  3259. */
  3260. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3261. /**
  3262. * TSL object that represents the shader variable `dashSize`.
  3263. *
  3264. * @tsl
  3265. * @type {PropertyNode<float>}
  3266. */
  3267. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3268. /**
  3269. * TSL object that represents the shader variable `gapSize`.
  3270. *
  3271. * @tsl
  3272. * @type {PropertyNode<float>}
  3273. */
  3274. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3275. /**
  3276. * TSL object that represents the shader variable `pointWidth`.
  3277. *
  3278. * @tsl
  3279. * @type {PropertyNode<float>}
  3280. */
  3281. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3282. /**
  3283. * TSL object that represents the shader variable `IOR`.
  3284. *
  3285. * @tsl
  3286. * @type {PropertyNode<float>}
  3287. */
  3288. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3289. /**
  3290. * TSL object that represents the shader variable `Transmission`.
  3291. *
  3292. * @tsl
  3293. * @type {PropertyNode<float>}
  3294. */
  3295. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3296. /**
  3297. * TSL object that represents the shader variable `Thickness`.
  3298. *
  3299. * @tsl
  3300. * @type {PropertyNode<float>}
  3301. */
  3302. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3303. /**
  3304. * TSL object that represents the shader variable `AttenuationDistance`.
  3305. *
  3306. * @tsl
  3307. * @type {PropertyNode<float>}
  3308. */
  3309. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3310. /**
  3311. * TSL object that represents the shader variable `AttenuationColor`.
  3312. *
  3313. * @tsl
  3314. * @type {PropertyNode<color>}
  3315. */
  3316. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3317. /**
  3318. * TSL object that represents the shader variable `Dispersion`.
  3319. *
  3320. * @tsl
  3321. * @type {PropertyNode<float>}
  3322. */
  3323. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3324. /**
  3325. * This node can be used to group single instances of {@link UniformNode}
  3326. * and manage them as a uniform buffer.
  3327. *
  3328. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3329. * will be used when defining the {@link UniformNode#groupNode} property.
  3330. *
  3331. * - `objectGroup`: Uniform buffer per object.
  3332. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3333. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3334. *
  3335. * @augments Node
  3336. */
  3337. class UniformGroupNode extends Node {
  3338. static get type() {
  3339. return 'UniformGroupNode';
  3340. }
  3341. /**
  3342. * Constructs a new uniform group node.
  3343. *
  3344. * @param {string} name - The name of the uniform group node.
  3345. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3346. * @param {number} [order=1] - Influences the internal sorting.
  3347. */
  3348. constructor( name, shared = false, order = 1 ) {
  3349. super( 'string' );
  3350. /**
  3351. * The name of the uniform group node.
  3352. *
  3353. * @type {string}
  3354. */
  3355. this.name = name;
  3356. /**
  3357. * Whether this uniform group node is shared or not.
  3358. *
  3359. * @type {boolean}
  3360. * @default false
  3361. */
  3362. this.shared = shared;
  3363. /**
  3364. * Influences the internal sorting.
  3365. * TODO: Add details when this property should be changed.
  3366. *
  3367. * @type {number}
  3368. * @default 1
  3369. */
  3370. this.order = order;
  3371. /**
  3372. * This flag can be used for type testing.
  3373. *
  3374. * @type {boolean}
  3375. * @readonly
  3376. * @default true
  3377. */
  3378. this.isUniformGroup = true;
  3379. }
  3380. serialize( data ) {
  3381. super.serialize( data );
  3382. data.name = this.name;
  3383. data.version = this.version;
  3384. data.shared = this.shared;
  3385. }
  3386. deserialize( data ) {
  3387. super.deserialize( data );
  3388. this.name = data.name;
  3389. this.version = data.version;
  3390. this.shared = data.shared;
  3391. }
  3392. }
  3393. /**
  3394. * TSL function for creating a uniform group node with the given name.
  3395. *
  3396. * @tsl
  3397. * @function
  3398. * @param {string} name - The name of the uniform group node.
  3399. * @returns {UniformGroupNode}
  3400. */
  3401. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3402. /**
  3403. * TSL function for creating a shared uniform group node with the given name and order.
  3404. *
  3405. * @tsl
  3406. * @function
  3407. * @param {string} name - The name of the uniform group node.
  3408. * @param {number} [order=0] - Influences the internal sorting.
  3409. * @returns {UniformGroupNode}
  3410. */
  3411. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3412. /**
  3413. * TSL object that represents a shared uniform group node which is updated once per frame.
  3414. *
  3415. * @tsl
  3416. * @type {UniformGroupNode}
  3417. */
  3418. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3419. /**
  3420. * TSL object that represents a shared uniform group node which is updated once per render.
  3421. *
  3422. * @tsl
  3423. * @type {UniformGroupNode}
  3424. */
  3425. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3426. /**
  3427. * TSL object that represents a uniform group node which is updated once per object.
  3428. *
  3429. * @tsl
  3430. * @type {UniformGroupNode}
  3431. */
  3432. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3433. /**
  3434. * Class for representing a uniform.
  3435. *
  3436. * @augments InputNode
  3437. */
  3438. class UniformNode extends InputNode {
  3439. static get type() {
  3440. return 'UniformNode';
  3441. }
  3442. /**
  3443. * Constructs a new uniform node.
  3444. *
  3445. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3446. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3447. */
  3448. constructor( value, nodeType = null ) {
  3449. super( value, nodeType );
  3450. /**
  3451. * This flag can be used for type testing.
  3452. *
  3453. * @type {boolean}
  3454. * @readonly
  3455. * @default true
  3456. */
  3457. this.isUniformNode = true;
  3458. /**
  3459. * The name or label of the uniform.
  3460. *
  3461. * @type {string}
  3462. * @default ''
  3463. */
  3464. this.name = '';
  3465. /**
  3466. * The uniform group of this uniform. By default, uniforms are
  3467. * managed per object but they might belong to a shared group
  3468. * which is updated per frame or render call.
  3469. *
  3470. * @type {UniformGroupNode}
  3471. */
  3472. this.groupNode = objectGroup;
  3473. }
  3474. /**
  3475. * Sets the {@link UniformNode#name} property.
  3476. *
  3477. * @param {string} name - The name of the uniform.
  3478. * @return {UniformNode} A reference to this node.
  3479. */
  3480. setName( name ) {
  3481. this.name = name;
  3482. return this;
  3483. }
  3484. /**
  3485. * Sets the {@link UniformNode#name} property.
  3486. *
  3487. * @deprecated
  3488. * @param {string} name - The name of the uniform.
  3489. * @return {UniformNode} A reference to this node.
  3490. */
  3491. label( name ) {
  3492. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  3493. return this.setName( name );
  3494. }
  3495. /**
  3496. * Sets the {@link UniformNode#groupNode} property.
  3497. *
  3498. * @param {UniformGroupNode} group - The uniform group.
  3499. * @return {UniformNode} A reference to this node.
  3500. */
  3501. setGroup( group ) {
  3502. this.groupNode = group;
  3503. return this;
  3504. }
  3505. /**
  3506. * Returns the {@link UniformNode#groupNode}.
  3507. *
  3508. * @return {UniformGroupNode} The uniform group.
  3509. */
  3510. getGroup() {
  3511. return this.groupNode;
  3512. }
  3513. /**
  3514. * By default, this method returns the result of {@link Node#getHash} but derived
  3515. * classes might overwrite this method with a different implementation.
  3516. *
  3517. * @param {NodeBuilder} builder - The current node builder.
  3518. * @return {string} The uniform hash.
  3519. */
  3520. getUniformHash( builder ) {
  3521. return this.getHash( builder );
  3522. }
  3523. onUpdate( callback, updateType ) {
  3524. callback = callback.bind( this );
  3525. return super.onUpdate( ( frame ) => {
  3526. const value = callback( frame, this );
  3527. if ( value !== undefined ) {
  3528. this.value = value;
  3529. }
  3530. }, updateType );
  3531. }
  3532. getInputType( builder ) {
  3533. let type = super.getInputType( builder );
  3534. if ( type === 'bool' ) {
  3535. type = 'uint';
  3536. }
  3537. return type;
  3538. }
  3539. generate( builder, output ) {
  3540. const type = this.getNodeType( builder );
  3541. const hash = this.getUniformHash( builder );
  3542. let sharedNode = builder.getNodeFromHash( hash );
  3543. if ( sharedNode === undefined ) {
  3544. builder.setHashNode( this, hash );
  3545. sharedNode = this;
  3546. }
  3547. const sharedNodeType = sharedNode.getInputType( builder );
  3548. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3549. const uniformName = builder.getPropertyName( nodeUniform );
  3550. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3551. //
  3552. let snippet = uniformName;
  3553. if ( type === 'bool' ) {
  3554. // cache to variable
  3555. const nodeData = builder.getDataFromNode( this );
  3556. let propertyName = nodeData.propertyName;
  3557. if ( propertyName === undefined ) {
  3558. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3559. propertyName = builder.getPropertyName( nodeVar );
  3560. nodeData.propertyName = propertyName;
  3561. snippet = builder.format( uniformName, sharedNodeType, type );
  3562. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3563. }
  3564. snippet = propertyName;
  3565. }
  3566. return builder.format( snippet, type, output );
  3567. }
  3568. }
  3569. /**
  3570. * TSL function for creating a uniform node.
  3571. *
  3572. * @tsl
  3573. * @function
  3574. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3575. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3576. * @returns {UniformNode}
  3577. */
  3578. const uniform = ( value, type ) => {
  3579. const nodeType = getConstNodeType( type || value );
  3580. if ( nodeType === value ) {
  3581. // if the value is a type but no having a value
  3582. value = getValueFromType( nodeType );
  3583. }
  3584. if ( value && value.isNode === true ) {
  3585. let v = value.value;
  3586. value.traverse( n => {
  3587. if ( n.isConstNode === true ) {
  3588. v = n.value;
  3589. }
  3590. } );
  3591. value = v;
  3592. }
  3593. return new UniformNode( value, nodeType );
  3594. };
  3595. /**
  3596. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3597. * ```js
  3598. * const colors = array( [
  3599. * vec3( 1, 0, 0 ),
  3600. * vec3( 0, 1, 0 ),
  3601. * vec3( 0, 0, 1 )
  3602. * ] );
  3603. *
  3604. * const redColor = tintColors.element( 0 );
  3605. * ```
  3606. *
  3607. * @augments TempNode
  3608. */
  3609. class ArrayNode extends TempNode {
  3610. static get type() {
  3611. return 'ArrayNode';
  3612. }
  3613. /**
  3614. * Constructs a new array node.
  3615. *
  3616. * @param {?string} nodeType - The data type of the elements.
  3617. * @param {number} count - Size of the array.
  3618. * @param {?Array<Node>} [values=null] - Array default values.
  3619. */
  3620. constructor( nodeType, count, values = null ) {
  3621. super( nodeType );
  3622. /**
  3623. * Array size.
  3624. *
  3625. * @type {number}
  3626. */
  3627. this.count = count;
  3628. /**
  3629. * Array default values.
  3630. *
  3631. * @type {?Array<Node>}
  3632. */
  3633. this.values = values;
  3634. /**
  3635. * This flag can be used for type testing.
  3636. *
  3637. * @type {boolean}
  3638. * @readonly
  3639. * @default true
  3640. */
  3641. this.isArrayNode = true;
  3642. }
  3643. /**
  3644. * Returns the number of elements in the node array.
  3645. *
  3646. * @param {NodeBuilder} builder - The current node builder.
  3647. * @return {number} The number of elements in the node array.
  3648. */
  3649. getArrayCount( /*builder*/ ) {
  3650. return this.count;
  3651. }
  3652. /**
  3653. * Returns the node's type.
  3654. *
  3655. * @param {NodeBuilder} builder - The current node builder.
  3656. * @return {string} The type of the node.
  3657. */
  3658. getNodeType( builder ) {
  3659. if ( this.nodeType === null ) {
  3660. return this.values[ 0 ].getNodeType( builder );
  3661. }
  3662. return this.nodeType;
  3663. }
  3664. /**
  3665. * Returns the node's type.
  3666. *
  3667. * @param {NodeBuilder} builder - The current node builder.
  3668. * @return {string} The type of the node.
  3669. */
  3670. getElementType( builder ) {
  3671. return this.getNodeType( builder );
  3672. }
  3673. /**
  3674. * Returns the type of a member variable.
  3675. *
  3676. * @param {NodeBuilder} builder - The current node builder.
  3677. * @param {string} name - The name of the member variable.
  3678. * @return {string} The type of the member variable.
  3679. */
  3680. getMemberType( builder, name ) {
  3681. if ( this.nodeType === null ) {
  3682. return this.values[ 0 ].getMemberType( builder, name );
  3683. }
  3684. return super.getMemberType( builder, name );
  3685. }
  3686. /**
  3687. * This method builds the output node and returns the resulting array as a shader string.
  3688. *
  3689. * @param {NodeBuilder} builder - The current node builder.
  3690. * @return {string} The generated shader string.
  3691. */
  3692. generate( builder ) {
  3693. const type = this.getNodeType( builder );
  3694. return builder.generateArray( type, this.count, this.values );
  3695. }
  3696. }
  3697. /**
  3698. * TSL function for creating an array node.
  3699. *
  3700. * @tsl
  3701. * @function
  3702. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3703. * or an array containing the default values (e.g., [ vec3() ]).
  3704. * @param {?number} [count] - Size of the array.
  3705. * @returns {ArrayNode}
  3706. */
  3707. const array = ( ...params ) => {
  3708. let node;
  3709. if ( params.length === 1 ) {
  3710. const values = params[ 0 ];
  3711. node = new ArrayNode( null, values.length, values );
  3712. } else {
  3713. const nodeType = params[ 0 ];
  3714. const count = params[ 1 ];
  3715. node = new ArrayNode( nodeType, count );
  3716. }
  3717. return nodeObject( node );
  3718. };
  3719. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3720. /**
  3721. * These node represents an assign operation. Meaning a node is assigned
  3722. * to another node.
  3723. *
  3724. * @augments TempNode
  3725. */
  3726. class AssignNode extends TempNode {
  3727. static get type() {
  3728. return 'AssignNode';
  3729. }
  3730. /**
  3731. * Constructs a new assign node.
  3732. *
  3733. * @param {Node} targetNode - The target node.
  3734. * @param {Node} sourceNode - The source type.
  3735. */
  3736. constructor( targetNode, sourceNode ) {
  3737. super();
  3738. /**
  3739. * The target node.
  3740. *
  3741. * @type {Node}
  3742. */
  3743. this.targetNode = targetNode;
  3744. /**
  3745. * The source node.
  3746. *
  3747. * @type {Node}
  3748. */
  3749. this.sourceNode = sourceNode;
  3750. /**
  3751. * This flag can be used for type testing.
  3752. *
  3753. * @type {boolean}
  3754. * @readonly
  3755. * @default true
  3756. */
  3757. this.isAssignNode = true;
  3758. }
  3759. /**
  3760. * Whether this node is used more than once in context of other nodes. This method
  3761. * is overwritten since it always returns `false` (assigns are unique).
  3762. *
  3763. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3764. */
  3765. hasDependencies() {
  3766. return false;
  3767. }
  3768. getNodeType( builder, output ) {
  3769. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3770. }
  3771. /**
  3772. * Whether a split is required when assigning source to target. This can happen when the component length of
  3773. * target and source data type does not match.
  3774. *
  3775. * @param {NodeBuilder} builder - The current node builder.
  3776. * @return {boolean} Whether a split is required when assigning source to target.
  3777. */
  3778. needsSplitAssign( builder ) {
  3779. const { targetNode } = this;
  3780. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3781. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3782. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3783. return assignDifferentVector;
  3784. }
  3785. return false;
  3786. }
  3787. setup( builder ) {
  3788. const { targetNode, sourceNode } = this;
  3789. const scope = targetNode.getScope();
  3790. const scopeData = builder.getDataFromNode( scope );
  3791. scopeData.assign = true;
  3792. const properties = builder.getNodeProperties( this );
  3793. properties.sourceNode = sourceNode;
  3794. properties.targetNode = targetNode.context( { assign: true } );
  3795. }
  3796. generate( builder, output ) {
  3797. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3798. const needsSplitAssign = this.needsSplitAssign( builder );
  3799. const target = targetNode.build( builder );
  3800. const targetType = targetNode.getNodeType( builder );
  3801. const source = sourceNode.build( builder, targetType );
  3802. const sourceType = sourceNode.getNodeType( builder );
  3803. const nodeData = builder.getDataFromNode( this );
  3804. //
  3805. let snippet;
  3806. if ( nodeData.initialized === true ) {
  3807. if ( output !== 'void' ) {
  3808. snippet = target;
  3809. }
  3810. } else if ( needsSplitAssign ) {
  3811. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3812. const sourceProperty = builder.getPropertyName( sourceVar );
  3813. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3814. const splitNode = targetNode.node;
  3815. const splitTargetNode = splitNode.node.context( { assign: true } );
  3816. const targetRoot = splitTargetNode.build( builder );
  3817. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3818. const component = splitNode.components[ i ];
  3819. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3820. }
  3821. if ( output !== 'void' ) {
  3822. snippet = target;
  3823. }
  3824. } else {
  3825. snippet = `${ target } = ${ source }`;
  3826. if ( output === 'void' || sourceType === 'void' ) {
  3827. builder.addLineFlowCode( snippet, this );
  3828. if ( output !== 'void' ) {
  3829. snippet = target;
  3830. }
  3831. }
  3832. }
  3833. nodeData.initialized = true;
  3834. return builder.format( snippet, targetType, output );
  3835. }
  3836. }
  3837. /**
  3838. * TSL function for creating an assign node.
  3839. *
  3840. * @tsl
  3841. * @function
  3842. * @param {Node} targetNode - The target node.
  3843. * @param {Node} sourceNode - The source type.
  3844. * @returns {AssignNode}
  3845. */
  3846. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3847. addMethodChaining( 'assign', assign );
  3848. /**
  3849. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3850. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3851. * this logic.
  3852. *
  3853. * @augments TempNode
  3854. */
  3855. class FunctionCallNode extends TempNode {
  3856. static get type() {
  3857. return 'FunctionCallNode';
  3858. }
  3859. /**
  3860. * Constructs a new function call node.
  3861. *
  3862. * @param {?FunctionNode} functionNode - The function node.
  3863. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3864. */
  3865. constructor( functionNode = null, parameters = {} ) {
  3866. super();
  3867. /**
  3868. * The function node.
  3869. *
  3870. * @type {?FunctionNode}
  3871. * @default null
  3872. */
  3873. this.functionNode = functionNode;
  3874. /**
  3875. * The parameters of the function call.
  3876. *
  3877. * @type {Object<string, Node>}
  3878. * @default {}
  3879. */
  3880. this.parameters = parameters;
  3881. }
  3882. /**
  3883. * Sets the parameters of the function call node.
  3884. *
  3885. * @param {Object<string, Node>} parameters - The parameters to set.
  3886. * @return {FunctionCallNode} A reference to this node.
  3887. */
  3888. setParameters( parameters ) {
  3889. this.parameters = parameters;
  3890. return this;
  3891. }
  3892. /**
  3893. * Returns the parameters of the function call node.
  3894. *
  3895. * @return {Object<string, Node>} The parameters of this node.
  3896. */
  3897. getParameters() {
  3898. return this.parameters;
  3899. }
  3900. /**
  3901. * Returns the type of this function call node.
  3902. *
  3903. * @param {NodeBuilder} builder - The current node builder.
  3904. * @returns {string} The type of this node.
  3905. */
  3906. getNodeType( builder ) {
  3907. return this.functionNode.getNodeType( builder );
  3908. }
  3909. /**
  3910. * Returns the function node of this function call node.
  3911. *
  3912. * @param {NodeBuilder} builder - The current node builder.
  3913. * @param {string} [name] - The name of the member.
  3914. * @returns {string} The type of the member.
  3915. */
  3916. getMemberType( builder, name ) {
  3917. return this.functionNode.getMemberType( builder, name );
  3918. }
  3919. generate( builder ) {
  3920. const params = [];
  3921. const functionNode = this.functionNode;
  3922. const inputs = functionNode.getInputs( builder );
  3923. const parameters = this.parameters;
  3924. const generateInput = ( node, inputNode ) => {
  3925. const type = inputNode.type;
  3926. const pointer = type === 'pointer';
  3927. let output;
  3928. if ( pointer ) output = '&' + node.build( builder );
  3929. else output = node.build( builder, type );
  3930. return output;
  3931. };
  3932. if ( Array.isArray( parameters ) ) {
  3933. if ( parameters.length > inputs.length ) {
  3934. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3935. parameters.length = inputs.length;
  3936. } else if ( parameters.length < inputs.length ) {
  3937. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3938. while ( parameters.length < inputs.length ) {
  3939. parameters.push( float( 0 ) );
  3940. }
  3941. }
  3942. for ( let i = 0; i < parameters.length; i ++ ) {
  3943. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3944. }
  3945. } else {
  3946. for ( const inputNode of inputs ) {
  3947. const node = parameters[ inputNode.name ];
  3948. if ( node !== undefined ) {
  3949. params.push( generateInput( node, inputNode ) );
  3950. } else {
  3951. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3952. params.push( generateInput( float( 0 ), inputNode ) );
  3953. }
  3954. }
  3955. }
  3956. const functionName = functionNode.build( builder, 'property' );
  3957. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3958. }
  3959. }
  3960. const call = ( func, ...params ) => {
  3961. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3962. return new FunctionCallNode( nodeObject( func ), params );
  3963. };
  3964. addMethodChaining( 'call', call );
  3965. const _vectorOperators = {
  3966. '==': 'equal',
  3967. '!=': 'notEqual',
  3968. '<': 'lessThan',
  3969. '>': 'greaterThan',
  3970. '<=': 'lessThanEqual',
  3971. '>=': 'greaterThanEqual',
  3972. '%': 'mod'
  3973. };
  3974. /**
  3975. * This node represents basic mathematical and logical operations like addition,
  3976. * subtraction or comparisons (e.g. `equal()`).
  3977. *
  3978. * @augments TempNode
  3979. */
  3980. class OperatorNode extends TempNode {
  3981. static get type() {
  3982. return 'OperatorNode';
  3983. }
  3984. /**
  3985. * Constructs a new operator node.
  3986. *
  3987. * @param {string} op - The operator.
  3988. * @param {Node} aNode - The first input.
  3989. * @param {Node} bNode - The second input.
  3990. * @param {...Node} params - Additional input parameters.
  3991. */
  3992. constructor( op, aNode, bNode, ...params ) {
  3993. super();
  3994. if ( params.length > 0 ) {
  3995. let finalOp = new OperatorNode( op, aNode, bNode );
  3996. for ( let i = 0; i < params.length - 1; i ++ ) {
  3997. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3998. }
  3999. aNode = finalOp;
  4000. bNode = params[ params.length - 1 ];
  4001. }
  4002. /**
  4003. * The operator.
  4004. *
  4005. * @type {string}
  4006. */
  4007. this.op = op;
  4008. /**
  4009. * The first input.
  4010. *
  4011. * @type {Node}
  4012. */
  4013. this.aNode = aNode;
  4014. /**
  4015. * The second input.
  4016. *
  4017. * @type {Node}
  4018. */
  4019. this.bNode = bNode;
  4020. /**
  4021. * This flag can be used for type testing.
  4022. *
  4023. * @type {boolean}
  4024. * @readonly
  4025. * @default true
  4026. */
  4027. this.isOperatorNode = true;
  4028. }
  4029. /**
  4030. * Returns the operator method name.
  4031. *
  4032. * @param {NodeBuilder} builder - The current node builder.
  4033. * @param {string} output - The output type.
  4034. * @returns {string} The operator method name.
  4035. */
  4036. getOperatorMethod( builder, output ) {
  4037. return builder.getMethod( _vectorOperators[ this.op ], output );
  4038. }
  4039. /**
  4040. * This method is overwritten since the node type is inferred from the operator
  4041. * and the input node types.
  4042. *
  4043. * @param {NodeBuilder} builder - The current node builder.
  4044. * @param {?string} [output=null] - The output type.
  4045. * @return {string} The node type.
  4046. */
  4047. getNodeType( builder, output = null ) {
  4048. const op = this.op;
  4049. const aNode = this.aNode;
  4050. const bNode = this.bNode;
  4051. const typeA = aNode.getNodeType( builder );
  4052. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  4053. if ( typeA === 'void' || typeB === 'void' ) {
  4054. return output || 'void';
  4055. } else if ( op === '%' ) {
  4056. return typeA;
  4057. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  4058. return builder.getIntegerType( typeA );
  4059. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  4060. return 'bool';
  4061. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  4062. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  4063. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  4064. } else {
  4065. // Handle matrix operations
  4066. if ( builder.isMatrix( typeA ) ) {
  4067. if ( typeB === 'float' ) {
  4068. return typeA; // matrix * scalar = matrix
  4069. } else if ( builder.isVector( typeB ) ) {
  4070. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  4071. } else if ( builder.isMatrix( typeB ) ) {
  4072. return typeA; // matrix * matrix
  4073. }
  4074. } else if ( builder.isMatrix( typeB ) ) {
  4075. if ( typeA === 'float' ) {
  4076. return typeB; // scalar * matrix = matrix
  4077. } else if ( builder.isVector( typeA ) ) {
  4078. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  4079. }
  4080. }
  4081. // Handle non-matrix cases
  4082. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  4083. // anytype x anytype: use the greater length vector
  4084. return typeB;
  4085. }
  4086. return typeA;
  4087. }
  4088. }
  4089. generate( builder, output ) {
  4090. const op = this.op;
  4091. const { aNode, bNode } = this;
  4092. const type = this.getNodeType( builder, output );
  4093. let typeA = null;
  4094. let typeB = null;
  4095. if ( type !== 'void' ) {
  4096. typeA = aNode.getNodeType( builder );
  4097. typeB = bNode ? bNode.getNodeType( builder ) : null;
  4098. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  4099. if ( builder.isVector( typeA ) ) {
  4100. typeB = typeA;
  4101. } else if ( builder.isVector( typeB ) ) {
  4102. typeA = typeB;
  4103. } else if ( typeA !== typeB ) {
  4104. typeA = typeB = 'float';
  4105. }
  4106. } else if ( op === '>>' || op === '<<' ) {
  4107. typeA = type;
  4108. typeB = builder.changeComponentType( typeB, 'uint' );
  4109. } else if ( op === '%' ) {
  4110. typeA = type;
  4111. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  4112. } else if ( builder.isMatrix( typeA ) ) {
  4113. if ( typeB === 'float' ) {
  4114. // Keep matrix type for typeA, but ensure typeB stays float
  4115. typeB = 'float';
  4116. } else if ( builder.isVector( typeB ) ) {
  4117. // matrix x vector
  4118. typeB = builder.getVectorFromMatrix( typeA );
  4119. } else if ( builder.isMatrix( typeB ) ) ; else {
  4120. typeA = typeB = type;
  4121. }
  4122. } else if ( builder.isMatrix( typeB ) ) {
  4123. if ( typeA === 'float' ) {
  4124. // Keep matrix type for typeB, but ensure typeA stays float
  4125. typeA = 'float';
  4126. } else if ( builder.isVector( typeA ) ) {
  4127. // vector x matrix
  4128. typeA = builder.getVectorFromMatrix( typeB );
  4129. } else {
  4130. typeA = typeB = type;
  4131. }
  4132. } else {
  4133. // anytype x anytype
  4134. typeA = typeB = type;
  4135. }
  4136. } else {
  4137. typeA = typeB = type;
  4138. }
  4139. const a = aNode.build( builder, typeA );
  4140. const b = bNode ? bNode.build( builder, typeB ) : null;
  4141. const fnOpSnippet = builder.getFunctionOperator( op );
  4142. if ( output !== 'void' ) {
  4143. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  4144. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  4145. if ( isGLSL ) {
  4146. if ( builder.isVector( typeA ) ) {
  4147. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  4148. } else {
  4149. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4150. }
  4151. } else {
  4152. // WGSL
  4153. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4154. }
  4155. } else if ( op === '%' ) {
  4156. if ( builder.isInteger( typeB ) ) {
  4157. return builder.format( `( ${ a } % ${ b } )`, type, output );
  4158. } else {
  4159. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  4160. }
  4161. } else if ( op === '!' || op === '~' ) {
  4162. return builder.format( `(${op}${a})`, typeA, output );
  4163. } else if ( fnOpSnippet ) {
  4164. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4165. } else {
  4166. // Handle matrix operations
  4167. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4168. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  4169. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4170. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4171. } else {
  4172. let snippet = `( ${ a } ${ op } ${ b } )`;
  4173. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4174. snippet = `all${ snippet }`;
  4175. }
  4176. return builder.format( snippet, type, output );
  4177. }
  4178. }
  4179. } else if ( typeA !== 'void' ) {
  4180. if ( fnOpSnippet ) {
  4181. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4182. } else {
  4183. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4184. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4185. } else {
  4186. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4187. }
  4188. }
  4189. }
  4190. }
  4191. serialize( data ) {
  4192. super.serialize( data );
  4193. data.op = this.op;
  4194. }
  4195. deserialize( data ) {
  4196. super.deserialize( data );
  4197. this.op = data.op;
  4198. }
  4199. }
  4200. /**
  4201. * Returns the addition of two or more value.
  4202. *
  4203. * @tsl
  4204. * @function
  4205. * @param {Node} a - The first input.
  4206. * @param {Node} b - The second input.
  4207. * @param {...Node} params - Additional input parameters.
  4208. * @returns {OperatorNode}
  4209. */
  4210. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4211. /**
  4212. * Returns the subtraction of two or more value.
  4213. *
  4214. * @tsl
  4215. * @function
  4216. * @param {Node} a - The first input.
  4217. * @param {Node} b - The second input.
  4218. * @param {...Node} params - Additional input parameters.
  4219. * @returns {OperatorNode}
  4220. */
  4221. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4222. /**
  4223. * Returns the multiplication of two or more value.
  4224. *
  4225. * @tsl
  4226. * @function
  4227. * @param {Node} a - The first input.
  4228. * @param {Node} b - The second input.
  4229. * @param {...Node} params - Additional input parameters.
  4230. * @returns {OperatorNode}
  4231. */
  4232. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4233. /**
  4234. * Returns the division of two or more value.
  4235. *
  4236. * @tsl
  4237. * @function
  4238. * @param {Node} a - The first input.
  4239. * @param {Node} b - The second input.
  4240. * @param {...Node} params - Additional input parameters.
  4241. * @returns {OperatorNode}
  4242. */
  4243. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4244. /**
  4245. * Computes the remainder of dividing the first node by the second one.
  4246. *
  4247. * @tsl
  4248. * @function
  4249. * @param {Node} a - The first input.
  4250. * @param {Node} b - The second input.
  4251. * @returns {OperatorNode}
  4252. */
  4253. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4254. /**
  4255. * Checks if two nodes are equal.
  4256. *
  4257. * @tsl
  4258. * @function
  4259. * @param {Node} a - The first input.
  4260. * @param {Node} b - The second input.
  4261. * @returns {OperatorNode}
  4262. */
  4263. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4264. /**
  4265. * Checks if two nodes are not equal.
  4266. *
  4267. * @tsl
  4268. * @function
  4269. * @param {Node} a - The first input.
  4270. * @param {Node} b - The second input.
  4271. * @returns {OperatorNode}
  4272. */
  4273. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4274. /**
  4275. * Checks if the first node is less than the second.
  4276. *
  4277. * @tsl
  4278. * @function
  4279. * @param {Node} a - The first input.
  4280. * @param {Node} b - The second input.
  4281. * @returns {OperatorNode}
  4282. */
  4283. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4284. /**
  4285. * Checks if the first node is greater than the second.
  4286. *
  4287. * @tsl
  4288. * @function
  4289. * @param {Node} a - The first input.
  4290. * @param {Node} b - The second input.
  4291. * @returns {OperatorNode}
  4292. */
  4293. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4294. /**
  4295. * Checks if the first node is less than or equal to the second.
  4296. *
  4297. * @tsl
  4298. * @function
  4299. * @param {Node} a - The first input.
  4300. * @param {Node} b - The second input.
  4301. * @returns {OperatorNode}
  4302. */
  4303. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4304. /**
  4305. * Checks if the first node is greater than or equal to the second.
  4306. *
  4307. * @tsl
  4308. * @function
  4309. * @param {Node} a - The first input.
  4310. * @param {Node} b - The second input.
  4311. * @returns {OperatorNode}
  4312. */
  4313. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4314. /**
  4315. * Performs a logical AND operation on multiple nodes.
  4316. *
  4317. * @tsl
  4318. * @function
  4319. * @param {...Node} nodes - The input nodes to be combined using AND.
  4320. * @returns {OperatorNode}
  4321. */
  4322. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4323. /**
  4324. * Performs a logical OR operation on multiple nodes.
  4325. *
  4326. * @tsl
  4327. * @function
  4328. * @param {...Node} nodes - The input nodes to be combined using OR.
  4329. * @returns {OperatorNode}
  4330. */
  4331. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4332. /**
  4333. * Performs logical NOT on a node.
  4334. *
  4335. * @tsl
  4336. * @function
  4337. * @param {Node} value - The value.
  4338. * @returns {OperatorNode}
  4339. */
  4340. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4341. /**
  4342. * Performs logical XOR on two nodes.
  4343. *
  4344. * @tsl
  4345. * @function
  4346. * @param {Node} a - The first input.
  4347. * @param {Node} b - The second input.
  4348. * @returns {OperatorNode}
  4349. */
  4350. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4351. /**
  4352. * Performs bitwise AND on two nodes.
  4353. *
  4354. * @tsl
  4355. * @function
  4356. * @param {Node} a - The first input.
  4357. * @param {Node} b - The second input.
  4358. * @returns {OperatorNode}
  4359. */
  4360. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4361. /**
  4362. * Performs bitwise NOT on a node.
  4363. *
  4364. * @tsl
  4365. * @function
  4366. * @param {Node} a - The first input.
  4367. * @param {Node} b - The second input.
  4368. * @returns {OperatorNode}
  4369. */
  4370. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4371. /**
  4372. * Performs bitwise OR on two nodes.
  4373. *
  4374. * @tsl
  4375. * @function
  4376. * @param {Node} a - The first input.
  4377. * @param {Node} b - The second input.
  4378. * @returns {OperatorNode}
  4379. */
  4380. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4381. /**
  4382. * Performs bitwise XOR on two nodes.
  4383. *
  4384. * @tsl
  4385. * @function
  4386. * @param {Node} a - The first input.
  4387. * @param {Node} b - The second input.
  4388. * @returns {OperatorNode}
  4389. */
  4390. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4391. /**
  4392. * Shifts a node to the left.
  4393. *
  4394. * @tsl
  4395. * @function
  4396. * @param {Node} a - The node to shift.
  4397. * @param {Node} b - The value to shift.
  4398. * @returns {OperatorNode}
  4399. */
  4400. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4401. /**
  4402. * Shifts a node to the right.
  4403. *
  4404. * @tsl
  4405. * @function
  4406. * @param {Node} a - The node to shift.
  4407. * @param {Node} b - The value to shift.
  4408. * @returns {OperatorNode}
  4409. */
  4410. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4411. /**
  4412. * Increments a node by 1.
  4413. *
  4414. * @tsl
  4415. * @function
  4416. * @param {Node} a - The node to increment.
  4417. * @returns {OperatorNode}
  4418. */
  4419. const incrementBefore = Fn( ( [ a ] ) => {
  4420. a.addAssign( 1 );
  4421. return a;
  4422. } );
  4423. /**
  4424. * Decrements a node by 1.
  4425. *
  4426. * @tsl
  4427. * @function
  4428. * @param {Node} a - The node to decrement.
  4429. * @returns {OperatorNode}
  4430. */
  4431. const decrementBefore = Fn( ( [ a ] ) => {
  4432. a.subAssign( 1 );
  4433. return a;
  4434. } );
  4435. /**
  4436. * Increments a node by 1 and returns the previous value.
  4437. *
  4438. * @tsl
  4439. * @function
  4440. * @param {Node} a - The node to increment.
  4441. * @returns {OperatorNode}
  4442. */
  4443. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4444. const temp = int( a ).toConst();
  4445. a.addAssign( 1 );
  4446. return temp;
  4447. } );
  4448. /**
  4449. * Decrements a node by 1 and returns the previous value.
  4450. *
  4451. * @tsl
  4452. * @function
  4453. * @param {Node} a - The node to decrement.
  4454. * @returns {OperatorNode}
  4455. */
  4456. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4457. const temp = int( a ).toConst();
  4458. a.subAssign( 1 );
  4459. return temp;
  4460. } );
  4461. addMethodChaining( 'add', add );
  4462. addMethodChaining( 'sub', sub );
  4463. addMethodChaining( 'mul', mul );
  4464. addMethodChaining( 'div', div );
  4465. addMethodChaining( 'mod', mod );
  4466. addMethodChaining( 'equal', equal );
  4467. addMethodChaining( 'notEqual', notEqual );
  4468. addMethodChaining( 'lessThan', lessThan );
  4469. addMethodChaining( 'greaterThan', greaterThan );
  4470. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4471. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4472. addMethodChaining( 'and', and );
  4473. addMethodChaining( 'or', or );
  4474. addMethodChaining( 'not', not );
  4475. addMethodChaining( 'xor', xor );
  4476. addMethodChaining( 'bitAnd', bitAnd );
  4477. addMethodChaining( 'bitNot', bitNot );
  4478. addMethodChaining( 'bitOr', bitOr );
  4479. addMethodChaining( 'bitXor', bitXor );
  4480. addMethodChaining( 'shiftLeft', shiftLeft );
  4481. addMethodChaining( 'shiftRight', shiftRight );
  4482. addMethodChaining( 'incrementBefore', incrementBefore );
  4483. addMethodChaining( 'decrementBefore', decrementBefore );
  4484. addMethodChaining( 'increment', increment );
  4485. addMethodChaining( 'decrement', decrement );
  4486. /**
  4487. * @tsl
  4488. * @function
  4489. * @deprecated since r175. Use {@link mod} instead.
  4490. *
  4491. * @param {Node} a - The first input.
  4492. * @param {Node} b - The second input.
  4493. * @returns {OperatorNode}
  4494. */
  4495. const modInt = ( a, b ) => { // @deprecated, r175
  4496. warn( 'TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.', new StackTrace() );
  4497. return mod( int( a ), int( b ) );
  4498. };
  4499. addMethodChaining( 'modInt', modInt );
  4500. /**
  4501. * This node represents a variety of mathematical methods available in shaders.
  4502. * They are divided into three categories:
  4503. *
  4504. * - Methods with one input like `sin`, `cos` or `normalize`.
  4505. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4506. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4507. *
  4508. * @augments TempNode
  4509. */
  4510. class MathNode extends TempNode {
  4511. static get type() {
  4512. return 'MathNode';
  4513. }
  4514. /**
  4515. * Constructs a new math node.
  4516. *
  4517. * @param {string} method - The method name.
  4518. * @param {Node} aNode - The first input.
  4519. * @param {?Node} [bNode=null] - The second input.
  4520. * @param {?Node} [cNode=null] - The third input.
  4521. */
  4522. constructor( method, aNode, bNode = null, cNode = null ) {
  4523. super();
  4524. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4525. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4526. let finalOp = new MathNode( method, aNode, bNode );
  4527. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4528. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4529. }
  4530. aNode = finalOp;
  4531. bNode = arguments[ arguments.length - 1 ];
  4532. cNode = null;
  4533. }
  4534. /**
  4535. * The method name.
  4536. *
  4537. * @type {string}
  4538. */
  4539. this.method = method;
  4540. /**
  4541. * The first input.
  4542. *
  4543. * @type {Node}
  4544. */
  4545. this.aNode = aNode;
  4546. /**
  4547. * The second input.
  4548. *
  4549. * @type {?Node}
  4550. * @default null
  4551. */
  4552. this.bNode = bNode;
  4553. /**
  4554. * The third input.
  4555. *
  4556. * @type {?Node}
  4557. * @default null
  4558. */
  4559. this.cNode = cNode;
  4560. /**
  4561. * This flag can be used for type testing.
  4562. *
  4563. * @type {boolean}
  4564. * @readonly
  4565. * @default true
  4566. */
  4567. this.isMathNode = true;
  4568. }
  4569. /**
  4570. * The input type is inferred from the node types of the input nodes.
  4571. *
  4572. * @param {NodeBuilder} builder - The current node builder.
  4573. * @return {string} The input type.
  4574. */
  4575. getInputType( builder ) {
  4576. const aType = this.aNode.getNodeType( builder );
  4577. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4578. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4579. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4580. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4581. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4582. if ( aLen > bLen && aLen > cLen ) {
  4583. return aType;
  4584. } else if ( bLen > cLen ) {
  4585. return bType;
  4586. } else if ( cLen > aLen ) {
  4587. return cType;
  4588. }
  4589. return aType;
  4590. }
  4591. /**
  4592. * The selected method as well as the input type determine the node type of this node.
  4593. *
  4594. * @param {NodeBuilder} builder - The current node builder.
  4595. * @return {string} The node type.
  4596. */
  4597. getNodeType( builder ) {
  4598. const method = this.method;
  4599. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4600. return 'float';
  4601. } else if ( method === MathNode.CROSS ) {
  4602. return 'vec3';
  4603. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4604. return 'bool';
  4605. } else if ( method === MathNode.EQUALS ) {
  4606. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4607. } else {
  4608. return this.getInputType( builder );
  4609. }
  4610. }
  4611. setup( builder ) {
  4612. const { aNode, bNode, method } = this;
  4613. let outputNode = null;
  4614. if ( method === MathNode.ONE_MINUS ) {
  4615. outputNode = sub( 1.0, aNode );
  4616. } else if ( method === MathNode.RECIPROCAL ) {
  4617. outputNode = div( 1.0, aNode );
  4618. } else if ( method === MathNode.DIFFERENCE ) {
  4619. outputNode = abs( sub( aNode, bNode ) );
  4620. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4621. // dir can be either a direction vector or a normal vector
  4622. // upper-left 3x3 of matrix is assumed to be orthogonal
  4623. let tA = aNode;
  4624. let tB = bNode;
  4625. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4626. tB = vec4( vec3( tB ), 0.0 );
  4627. } else {
  4628. tA = vec4( vec3( tA ), 0.0 );
  4629. }
  4630. const mulNode = mul( tA, tB ).xyz;
  4631. outputNode = normalize( mulNode );
  4632. }
  4633. if ( outputNode !== null ) {
  4634. return outputNode;
  4635. } else {
  4636. return super.setup( builder );
  4637. }
  4638. }
  4639. generate( builder, output ) {
  4640. const properties = builder.getNodeProperties( this );
  4641. if ( properties.outputNode ) {
  4642. return super.generate( builder, output );
  4643. }
  4644. let method = this.method;
  4645. const type = this.getNodeType( builder );
  4646. const inputType = this.getInputType( builder );
  4647. const a = this.aNode;
  4648. const b = this.bNode;
  4649. const c = this.cNode;
  4650. const coordinateSystem = builder.renderer.coordinateSystem;
  4651. if ( method === MathNode.NEGATE ) {
  4652. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4653. } else {
  4654. const params = [];
  4655. if ( method === MathNode.CROSS ) {
  4656. params.push(
  4657. a.build( builder, type ),
  4658. b.build( builder, type )
  4659. );
  4660. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4661. params.push(
  4662. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4663. b.build( builder, inputType )
  4664. );
  4665. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4666. params.push(
  4667. a.build( builder, inputType ),
  4668. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4669. );
  4670. } else if ( method === MathNode.REFRACT ) {
  4671. params.push(
  4672. a.build( builder, inputType ),
  4673. b.build( builder, inputType ),
  4674. c.build( builder, 'float' )
  4675. );
  4676. } else if ( method === MathNode.MIX ) {
  4677. params.push(
  4678. a.build( builder, inputType ),
  4679. b.build( builder, inputType ),
  4680. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4681. );
  4682. } else {
  4683. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4684. method = 'atan2';
  4685. }
  4686. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4687. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.`, this.stackTrace );
  4688. method = '/*' + method + '*/';
  4689. }
  4690. params.push( a.build( builder, inputType ) );
  4691. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4692. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4693. }
  4694. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4695. }
  4696. }
  4697. serialize( data ) {
  4698. super.serialize( data );
  4699. data.method = this.method;
  4700. }
  4701. deserialize( data ) {
  4702. super.deserialize( data );
  4703. this.method = data.method;
  4704. }
  4705. }
  4706. // 1 input
  4707. MathNode.ALL = 'all';
  4708. MathNode.ANY = 'any';
  4709. MathNode.RADIANS = 'radians';
  4710. MathNode.DEGREES = 'degrees';
  4711. MathNode.EXP = 'exp';
  4712. MathNode.EXP2 = 'exp2';
  4713. MathNode.LOG = 'log';
  4714. MathNode.LOG2 = 'log2';
  4715. MathNode.SQRT = 'sqrt';
  4716. MathNode.INVERSE_SQRT = 'inversesqrt';
  4717. MathNode.FLOOR = 'floor';
  4718. MathNode.CEIL = 'ceil';
  4719. MathNode.NORMALIZE = 'normalize';
  4720. MathNode.FRACT = 'fract';
  4721. MathNode.SIN = 'sin';
  4722. MathNode.COS = 'cos';
  4723. MathNode.TAN = 'tan';
  4724. MathNode.ASIN = 'asin';
  4725. MathNode.ACOS = 'acos';
  4726. MathNode.ATAN = 'atan';
  4727. MathNode.ABS = 'abs';
  4728. MathNode.SIGN = 'sign';
  4729. MathNode.LENGTH = 'length';
  4730. MathNode.NEGATE = 'negate';
  4731. MathNode.ONE_MINUS = 'oneMinus';
  4732. MathNode.DFDX = 'dFdx';
  4733. MathNode.DFDY = 'dFdy';
  4734. MathNode.ROUND = 'round';
  4735. MathNode.RECIPROCAL = 'reciprocal';
  4736. MathNode.TRUNC = 'trunc';
  4737. MathNode.FWIDTH = 'fwidth';
  4738. MathNode.TRANSPOSE = 'transpose';
  4739. MathNode.DETERMINANT = 'determinant';
  4740. MathNode.INVERSE = 'inverse';
  4741. // 2 inputs
  4742. MathNode.EQUALS = 'equals';
  4743. MathNode.MIN = 'min';
  4744. MathNode.MAX = 'max';
  4745. MathNode.STEP = 'step';
  4746. MathNode.REFLECT = 'reflect';
  4747. MathNode.DISTANCE = 'distance';
  4748. MathNode.DIFFERENCE = 'difference';
  4749. MathNode.DOT = 'dot';
  4750. MathNode.CROSS = 'cross';
  4751. MathNode.POW = 'pow';
  4752. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4753. // 3 inputs
  4754. MathNode.MIX = 'mix';
  4755. MathNode.CLAMP = 'clamp';
  4756. MathNode.REFRACT = 'refract';
  4757. MathNode.SMOOTHSTEP = 'smoothstep';
  4758. MathNode.FACEFORWARD = 'faceforward';
  4759. // 1 inputs
  4760. /**
  4761. * A small value used to handle floating-point precision errors.
  4762. *
  4763. * @tsl
  4764. * @type {Node<float>}
  4765. */
  4766. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4767. /**
  4768. * Represents infinity.
  4769. *
  4770. * @tsl
  4771. * @type {Node<float>}
  4772. */
  4773. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4774. /**
  4775. * Represents PI.
  4776. *
  4777. * @tsl
  4778. * @type {Node<float>}
  4779. */
  4780. const PI = /*@__PURE__*/ float( Math.PI );
  4781. /**
  4782. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4783. *
  4784. * @tsl
  4785. * @deprecated
  4786. * @type {Node<float>}
  4787. */
  4788. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4789. /**
  4790. * Represents PI * 2.
  4791. *
  4792. * @tsl
  4793. * @type {Node<float>}
  4794. */
  4795. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4796. /**
  4797. * Represents PI / 2.
  4798. *
  4799. * @tsl
  4800. * @type {Node<float>}
  4801. */
  4802. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4803. /**
  4804. * Returns `true` if all components of `x` are `true`.
  4805. *
  4806. * @tsl
  4807. * @function
  4808. * @param {Node | number} x - The parameter.
  4809. * @returns {Node<bool>}
  4810. */
  4811. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4812. /**
  4813. * Returns `true` if any components of `x` are `true`.
  4814. *
  4815. * @tsl
  4816. * @function
  4817. * @param {Node | number} x - The parameter.
  4818. * @returns {Node<bool>}
  4819. */
  4820. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4821. /**
  4822. * Converts a quantity in degrees to radians.
  4823. *
  4824. * @tsl
  4825. * @function
  4826. * @param {Node | number} x - The input in degrees.
  4827. * @returns {Node}
  4828. */
  4829. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4830. /**
  4831. * Convert a quantity in radians to degrees.
  4832. *
  4833. * @tsl
  4834. * @function
  4835. * @param {Node | number} x - The input in radians.
  4836. * @returns {Node}
  4837. */
  4838. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4839. /**
  4840. * Returns the natural exponentiation of the parameter.
  4841. *
  4842. * @tsl
  4843. * @function
  4844. * @param {Node | number} x - The parameter.
  4845. * @returns {Node}
  4846. */
  4847. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4848. /**
  4849. * Returns 2 raised to the power of the parameter.
  4850. *
  4851. * @tsl
  4852. * @function
  4853. * @param {Node | number} x - The parameter.
  4854. * @returns {Node}
  4855. */
  4856. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4857. /**
  4858. * Returns the natural logarithm of the parameter.
  4859. *
  4860. * @tsl
  4861. * @function
  4862. * @param {Node | number} x - The parameter.
  4863. * @returns {Node}
  4864. */
  4865. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4866. /**
  4867. * Returns the base 2 logarithm of the parameter.
  4868. *
  4869. * @tsl
  4870. * @function
  4871. * @param {Node | number} x - The parameter.
  4872. * @returns {Node}
  4873. */
  4874. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4875. /**
  4876. * Returns the square root of the parameter.
  4877. *
  4878. * @tsl
  4879. * @function
  4880. * @param {Node | number} x - The parameter.
  4881. * @returns {Node}
  4882. */
  4883. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4884. /**
  4885. * Returns the inverse of the square root of the parameter.
  4886. *
  4887. * @tsl
  4888. * @function
  4889. * @param {Node | number} x - The parameter.
  4890. * @returns {Node}
  4891. */
  4892. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4893. /**
  4894. * Finds the nearest integer less than or equal to the parameter.
  4895. *
  4896. * @tsl
  4897. * @function
  4898. * @param {Node | number} x - The parameter.
  4899. * @returns {Node}
  4900. */
  4901. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4902. /**
  4903. * Finds the nearest integer that is greater than or equal to the parameter.
  4904. *
  4905. * @tsl
  4906. * @function
  4907. * @param {Node | number} x - The parameter.
  4908. * @returns {Node}
  4909. */
  4910. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4911. /**
  4912. * Calculates the unit vector in the same direction as the original vector.
  4913. *
  4914. * @tsl
  4915. * @function
  4916. * @param {Node} x - The input vector.
  4917. * @returns {Node}
  4918. */
  4919. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4920. /**
  4921. * Computes the fractional part of the parameter.
  4922. *
  4923. * @tsl
  4924. * @function
  4925. * @param {Node | number} x - The parameter.
  4926. * @returns {Node}
  4927. */
  4928. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4929. /**
  4930. * Returns the sine of the parameter.
  4931. *
  4932. * @tsl
  4933. * @function
  4934. * @param {Node | number} x - The parameter.
  4935. * @returns {Node}
  4936. */
  4937. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4938. /**
  4939. * Returns the cosine of the parameter.
  4940. *
  4941. * @tsl
  4942. * @function
  4943. * @param {Node | number} x - The parameter.
  4944. * @returns {Node}
  4945. */
  4946. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4947. /**
  4948. * Returns the tangent of the parameter.
  4949. *
  4950. * @tsl
  4951. * @function
  4952. * @param {Node | number} x - The parameter.
  4953. * @returns {Node}
  4954. */
  4955. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4956. /**
  4957. * Returns the arcsine of the parameter.
  4958. *
  4959. * @tsl
  4960. * @function
  4961. * @param {Node | number} x - The parameter.
  4962. * @returns {Node}
  4963. */
  4964. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4965. /**
  4966. * Returns the arccosine of the parameter.
  4967. *
  4968. * @tsl
  4969. * @function
  4970. * @param {Node | number} x - The parameter.
  4971. * @returns {Node}
  4972. */
  4973. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4974. /**
  4975. * Returns the arc-tangent of the parameter.
  4976. * If two parameters are provided, the result is `atan2(y/x)`.
  4977. *
  4978. * @tsl
  4979. * @function
  4980. * @param {Node | number} y - The y parameter.
  4981. * @param {?(Node | number)} x - The x parameter.
  4982. * @returns {Node}
  4983. */
  4984. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4985. /**
  4986. * Returns the absolute value of the parameter.
  4987. *
  4988. * @tsl
  4989. * @function
  4990. * @param {Node | number} x - The parameter.
  4991. * @returns {Node}
  4992. */
  4993. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4994. /**
  4995. * Extracts the sign of the parameter.
  4996. *
  4997. * @tsl
  4998. * @function
  4999. * @param {Node | number} x - The parameter.
  5000. * @returns {Node}
  5001. */
  5002. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  5003. /**
  5004. * Calculates the length of a vector.
  5005. *
  5006. * @tsl
  5007. * @function
  5008. * @param {Node} x - The parameter.
  5009. * @returns {Node<float>}
  5010. */
  5011. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  5012. /**
  5013. * Negates the value of the parameter (-x).
  5014. *
  5015. * @tsl
  5016. * @function
  5017. * @param {Node | number} x - The parameter.
  5018. * @returns {Node}
  5019. */
  5020. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  5021. /**
  5022. * Return `1` minus the parameter.
  5023. *
  5024. * @tsl
  5025. * @function
  5026. * @param {Node | number} x - The parameter.
  5027. * @returns {Node}
  5028. */
  5029. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  5030. /**
  5031. * Returns the partial derivative of the parameter with respect to x.
  5032. *
  5033. * @tsl
  5034. * @function
  5035. * @param {Node | number} x - The parameter.
  5036. * @returns {Node}
  5037. */
  5038. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  5039. /**
  5040. * Returns the partial derivative of the parameter with respect to y.
  5041. *
  5042. * @tsl
  5043. * @function
  5044. * @param {Node | number} x - The parameter.
  5045. * @returns {Node}
  5046. */
  5047. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  5048. /**
  5049. * Rounds the parameter to the nearest integer.
  5050. *
  5051. * @tsl
  5052. * @function
  5053. * @param {Node | number} x - The parameter.
  5054. * @returns {Node}
  5055. */
  5056. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  5057. /**
  5058. * Returns the reciprocal of the parameter `(1/x)`.
  5059. *
  5060. * @tsl
  5061. * @function
  5062. * @param {Node | number} x - The parameter.
  5063. * @returns {Node}
  5064. */
  5065. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  5066. /**
  5067. * Truncates the parameter, removing the fractional part.
  5068. *
  5069. * @tsl
  5070. * @function
  5071. * @param {Node | number} x - The parameter.
  5072. * @returns {Node}
  5073. */
  5074. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  5075. /**
  5076. * Returns the sum of the absolute derivatives in x and y.
  5077. *
  5078. * @tsl
  5079. * @function
  5080. * @param {Node | number} x - The parameter.
  5081. * @returns {Node}
  5082. */
  5083. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  5084. /**
  5085. * Returns the transpose of a matrix.
  5086. *
  5087. * @tsl
  5088. * @function
  5089. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5090. * @returns {Node}
  5091. */
  5092. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  5093. /**
  5094. * Returns the determinant of a matrix.
  5095. *
  5096. * @tsl
  5097. * @function
  5098. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5099. * @returns {Node<float>}
  5100. */
  5101. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  5102. /**
  5103. * Returns the inverse of a matrix.
  5104. *
  5105. * @tsl
  5106. * @function
  5107. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  5108. * @returns {Node<mat2|mat3|mat4>}
  5109. */
  5110. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  5111. // 2 inputs
  5112. /**
  5113. * Returns the least of the given values.
  5114. *
  5115. * @tsl
  5116. * @function
  5117. * @param {...(Node | number)} values - The values to compare.
  5118. * @returns {Node}
  5119. */
  5120. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  5121. /**
  5122. * Returns the greatest of the given values.
  5123. *
  5124. * @tsl
  5125. * @function
  5126. * @param {...(Node | number)} values - The values to compare.
  5127. * @returns {Node}
  5128. */
  5129. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  5130. /**
  5131. * Generate a step function by comparing two values.
  5132. *
  5133. * @tsl
  5134. * @function
  5135. * @param {Node | number} x - The y parameter.
  5136. * @param {Node | number} y - The x parameter.
  5137. * @returns {Node}
  5138. */
  5139. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  5140. /**
  5141. * Calculates the reflection direction for an incident vector.
  5142. *
  5143. * @tsl
  5144. * @function
  5145. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5146. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5147. * @returns {Node<vec2|vec3|vec4>}
  5148. */
  5149. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  5150. /**
  5151. * Calculates the distance between two points.
  5152. *
  5153. * @tsl
  5154. * @function
  5155. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5156. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5157. * @returns {Node<float>}
  5158. */
  5159. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5160. /**
  5161. * Calculates the absolute difference between two values.
  5162. *
  5163. * @tsl
  5164. * @function
  5165. * @param {Node | number} x - The first parameter.
  5166. * @param {Node | number} y - The second parameter.
  5167. * @returns {Node}
  5168. */
  5169. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5170. /**
  5171. * Calculates the dot product of two vectors.
  5172. *
  5173. * @tsl
  5174. * @function
  5175. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5176. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5177. * @returns {Node<float>}
  5178. */
  5179. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5180. /**
  5181. * Calculates the cross product of two vectors.
  5182. *
  5183. * @tsl
  5184. * @function
  5185. * @param {Node<vec2|vec3>} x - The first vector.
  5186. * @param {Node<vec2|vec3>} y - The second vector.
  5187. * @returns {Node<float|vec3>}
  5188. */
  5189. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5190. /**
  5191. * Return the value of the first parameter raised to the power of the second one.
  5192. *
  5193. * @tsl
  5194. * @function
  5195. * @param {Node | number} x - The first parameter.
  5196. * @param {Node | number} y - The second parameter.
  5197. * @returns {Node}
  5198. */
  5199. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5200. /**
  5201. * Returns the square of the parameter.
  5202. *
  5203. * @tsl
  5204. * @function
  5205. * @param {Node | number} x - The first parameter.
  5206. * @returns {Node}
  5207. */
  5208. const pow2 = ( x ) => mul( x, x );
  5209. /**
  5210. * Returns the cube of the parameter.
  5211. *
  5212. * @tsl
  5213. * @function
  5214. * @param {Node | number} x - The first parameter.
  5215. * @returns {Node}
  5216. */
  5217. const pow3 = ( x ) => mul( x, x, x );
  5218. /**
  5219. * Returns the fourth power of the parameter.
  5220. *
  5221. * @tsl
  5222. * @function
  5223. * @param {Node | number} x - The first parameter.
  5224. * @returns {Node}
  5225. */
  5226. const pow4 = ( x ) => mul( x, x, x, x );
  5227. /**
  5228. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5229. *
  5230. * @tsl
  5231. * @function
  5232. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5233. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5234. * @returns {Node}
  5235. */
  5236. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5237. /**
  5238. * Returns the cube root of a number.
  5239. *
  5240. * @tsl
  5241. * @function
  5242. * @param {Node | number} a - The first parameter.
  5243. * @returns {Node}
  5244. */
  5245. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5246. /**
  5247. * Calculate the squared length of a vector.
  5248. *
  5249. * @tsl
  5250. * @function
  5251. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5252. * @returns {Node<float>}
  5253. */
  5254. const lengthSq = ( a ) => dot( a, a );
  5255. /**
  5256. * Linearly interpolates between two values.
  5257. *
  5258. * @tsl
  5259. * @function
  5260. * @param {Node | number} a - The first parameter.
  5261. * @param {Node | number} b - The second parameter.
  5262. * @param {Node | number} t - The interpolation value.
  5263. * @returns {Node}
  5264. */
  5265. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5266. /**
  5267. * Constrains a value to lie between two further values.
  5268. *
  5269. * @tsl
  5270. * @function
  5271. * @param {Node | number} value - The value to constrain.
  5272. * @param {Node | number} [low=0] - The lower bound.
  5273. * @param {Node | number} [high=1] - The upper bound.
  5274. * @returns {Node}
  5275. */
  5276. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  5277. /**
  5278. * Constrains a value between `0` and `1`.
  5279. *
  5280. * @tsl
  5281. * @function
  5282. * @param {Node | number} value - The value to constrain.
  5283. * @returns {Node}
  5284. */
  5285. const saturate = ( value ) => clamp( value );
  5286. /**
  5287. * Calculates the refraction direction for an incident vector.
  5288. *
  5289. * @tsl
  5290. * @function
  5291. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5292. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5293. * @param {Node<float>} eta - The ratio of indices of refraction.
  5294. * @returns {Node<vec2|vec3|vec4>}
  5295. */
  5296. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5297. /**
  5298. * Performs a Hermite interpolation between two values.
  5299. *
  5300. * @tsl
  5301. * @function
  5302. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5303. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5304. * @param {Node | number} x - The source value for interpolation.
  5305. * @returns {Node}
  5306. */
  5307. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5308. /**
  5309. * Returns a vector pointing in the same direction as another.
  5310. *
  5311. * @tsl
  5312. * @function
  5313. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5314. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5315. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5316. * @returns {Node<vec2|vec3|vec4>}
  5317. */
  5318. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5319. /**
  5320. * Returns a random value for the given uv.
  5321. *
  5322. * @tsl
  5323. * @function
  5324. * @param {Node<vec2>} uv - The uv node.
  5325. * @returns {Node<float>}
  5326. */
  5327. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5328. const a = 12.9898, b = 78.233, c = 43758.5453;
  5329. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5330. return fract( sin( sn ).mul( c ) );
  5331. } );
  5332. /**
  5333. * Alias for `mix()` with a different parameter order.
  5334. *
  5335. * @tsl
  5336. * @function
  5337. * @param {Node | number} t - The interpolation value.
  5338. * @param {Node | number} e1 - The first parameter.
  5339. * @param {Node | number} e2 - The second parameter.
  5340. * @returns {Node}
  5341. */
  5342. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5343. /**
  5344. * Alias for `smoothstep()` with a different parameter order.
  5345. *
  5346. * @tsl
  5347. * @function
  5348. * @param {Node | number} x - The source value for interpolation.
  5349. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5350. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5351. * @returns {Node}
  5352. */
  5353. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5354. /**
  5355. * Alias for `step()` with a different parameter order.
  5356. *
  5357. * @tsl
  5358. * @function
  5359. * @param {Node | number} x - The source value for interpolation.
  5360. * @param {Node | number} edge - The edge value.
  5361. * @returns {Node}
  5362. */
  5363. const stepElement = ( x, edge ) => step( edge, x );
  5364. // GLSL alias function
  5365. const faceforward = faceForward;
  5366. const inversesqrt = inverseSqrt;
  5367. // Method chaining
  5368. addMethodChaining( 'all', all );
  5369. addMethodChaining( 'any', any );
  5370. addMethodChaining( 'radians', radians );
  5371. addMethodChaining( 'degrees', degrees );
  5372. addMethodChaining( 'exp', exp );
  5373. addMethodChaining( 'exp2', exp2 );
  5374. addMethodChaining( 'log', log );
  5375. addMethodChaining( 'log2', log2 );
  5376. addMethodChaining( 'sqrt', sqrt );
  5377. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5378. addMethodChaining( 'floor', floor );
  5379. addMethodChaining( 'ceil', ceil );
  5380. addMethodChaining( 'normalize', normalize );
  5381. addMethodChaining( 'fract', fract );
  5382. addMethodChaining( 'sin', sin );
  5383. addMethodChaining( 'cos', cos );
  5384. addMethodChaining( 'tan', tan );
  5385. addMethodChaining( 'asin', asin );
  5386. addMethodChaining( 'acos', acos );
  5387. addMethodChaining( 'atan', atan );
  5388. addMethodChaining( 'abs', abs );
  5389. addMethodChaining( 'sign', sign );
  5390. addMethodChaining( 'length', length );
  5391. addMethodChaining( 'lengthSq', lengthSq );
  5392. addMethodChaining( 'negate', negate );
  5393. addMethodChaining( 'oneMinus', oneMinus );
  5394. addMethodChaining( 'dFdx', dFdx );
  5395. addMethodChaining( 'dFdy', dFdy );
  5396. addMethodChaining( 'round', round );
  5397. addMethodChaining( 'reciprocal', reciprocal );
  5398. addMethodChaining( 'trunc', trunc );
  5399. addMethodChaining( 'fwidth', fwidth );
  5400. addMethodChaining( 'min', min$1 );
  5401. addMethodChaining( 'max', max$1 );
  5402. addMethodChaining( 'step', stepElement );
  5403. addMethodChaining( 'reflect', reflect );
  5404. addMethodChaining( 'distance', distance );
  5405. addMethodChaining( 'dot', dot );
  5406. addMethodChaining( 'cross', cross );
  5407. addMethodChaining( 'pow', pow );
  5408. addMethodChaining( 'pow2', pow2 );
  5409. addMethodChaining( 'pow3', pow3 );
  5410. addMethodChaining( 'pow4', pow4 );
  5411. addMethodChaining( 'transformDirection', transformDirection );
  5412. addMethodChaining( 'mix', mixElement );
  5413. addMethodChaining( 'clamp', clamp );
  5414. addMethodChaining( 'refract', refract );
  5415. addMethodChaining( 'smoothstep', smoothstepElement );
  5416. addMethodChaining( 'faceForward', faceForward );
  5417. addMethodChaining( 'difference', difference );
  5418. addMethodChaining( 'saturate', saturate );
  5419. addMethodChaining( 'cbrt', cbrt );
  5420. addMethodChaining( 'transpose', transpose );
  5421. addMethodChaining( 'determinant', determinant );
  5422. addMethodChaining( 'inverse', inverse );
  5423. addMethodChaining( 'rand', rand );
  5424. /**
  5425. * Represents a logical `if/else` statement. Can be used as an alternative
  5426. * to the `If()`/`Else()` syntax.
  5427. *
  5428. * The corresponding TSL `select()` looks like so:
  5429. * ```js
  5430. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5431. * ```
  5432. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5433. * determine the outcome of the entire statement.
  5434. *
  5435. * @augments Node
  5436. */
  5437. class ConditionalNode extends Node {
  5438. static get type() {
  5439. return 'ConditionalNode';
  5440. }
  5441. /**
  5442. * Constructs a new conditional node.
  5443. *
  5444. * @param {Node} condNode - The node that defines the condition.
  5445. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5446. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5447. */
  5448. constructor( condNode, ifNode, elseNode = null ) {
  5449. super();
  5450. /**
  5451. * The node that defines the condition.
  5452. *
  5453. * @type {Node}
  5454. */
  5455. this.condNode = condNode;
  5456. /**
  5457. * The node that is evaluate when the condition ends up `true`.
  5458. *
  5459. * @type {Node}
  5460. */
  5461. this.ifNode = ifNode;
  5462. /**
  5463. * The node that is evaluate when the condition ends up `false`.
  5464. *
  5465. * @type {?Node}
  5466. * @default null
  5467. */
  5468. this.elseNode = elseNode;
  5469. }
  5470. /**
  5471. * This method is overwritten since the node type is inferred from the if/else
  5472. * nodes.
  5473. *
  5474. * @param {NodeBuilder} builder - The current node builder.
  5475. * @return {string} The node type.
  5476. */
  5477. getNodeType( builder ) {
  5478. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5479. if ( ifNode === undefined ) {
  5480. // fallback setup
  5481. builder.flowBuildStage( this, 'setup' );
  5482. return this.getNodeType( builder );
  5483. }
  5484. const ifType = ifNode.getNodeType( builder );
  5485. if ( elseNode !== null ) {
  5486. const elseType = elseNode.getNodeType( builder );
  5487. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5488. return elseType;
  5489. }
  5490. }
  5491. return ifType;
  5492. }
  5493. setup( builder ) {
  5494. const condNode = this.condNode;
  5495. const ifNode = this.ifNode.isolate();
  5496. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5497. //
  5498. const currentNodeBlock = builder.context.nodeBlock;
  5499. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5500. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5501. //
  5502. const isUniformFlow = builder.context.uniformFlow;
  5503. const properties = builder.getNodeProperties( this );
  5504. properties.condNode = condNode;
  5505. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5506. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5507. }
  5508. generate( builder, output ) {
  5509. const type = this.getNodeType( builder );
  5510. const nodeData = builder.getDataFromNode( this );
  5511. if ( nodeData.nodeProperty !== undefined ) {
  5512. return nodeData.nodeProperty;
  5513. }
  5514. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5515. const functionNode = builder.currentFunctionNode;
  5516. const needsOutput = output !== 'void';
  5517. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5518. nodeData.nodeProperty = nodeProperty;
  5519. const nodeSnippet = condNode.build( builder, 'bool' );
  5520. const isUniformFlow = builder.context.uniformFlow;
  5521. if ( isUniformFlow && elseNode !== null ) {
  5522. const ifSnippet = ifNode.build( builder, type );
  5523. const elseSnippet = elseNode.build( builder, type );
  5524. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5525. // TODO: If node property already exists return something else
  5526. return builder.format( mathSnippet, type, output );
  5527. }
  5528. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5529. let ifSnippet = ifNode.build( builder, type );
  5530. if ( ifSnippet ) {
  5531. if ( needsOutput ) {
  5532. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5533. } else {
  5534. ifSnippet = 'return ' + ifSnippet + ';';
  5535. if ( functionNode === null ) {
  5536. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.', this.stackTrace );
  5537. ifSnippet = '// ' + ifSnippet;
  5538. }
  5539. }
  5540. }
  5541. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5542. if ( elseNode !== null ) {
  5543. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5544. let elseSnippet = elseNode.build( builder, type );
  5545. if ( elseSnippet ) {
  5546. if ( needsOutput ) {
  5547. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5548. } else {
  5549. elseSnippet = 'return ' + elseSnippet + ';';
  5550. if ( functionNode === null ) {
  5551. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.', this.stackTrace );
  5552. elseSnippet = '// ' + elseSnippet;
  5553. }
  5554. }
  5555. }
  5556. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5557. } else {
  5558. builder.addFlowCode( '\n\n' );
  5559. }
  5560. return builder.format( nodeProperty, type, output );
  5561. }
  5562. }
  5563. /**
  5564. * TSL function for creating a conditional node.
  5565. *
  5566. * @tsl
  5567. * @function
  5568. * @param {Node} condNode - The node that defines the condition.
  5569. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5570. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5571. * @returns {ConditionalNode}
  5572. */
  5573. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5574. addMethodChaining( 'select', select );
  5575. /**
  5576. * This node can be used as a context management component for another node.
  5577. * {@link NodeBuilder} performs its node building process in a specific context and
  5578. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5579. *
  5580. * ```js
  5581. *node.context( { getUV: () => customCoord } );
  5582. *\// or
  5583. *material.contextNode = context( { getUV: () => customCoord } );
  5584. *\// or
  5585. *renderer.contextNode = context( { getUV: () => customCoord } );
  5586. *\// or
  5587. *scenePass.contextNode = context( { getUV: () => customCoord } );
  5588. *```
  5589. * @augments Node
  5590. */
  5591. class ContextNode extends Node {
  5592. static get type() {
  5593. return 'ContextNode';
  5594. }
  5595. /**
  5596. * Constructs a new context node.
  5597. *
  5598. * @param {Node} node - The node whose context should be modified.
  5599. * @param {Object} [value={}] - The modified context data.
  5600. */
  5601. constructor( node = null, value = {} ) {
  5602. super();
  5603. /**
  5604. * This flag can be used for type testing.
  5605. *
  5606. * @type {boolean}
  5607. * @readonly
  5608. * @default true
  5609. */
  5610. this.isContextNode = true;
  5611. /**
  5612. * The node whose context should be modified.
  5613. *
  5614. * @type {Node}
  5615. */
  5616. this.node = node;
  5617. /**
  5618. * The modified context data.
  5619. *
  5620. * @type {Object}
  5621. * @default {}
  5622. */
  5623. this.value = value;
  5624. }
  5625. /**
  5626. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5627. *
  5628. * @return {Node} A reference to {@link ContextNode#node}.
  5629. */
  5630. getScope() {
  5631. return this.node.getScope();
  5632. }
  5633. /**
  5634. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5635. *
  5636. * @param {NodeBuilder} builder - The current node builder.
  5637. * @return {string} The node type.
  5638. */
  5639. getNodeType( builder ) {
  5640. return this.node.getNodeType( builder );
  5641. }
  5642. /**
  5643. * Gathers the context data from all parent context nodes.
  5644. *
  5645. * @return {Object} The gathered context data.
  5646. */
  5647. getFlowContextData() {
  5648. const children = [];
  5649. this.traverse( ( node ) => {
  5650. if ( node.isContextNode === true ) {
  5651. children.push( node.value );
  5652. }
  5653. } );
  5654. return Object.assign( {}, ...children );
  5655. }
  5656. /**
  5657. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5658. *
  5659. * @param {NodeBuilder} builder - The current node builder.
  5660. * @param {string} name - The member name.
  5661. * @returns {string} The member type.
  5662. */
  5663. getMemberType( builder, name ) {
  5664. return this.node.getMemberType( builder, name );
  5665. }
  5666. analyze( builder ) {
  5667. const previousContext = builder.addContext( this.value );
  5668. this.node.build( builder );
  5669. builder.setContext( previousContext );
  5670. }
  5671. setup( builder ) {
  5672. const previousContext = builder.addContext( this.value );
  5673. this.node.build( builder );
  5674. builder.setContext( previousContext );
  5675. }
  5676. generate( builder, output ) {
  5677. const previousContext = builder.addContext( this.value );
  5678. const snippet = this.node.build( builder, output );
  5679. builder.setContext( previousContext );
  5680. return snippet;
  5681. }
  5682. }
  5683. /**
  5684. * TSL function for creating a context node.
  5685. *
  5686. * @tsl
  5687. * @function
  5688. * @param {Node|Object} [nodeOrValue={}] - The node whose context should be modified or the modified context data.
  5689. * @param {Object} [value={}] - The modified context data.
  5690. * @returns {ContextNode}
  5691. */
  5692. const context = ( nodeOrValue = null, value = {} ) => {
  5693. let node = nodeOrValue;
  5694. if ( node === null || node.isNode !== true ) {
  5695. value = node || value;
  5696. node = null;
  5697. }
  5698. return new ContextNode( node, value );
  5699. };
  5700. /**
  5701. * TSL function for defining a uniformFlow context value for a given node.
  5702. *
  5703. * @tsl
  5704. * @function
  5705. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5706. * @returns {ContextNode}
  5707. */
  5708. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5709. /**
  5710. * TSL function for defining a name for the context value for a given node.
  5711. *
  5712. * @tsl
  5713. * @function
  5714. * @param {Node} node - The node whose context should be modified.
  5715. * @param {string} name - The name to set.
  5716. * @returns {ContextNode}
  5717. */
  5718. const setName = ( node, name ) => context( node, { nodeName: name } );
  5719. /**
  5720. * TSL function for defining a built-in shadow context for a given node.
  5721. *
  5722. * @tsl
  5723. * @function
  5724. * @param {ShadowNode} shadowNode - The shadow node representing the light's shadow.
  5725. * @param {Light} light - The light associated with the shadow.
  5726. * @param {Node} [node=null] - The node whose context should be modified.
  5727. * @returns {ContextNode}
  5728. */
  5729. function builtinShadowContext( shadowNode, light, node = null ) {
  5730. return context( node, {
  5731. getShadow: ( { light: shadowLight, shadowColorNode } ) => {
  5732. if ( light === shadowLight ) {
  5733. return shadowColorNode.mul( shadowNode );
  5734. }
  5735. return shadowColorNode;
  5736. }
  5737. } );
  5738. }
  5739. /**
  5740. * TSL function for defining a built-in ambient occlusion context for a given node.
  5741. *
  5742. * @tsl
  5743. * @function
  5744. * @param {Node} aoNode - The ambient occlusion value node to apply.
  5745. * @param {Node} [node=null] - The node whose context should be modified.
  5746. * @returns {ContextNode}
  5747. */
  5748. function builtinAOContext( aoNode, node = null ) {
  5749. return context( node, {
  5750. getAO: ( inputNode, { material } ) => {
  5751. if ( material.transparent === true ) return inputNode;
  5752. return inputNode !== null ? inputNode.mul( aoNode ) : aoNode;
  5753. }
  5754. } );
  5755. }
  5756. /**
  5757. * TSL function for defining a label context value for a given node.
  5758. *
  5759. * @tsl
  5760. * @function
  5761. * @deprecated
  5762. * @param {Node} node - The node whose context should be modified.
  5763. * @param {string} name - The name/label to set.
  5764. * @returns {ContextNode}
  5765. */
  5766. function label( node, name ) {
  5767. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5768. return setName( node, name );
  5769. }
  5770. addMethodChaining( 'context', context );
  5771. addMethodChaining( 'label', label );
  5772. addMethodChaining( 'uniformFlow', uniformFlow );
  5773. addMethodChaining( 'setName', setName );
  5774. addMethodChaining( 'builtinShadowContext', ( node, shadowNode, light ) => builtinShadowContext( shadowNode, light, node ) );
  5775. addMethodChaining( 'builtinAOContext', ( node, aoValue ) => builtinAOContext( aoValue, node ) );
  5776. /**
  5777. * Class for representing shader variables as nodes. Variables are created from
  5778. * existing nodes like the following:
  5779. *
  5780. * ```js
  5781. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5782. * ```
  5783. *
  5784. * @augments Node
  5785. */
  5786. class VarNode extends Node {
  5787. static get type() {
  5788. return 'VarNode';
  5789. }
  5790. /**
  5791. * Constructs a new variable node.
  5792. *
  5793. * @param {Node} node - The node for which a variable should be created.
  5794. * @param {?string} [name=null] - The name of the variable in the shader.
  5795. * @param {boolean} [readOnly=false] - The read-only flag.
  5796. */
  5797. constructor( node, name = null, readOnly = false ) {
  5798. super();
  5799. /**
  5800. * The node for which a variable should be created.
  5801. *
  5802. * @type {Node}
  5803. */
  5804. this.node = node;
  5805. /**
  5806. * The name of the variable in the shader. If no name is defined,
  5807. * the node system auto-generates one.
  5808. *
  5809. * @type {?string}
  5810. * @default null
  5811. */
  5812. this.name = name;
  5813. /**
  5814. * `VarNode` sets this property to `true` by default.
  5815. *
  5816. * @type {boolean}
  5817. * @default true
  5818. */
  5819. this.global = true;
  5820. /**
  5821. * This flag can be used for type testing.
  5822. *
  5823. * @type {boolean}
  5824. * @readonly
  5825. * @default true
  5826. */
  5827. this.isVarNode = true;
  5828. /**
  5829. *
  5830. * The read-only flag.
  5831. *
  5832. * @type {boolean}
  5833. * @default false
  5834. */
  5835. this.readOnly = readOnly;
  5836. /**
  5837. *
  5838. * Add this flag to the node system to indicate that this node require parents.
  5839. *
  5840. * @type {boolean}
  5841. * @default true
  5842. */
  5843. this.parents = true;
  5844. /**
  5845. * This flag is used to indicate that this node is used for intent.
  5846. *
  5847. * @type {boolean}
  5848. * @default false
  5849. */
  5850. this.intent = false;
  5851. }
  5852. /**
  5853. * Sets the intent flag for this node.
  5854. *
  5855. * This flag is used to indicate that this node is used for intent
  5856. * and should not be built directly. Instead, it is used to indicate that
  5857. * the node should be treated as a variable intent.
  5858. *
  5859. * It's useful for assigning variables without needing creating a new variable node.
  5860. *
  5861. * @param {boolean} value - The value to set for the intent flag.
  5862. * @returns {VarNode} This node.
  5863. */
  5864. setIntent( value ) {
  5865. this.intent = value;
  5866. return this;
  5867. }
  5868. /**
  5869. * Checks if this node is used for intent.
  5870. *
  5871. * @param {NodeBuilder} builder - The node builder.
  5872. * @returns {boolean} Whether this node is used for intent.
  5873. */
  5874. isIntent( builder ) {
  5875. const data = builder.getDataFromNode( this );
  5876. if ( data.forceDeclaration === true ) return false;
  5877. return this.intent;
  5878. }
  5879. /**
  5880. * Returns the intent flag of this node.
  5881. *
  5882. * @return {boolean} The intent flag.
  5883. */
  5884. getIntent() {
  5885. return this.intent;
  5886. }
  5887. getMemberType( builder, name ) {
  5888. return this.node.getMemberType( builder, name );
  5889. }
  5890. getElementType( builder ) {
  5891. return this.node.getElementType( builder );
  5892. }
  5893. getNodeType( builder ) {
  5894. return this.node.getNodeType( builder );
  5895. }
  5896. getArrayCount( builder ) {
  5897. return this.node.getArrayCount( builder );
  5898. }
  5899. isAssign( builder ) {
  5900. const data = builder.getDataFromNode( this );
  5901. return data.assign;
  5902. }
  5903. build( ...params ) {
  5904. const builder = params[ 0 ];
  5905. if ( this._hasStack( builder ) === false && builder.buildStage === 'setup' ) {
  5906. if ( builder.context.nodeLoop || builder.context.nodeBlock ) {
  5907. let addBefore = false;
  5908. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  5909. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  5910. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  5911. if ( shaderNodeData.hasLoop ) {
  5912. const data = builder.getDataFromNode( this );
  5913. data.forceDeclaration = true;
  5914. addBefore = true;
  5915. }
  5916. }
  5917. }
  5918. const baseStack = builder.getBaseStack();
  5919. if ( addBefore ) {
  5920. baseStack.addToStackBefore( this );
  5921. } else {
  5922. baseStack.addToStack( this );
  5923. }
  5924. }
  5925. }
  5926. if ( this.isIntent( builder ) ) {
  5927. if ( this.isAssign( builder ) !== true ) {
  5928. return this.node.build( ...params );
  5929. }
  5930. }
  5931. return super.build( ...params );
  5932. }
  5933. generate( builder ) {
  5934. const { node, name, readOnly } = this;
  5935. const { renderer } = builder;
  5936. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5937. let isDeterministic = false;
  5938. let shouldTreatAsReadOnly = false;
  5939. if ( readOnly ) {
  5940. isDeterministic = builder.isDeterministic( node );
  5941. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5942. }
  5943. const nodeType = this.getNodeType( builder );
  5944. if ( nodeType == 'void' ) {
  5945. if ( this.isIntent( builder ) !== true ) {
  5946. error( 'TSL: ".toVar()" can not be used with void type.', this.stackTrace );
  5947. }
  5948. const snippet = node.build( builder );
  5949. return snippet;
  5950. }
  5951. const vectorType = builder.getVectorType( nodeType );
  5952. const snippet = node.build( builder, vectorType );
  5953. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5954. const propertyName = builder.getPropertyName( nodeVar );
  5955. let declarationPrefix = propertyName;
  5956. if ( shouldTreatAsReadOnly ) {
  5957. if ( isWebGPUBackend ) {
  5958. declarationPrefix = isDeterministic
  5959. ? `const ${ propertyName }`
  5960. : `let ${ propertyName }`;
  5961. } else {
  5962. const count = node.getArrayCount( builder );
  5963. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5964. }
  5965. }
  5966. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5967. return propertyName;
  5968. }
  5969. _hasStack( builder ) {
  5970. const nodeData = builder.getDataFromNode( this );
  5971. return nodeData.stack !== undefined;
  5972. }
  5973. }
  5974. /**
  5975. * TSL function for creating a var node.
  5976. *
  5977. * @tsl
  5978. * @function
  5979. * @param {Node} node - The node for which a variable should be created.
  5980. * @param {?string} name - The name of the variable in the shader.
  5981. * @returns {VarNode}
  5982. */
  5983. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5984. /**
  5985. * TSL function for creating a var node.
  5986. *
  5987. * @tsl
  5988. * @function
  5989. * @param {Node} node - The node for which a variable should be created.
  5990. * @param {?string} name - The name of the variable in the shader.
  5991. * @returns {VarNode}
  5992. */
  5993. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5994. /**
  5995. * TSL function for creating a const node.
  5996. *
  5997. * @tsl
  5998. * @function
  5999. * @param {Node} node - The node for which a constant should be created.
  6000. * @param {?string} name - The name of the constant in the shader.
  6001. * @returns {VarNode}
  6002. */
  6003. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  6004. //
  6005. //
  6006. /**
  6007. * TSL function for creating a var intent node.
  6008. *
  6009. * @tsl
  6010. * @function
  6011. * @param {Node} node - The node for which a variable should be created.
  6012. * @param {?string} name - The name of the variable in the shader.
  6013. * @returns {VarNode}
  6014. */
  6015. const VarIntent = ( node ) => {
  6016. return createVar( node ).setIntent( true ).toStack();
  6017. };
  6018. // Method chaining
  6019. addMethodChaining( 'toVar', Var );
  6020. addMethodChaining( 'toConst', Const );
  6021. addMethodChaining( 'toVarIntent', VarIntent );
  6022. /**
  6023. * This node is used to build a sub-build in the node system.
  6024. *
  6025. * @augments Node
  6026. * @param {Node} node - The node to be built in the sub-build.
  6027. * @param {string} name - The name of the sub-build.
  6028. * @param {?string} [nodeType=null] - The type of the node, if known.
  6029. */
  6030. class SubBuildNode extends Node {
  6031. static get type() {
  6032. return 'SubBuild';
  6033. }
  6034. constructor( node, name, nodeType = null ) {
  6035. super( nodeType );
  6036. /**
  6037. * The node to be built in the sub-build.
  6038. *
  6039. * @type {Node}
  6040. */
  6041. this.node = node;
  6042. /**
  6043. * The name of the sub-build.
  6044. *
  6045. * @type {string}
  6046. */
  6047. this.name = name;
  6048. /**
  6049. * This flag can be used for type testing.
  6050. *
  6051. * @type {boolean}
  6052. * @readonly
  6053. * @default true
  6054. */
  6055. this.isSubBuildNode = true;
  6056. }
  6057. getNodeType( builder ) {
  6058. if ( this.nodeType !== null ) return this.nodeType;
  6059. builder.addSubBuild( this.name );
  6060. const nodeType = this.node.getNodeType( builder );
  6061. builder.removeSubBuild();
  6062. return nodeType;
  6063. }
  6064. build( builder, ...params ) {
  6065. builder.addSubBuild( this.name );
  6066. const data = this.node.build( builder, ...params );
  6067. builder.removeSubBuild();
  6068. return data;
  6069. }
  6070. }
  6071. /**
  6072. * Creates a new sub-build node.
  6073. *
  6074. * @tsl
  6075. * @function
  6076. * @param {Node} node - The node to be built in the sub-build.
  6077. * @param {string} name - The name of the sub-build.
  6078. * @param {?string} [type=null] - The type of the node, if known.
  6079. * @returns {Node} A node object wrapping the SubBuildNode instance.
  6080. */
  6081. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  6082. /**
  6083. * Class for representing shader varyings as nodes. Varyings are create from
  6084. * existing nodes like the following:
  6085. *
  6086. * ```js
  6087. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  6088. * ```
  6089. *
  6090. * @augments Node
  6091. */
  6092. class VaryingNode extends Node {
  6093. static get type() {
  6094. return 'VaryingNode';
  6095. }
  6096. /**
  6097. * Constructs a new varying node.
  6098. *
  6099. * @param {Node} node - The node for which a varying should be created.
  6100. * @param {?string} name - The name of the varying in the shader.
  6101. */
  6102. constructor( node, name = null ) {
  6103. super();
  6104. /**
  6105. * The node for which a varying should be created.
  6106. *
  6107. * @type {Node}
  6108. */
  6109. this.node = subBuild( node, 'VERTEX' );
  6110. /**
  6111. * The name of the varying in the shader. If no name is defined,
  6112. * the node system auto-generates one.
  6113. *
  6114. * @type {?string}
  6115. * @default null
  6116. */
  6117. this.name = name;
  6118. /**
  6119. * This flag can be used for type testing.
  6120. *
  6121. * @type {boolean}
  6122. * @readonly
  6123. * @default true
  6124. */
  6125. this.isVaryingNode = true;
  6126. /**
  6127. * The interpolation type of the varying data.
  6128. *
  6129. * @type {?string}
  6130. * @default null
  6131. */
  6132. this.interpolationType = null;
  6133. /**
  6134. * The interpolation sampling type of varying data.
  6135. *
  6136. * @type {?string}
  6137. * @default null
  6138. */
  6139. this.interpolationSampling = null;
  6140. /**
  6141. * This flag is used for global cache.
  6142. *
  6143. * @type {boolean}
  6144. * @default true
  6145. */
  6146. this.global = true;
  6147. }
  6148. /**
  6149. * Defines the interpolation type of the varying.
  6150. *
  6151. * @param {string} type - The interpolation type.
  6152. * @param {?string} sampling - The interpolation sampling type
  6153. * @return {VaryingNode} A reference to this node.
  6154. */
  6155. setInterpolation( type, sampling = null ) {
  6156. this.interpolationType = type;
  6157. this.interpolationSampling = sampling;
  6158. return this;
  6159. }
  6160. getHash( builder ) {
  6161. return this.name || super.getHash( builder );
  6162. }
  6163. getNodeType( builder ) {
  6164. // VaryingNode is auto type
  6165. return this.node.getNodeType( builder );
  6166. }
  6167. /**
  6168. * This method performs the setup of a varying node with the current node builder.
  6169. *
  6170. * @param {NodeBuilder} builder - The current node builder.
  6171. * @return {NodeVarying} The node varying from the node builder.
  6172. */
  6173. setupVarying( builder ) {
  6174. const properties = builder.getNodeProperties( this );
  6175. let varying = properties.varying;
  6176. if ( varying === undefined ) {
  6177. const name = this.name;
  6178. const type = this.getNodeType( builder );
  6179. const interpolationType = this.interpolationType;
  6180. const interpolationSampling = this.interpolationSampling;
  6181. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  6182. properties.node = subBuild( this.node, 'VERTEX' );
  6183. }
  6184. // this property can be used to check if the varying can be optimized for a variable
  6185. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  6186. return varying;
  6187. }
  6188. setup( builder ) {
  6189. this.setupVarying( builder );
  6190. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6191. }
  6192. analyze( builder ) {
  6193. this.setupVarying( builder );
  6194. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6195. }
  6196. generate( builder ) {
  6197. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  6198. const properties = builder.getNodeProperties( this );
  6199. const varying = this.setupVarying( builder );
  6200. if ( properties[ propertyKey ] === undefined ) {
  6201. const type = this.getNodeType( builder );
  6202. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  6203. // force node run in vertex stage
  6204. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  6205. properties[ propertyKey ] = propertyName;
  6206. }
  6207. return builder.getPropertyName( varying );
  6208. }
  6209. }
  6210. /**
  6211. * TSL function for creating a varying node.
  6212. *
  6213. * @tsl
  6214. * @function
  6215. * @param {Node} node - The node for which a varying should be created.
  6216. * @param {?string} name - The name of the varying in the shader.
  6217. * @returns {VaryingNode}
  6218. */
  6219. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6220. /**
  6221. * Computes a node in the vertex stage.
  6222. *
  6223. * @tsl
  6224. * @function
  6225. * @param {Node} node - The node which should be executed in the vertex stage.
  6226. * @returns {VaryingNode}
  6227. */
  6228. const vertexStage = ( node ) => varying( node );
  6229. addMethodChaining( 'toVarying', varying );
  6230. addMethodChaining( 'toVertexStage', vertexStage );
  6231. /**
  6232. * Converts the given color value from sRGB to linear-sRGB color space.
  6233. *
  6234. * @tsl
  6235. * @function
  6236. * @param {Node<vec3>} color - The sRGB color.
  6237. * @return {Node<vec3>} The linear-sRGB color.
  6238. */
  6239. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6240. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6241. const b = color.mul( 0.0773993808 );
  6242. const factor = color.lessThanEqual( 0.04045 );
  6243. const rgbResult = mix( a, b, factor );
  6244. return rgbResult;
  6245. } ).setLayout( {
  6246. name: 'sRGBTransferEOTF',
  6247. type: 'vec3',
  6248. inputs: [
  6249. { name: 'color', type: 'vec3' }
  6250. ]
  6251. } );
  6252. /**
  6253. * Converts the given color value from linear-sRGB to sRGB color space.
  6254. *
  6255. * @tsl
  6256. * @function
  6257. * @param {Node<vec3>} color - The linear-sRGB color.
  6258. * @return {Node<vec3>} The sRGB color.
  6259. */
  6260. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6261. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6262. const b = color.mul( 12.92 );
  6263. const factor = color.lessThanEqual( 0.0031308 );
  6264. const rgbResult = mix( a, b, factor );
  6265. return rgbResult;
  6266. } ).setLayout( {
  6267. name: 'sRGBTransferOETF',
  6268. type: 'vec3',
  6269. inputs: [
  6270. { name: 'color', type: 'vec3' }
  6271. ]
  6272. } );
  6273. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6274. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6275. /**
  6276. * This node represents a color space conversion. Meaning it converts
  6277. * a color value from a source to a target color space.
  6278. *
  6279. * @augments TempNode
  6280. */
  6281. class ColorSpaceNode extends TempNode {
  6282. static get type() {
  6283. return 'ColorSpaceNode';
  6284. }
  6285. /**
  6286. * Constructs a new color space node.
  6287. *
  6288. * @param {Node} colorNode - Represents the color to convert.
  6289. * @param {string} source - The source color space.
  6290. * @param {string} target - The target color space.
  6291. */
  6292. constructor( colorNode, source, target ) {
  6293. super( 'vec4' );
  6294. /**
  6295. * Represents the color to convert.
  6296. *
  6297. * @type {Node}
  6298. */
  6299. this.colorNode = colorNode;
  6300. /**
  6301. * The source color space.
  6302. *
  6303. * @type {string}
  6304. */
  6305. this.source = source;
  6306. /**
  6307. * The target color space.
  6308. *
  6309. * @type {string}
  6310. */
  6311. this.target = target;
  6312. }
  6313. /**
  6314. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6315. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6316. * color management and renderer.
  6317. *
  6318. * @param {NodeBuilder} builder - The current node builder.
  6319. * @param {string} colorSpace - The color space to resolve.
  6320. * @return {string} The resolved color space.
  6321. */
  6322. resolveColorSpace( builder, colorSpace ) {
  6323. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6324. return ColorManagement.workingColorSpace;
  6325. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6326. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6327. }
  6328. return colorSpace;
  6329. }
  6330. setup( builder ) {
  6331. const { colorNode } = this;
  6332. const source = this.resolveColorSpace( builder, this.source );
  6333. const target = this.resolveColorSpace( builder, this.target );
  6334. let outputNode = colorNode;
  6335. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6336. return outputNode;
  6337. }
  6338. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6339. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6340. }
  6341. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6342. outputNode = vec4(
  6343. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6344. outputNode.a
  6345. );
  6346. }
  6347. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6348. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6349. }
  6350. return outputNode;
  6351. }
  6352. }
  6353. /**
  6354. * TSL function for converting a given color node from the current working color space to the given color space.
  6355. *
  6356. * @tsl
  6357. * @function
  6358. * @param {Node} node - Represents the node to convert.
  6359. * @param {string} targetColorSpace - The target color space.
  6360. * @returns {ColorSpaceNode}
  6361. */
  6362. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6363. /**
  6364. * TSL function for converting a given color node from the given color space to the current working color space.
  6365. *
  6366. * @tsl
  6367. * @function
  6368. * @param {Node} node - Represents the node to convert.
  6369. * @param {string} sourceColorSpace - The source color space.
  6370. * @returns {ColorSpaceNode}
  6371. */
  6372. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6373. /**
  6374. * TSL function for converting a given color node from one color space to another one.
  6375. *
  6376. * @tsl
  6377. * @function
  6378. * @param {Node} node - Represents the node to convert.
  6379. * @param {string} sourceColorSpace - The source color space.
  6380. * @param {string} targetColorSpace - The target color space.
  6381. * @returns {ColorSpaceNode}
  6382. */
  6383. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6384. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6385. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6386. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  6387. /**
  6388. * This class is only relevant if the referenced property is array-like.
  6389. * In this case, `ReferenceElementNode` allows to refer to a specific
  6390. * element inside the data structure via an index.
  6391. *
  6392. * @augments ArrayElementNode
  6393. */
  6394. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6395. static get type() {
  6396. return 'ReferenceElementNode';
  6397. }
  6398. /**
  6399. * Constructs a new reference element node.
  6400. *
  6401. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6402. * @param {Node} indexNode - The index node that defines the element access.
  6403. */
  6404. constructor( referenceNode, indexNode ) {
  6405. super( referenceNode, indexNode );
  6406. /**
  6407. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6408. * property references to the current node.
  6409. *
  6410. * @type {?ReferenceBaseNode}
  6411. * @default null
  6412. */
  6413. this.referenceNode = referenceNode;
  6414. /**
  6415. * This flag can be used for type testing.
  6416. *
  6417. * @type {boolean}
  6418. * @readonly
  6419. * @default true
  6420. */
  6421. this.isReferenceElementNode = true;
  6422. }
  6423. /**
  6424. * This method is overwritten since the node type is inferred from
  6425. * the uniform type of the reference node.
  6426. *
  6427. * @return {string} The node type.
  6428. */
  6429. getNodeType() {
  6430. return this.referenceNode.uniformType;
  6431. }
  6432. generate( builder ) {
  6433. const snippet = super.generate( builder );
  6434. const arrayType = this.referenceNode.getNodeType();
  6435. const elementType = this.getNodeType();
  6436. return builder.format( snippet, arrayType, elementType );
  6437. }
  6438. };
  6439. /**
  6440. * Base class for nodes which establishes a reference to a property of another object.
  6441. * In this way, the value of the node is automatically linked to the value of
  6442. * referenced object. Reference nodes internally represent the linked value
  6443. * as a uniform.
  6444. *
  6445. * @augments Node
  6446. */
  6447. class ReferenceBaseNode extends Node {
  6448. static get type() {
  6449. return 'ReferenceBaseNode';
  6450. }
  6451. /**
  6452. * Constructs a new reference base node.
  6453. *
  6454. * @param {string} property - The name of the property the node refers to.
  6455. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6456. * @param {?Object} [object=null] - The object the property belongs to.
  6457. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6458. */
  6459. constructor( property, uniformType, object = null, count = null ) {
  6460. super();
  6461. /**
  6462. * The name of the property the node refers to.
  6463. *
  6464. * @type {string}
  6465. */
  6466. this.property = property;
  6467. /**
  6468. * The uniform type that should be used to represent the property value.
  6469. *
  6470. * @type {string}
  6471. */
  6472. this.uniformType = uniformType;
  6473. /**
  6474. * The object the property belongs to.
  6475. *
  6476. * @type {?Object}
  6477. * @default null
  6478. */
  6479. this.object = object;
  6480. /**
  6481. * When the linked property is an array, this parameter defines its length.
  6482. *
  6483. * @type {?number}
  6484. * @default null
  6485. */
  6486. this.count = count;
  6487. /**
  6488. * The property name might have dots so nested properties can be referred.
  6489. * The hierarchy of the names is stored inside this array.
  6490. *
  6491. * @type {Array<string>}
  6492. */
  6493. this.properties = property.split( '.' );
  6494. /**
  6495. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6496. * since the final reference might be updated from calling code.
  6497. *
  6498. * @type {?Object}
  6499. * @default null
  6500. */
  6501. this.reference = object;
  6502. /**
  6503. * The uniform node that holds the value of the reference node.
  6504. *
  6505. * @type {UniformNode}
  6506. * @default null
  6507. */
  6508. this.node = null;
  6509. /**
  6510. * The uniform group of the internal uniform.
  6511. *
  6512. * @type {UniformGroupNode}
  6513. * @default null
  6514. */
  6515. this.group = null;
  6516. /**
  6517. * Overwritten since reference nodes are updated per object.
  6518. *
  6519. * @type {string}
  6520. * @default 'object'
  6521. */
  6522. this.updateType = NodeUpdateType.OBJECT;
  6523. }
  6524. /**
  6525. * Sets the uniform group for this reference node.
  6526. *
  6527. * @param {UniformGroupNode} group - The uniform group to set.
  6528. * @return {ReferenceBaseNode} A reference to this node.
  6529. */
  6530. setGroup( group ) {
  6531. this.group = group;
  6532. return this;
  6533. }
  6534. /**
  6535. * When the referred property is array-like, this method can be used
  6536. * to access elements via an index node.
  6537. *
  6538. * @param {IndexNode} indexNode - indexNode.
  6539. * @return {ReferenceElementNode} A reference to an element.
  6540. */
  6541. element( indexNode ) {
  6542. return new ReferenceElementNode$1( this, nodeObject( indexNode ) );
  6543. }
  6544. /**
  6545. * Sets the node type which automatically defines the internal
  6546. * uniform type.
  6547. *
  6548. * @param {string} uniformType - The type to set.
  6549. */
  6550. setNodeType( uniformType ) {
  6551. const node = uniform( null, uniformType );
  6552. if ( this.group !== null ) {
  6553. node.setGroup( this.group );
  6554. }
  6555. this.node = node;
  6556. }
  6557. /**
  6558. * This method is overwritten since the node type is inferred from
  6559. * the type of the reference node.
  6560. *
  6561. * @param {NodeBuilder} builder - The current node builder.
  6562. * @return {string} The node type.
  6563. */
  6564. getNodeType( builder ) {
  6565. if ( this.node === null ) {
  6566. this.updateReference( builder );
  6567. this.updateValue();
  6568. }
  6569. return this.node.getNodeType( builder );
  6570. }
  6571. /**
  6572. * Returns the property value from the given referred object.
  6573. *
  6574. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6575. * @return {any} The value.
  6576. */
  6577. getValueFromReference( object = this.reference ) {
  6578. const { properties } = this;
  6579. let value = object[ properties[ 0 ] ];
  6580. for ( let i = 1; i < properties.length; i ++ ) {
  6581. value = value[ properties[ i ] ];
  6582. }
  6583. return value;
  6584. }
  6585. /**
  6586. * Allows to update the reference based on the given state. The state is only
  6587. * evaluated {@link ReferenceBaseNode#object} is not set.
  6588. *
  6589. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6590. * @return {Object} The updated reference.
  6591. */
  6592. updateReference( state ) {
  6593. this.reference = this.object !== null ? this.object : state.object;
  6594. return this.reference;
  6595. }
  6596. /**
  6597. * The output of the reference node is the internal uniform node.
  6598. *
  6599. * @return {UniformNode} The output node.
  6600. */
  6601. setup() {
  6602. this.updateValue();
  6603. return this.node;
  6604. }
  6605. /**
  6606. * Overwritten to update the internal uniform value.
  6607. *
  6608. * @param {NodeFrame} frame - A reference to the current node frame.
  6609. */
  6610. update( /*frame*/ ) {
  6611. this.updateValue();
  6612. }
  6613. /**
  6614. * Retrieves the value from the referred object property and uses it
  6615. * to updated the internal uniform.
  6616. */
  6617. updateValue() {
  6618. if ( this.node === null ) this.setNodeType( this.uniformType );
  6619. const value = this.getValueFromReference();
  6620. if ( Array.isArray( value ) ) {
  6621. this.node.array = value;
  6622. } else {
  6623. this.node.value = value;
  6624. }
  6625. }
  6626. }
  6627. /**
  6628. * TSL function for creating a reference base node.
  6629. *
  6630. * @tsl
  6631. * @function
  6632. * @param {string} name - The name of the property the node refers to.
  6633. * @param {string} type - The uniform type that should be used to represent the property value.
  6634. * @param {Object} object - The object the property belongs to.
  6635. * @returns {ReferenceBaseNode}
  6636. */
  6637. const reference$1 = ( name, type, object ) => new ReferenceBaseNode( name, type, object );
  6638. /**
  6639. * This node is a special type of reference node which is intended
  6640. * for linking renderer properties with node values.
  6641. * ```js
  6642. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6643. * ```
  6644. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6645. * automatically be updated.
  6646. *
  6647. * @augments ReferenceBaseNode
  6648. */
  6649. class RendererReferenceNode extends ReferenceBaseNode {
  6650. static get type() {
  6651. return 'RendererReferenceNode';
  6652. }
  6653. /**
  6654. * Constructs a new renderer reference node.
  6655. *
  6656. * @param {string} property - The name of the property the node refers to.
  6657. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6658. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6659. * the node refers to the renderer of the current state.
  6660. */
  6661. constructor( property, inputType, renderer = null ) {
  6662. super( property, inputType, renderer );
  6663. /**
  6664. * The renderer the property belongs to. When no renderer is set,
  6665. * the node refers to the renderer of the current state.
  6666. *
  6667. * @type {?Renderer}
  6668. * @default null
  6669. */
  6670. this.renderer = renderer;
  6671. this.setGroup( renderGroup );
  6672. }
  6673. /**
  6674. * Updates the reference based on the given state. The state is only evaluated
  6675. * {@link RendererReferenceNode#renderer} is not set.
  6676. *
  6677. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6678. * @return {Object} The updated reference.
  6679. */
  6680. updateReference( state ) {
  6681. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6682. return this.reference;
  6683. }
  6684. }
  6685. /**
  6686. * TSL function for creating a renderer reference node.
  6687. *
  6688. * @tsl
  6689. * @function
  6690. * @param {string} name - The name of the property the node refers to.
  6691. * @param {string} type - The uniform type that should be used to represent the property value.
  6692. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6693. * the node refers to the renderer of the current state.
  6694. * @returns {RendererReferenceNode}
  6695. */
  6696. const rendererReference = ( name, type, renderer = null ) => new RendererReferenceNode( name, type, renderer );
  6697. /**
  6698. * This node represents a tone mapping operation.
  6699. *
  6700. * @augments TempNode
  6701. */
  6702. class ToneMappingNode extends TempNode {
  6703. static get type() {
  6704. return 'ToneMappingNode';
  6705. }
  6706. /**
  6707. * Constructs a new tone mapping node.
  6708. *
  6709. * @param {number} toneMapping - The tone mapping type.
  6710. * @param {Node} exposureNode - The tone mapping exposure.
  6711. * @param {Node} [colorNode=null] - The color node to process.
  6712. */
  6713. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6714. super( 'vec3' );
  6715. /**
  6716. * The tone mapping type.
  6717. *
  6718. * @private
  6719. * @type {number}
  6720. */
  6721. this._toneMapping = toneMapping;
  6722. /**
  6723. * The tone mapping exposure.
  6724. *
  6725. * @type {Node}
  6726. * @default null
  6727. */
  6728. this.exposureNode = exposureNode;
  6729. /**
  6730. * Represents the color to process.
  6731. *
  6732. * @type {?Node}
  6733. * @default null
  6734. */
  6735. this.colorNode = colorNode;
  6736. }
  6737. /**
  6738. * Overwrites the default `customCacheKey()` implementation by including the tone
  6739. * mapping type into the cache key.
  6740. *
  6741. * @return {number} The hash.
  6742. */
  6743. customCacheKey() {
  6744. return hash$1( this._toneMapping );
  6745. }
  6746. /**
  6747. * Sets the tone mapping type.
  6748. *
  6749. * @param {number} value - The tone mapping type.
  6750. * @return {ToneMappingNode} A reference to this node.
  6751. */
  6752. setToneMapping( value ) {
  6753. this._toneMapping = value;
  6754. return this;
  6755. }
  6756. /**
  6757. * Gets the tone mapping type.
  6758. *
  6759. * @returns {number} The tone mapping type.
  6760. */
  6761. getToneMapping() {
  6762. return this._toneMapping;
  6763. }
  6764. setup( builder ) {
  6765. const colorNode = this.colorNode || builder.context.color;
  6766. const toneMapping = this._toneMapping;
  6767. if ( toneMapping === NoToneMapping ) return colorNode;
  6768. let outputNode = null;
  6769. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6770. if ( toneMappingFn !== null ) {
  6771. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6772. } else {
  6773. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6774. outputNode = colorNode;
  6775. }
  6776. return outputNode;
  6777. }
  6778. }
  6779. /**
  6780. * TSL function for creating a tone mapping node.
  6781. *
  6782. * @tsl
  6783. * @function
  6784. * @param {number} mapping - The tone mapping type.
  6785. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6786. * @param {Node<vec3> | Color} color - The color node to process.
  6787. * @returns {ToneMappingNode<vec3>}
  6788. */
  6789. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6790. /**
  6791. * TSL object that represents the global tone mapping exposure of the renderer.
  6792. *
  6793. * @tsl
  6794. * @type {RendererReferenceNode<vec3>}
  6795. */
  6796. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6797. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6798. /**
  6799. * Internal buffer attribute library.
  6800. *
  6801. * @private
  6802. * @type {WeakMap<TypedArray, InterleavedBuffer>}
  6803. */
  6804. const _bufferLib = new WeakMap();
  6805. /**
  6806. * Internal method for retrieving or creating interleaved buffers.
  6807. *
  6808. * @private
  6809. * @param {TypedArray} value - The attribute data.
  6810. * @param {number} itemSize - The attribute item size.
  6811. * @returns {InterleavedBuffer} The interleaved buffer.
  6812. */
  6813. function _getBufferAttribute( value, itemSize ) {
  6814. let buffer = _bufferLib.get( value );
  6815. if ( buffer === undefined ) {
  6816. buffer = new InterleavedBuffer( value, itemSize );
  6817. _bufferLib.set( value, buffer );
  6818. }
  6819. return buffer;
  6820. }
  6821. /**
  6822. * In earlier `three.js` versions it was only possible to define attribute data
  6823. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6824. * on the node level.
  6825. * ```js
  6826. * const geometry = new THREE.PlaneGeometry();
  6827. * const positionAttribute = geometry.getAttribute( 'position' );
  6828. *
  6829. * const colors = [];
  6830. * for ( let i = 0; i < position.count; i ++ ) {
  6831. * colors.push( 1, 0, 0 );
  6832. * }
  6833. *
  6834. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6835. * ```
  6836. * This new approach is especially interesting when geometry data are generated via
  6837. * compute shaders. The below line converts a storage buffer into an attribute node.
  6838. * ```js
  6839. * material.positionNode = positionBuffer.toAttribute();
  6840. * ```
  6841. * @augments InputNode
  6842. */
  6843. class BufferAttributeNode extends InputNode {
  6844. static get type() {
  6845. return 'BufferAttributeNode';
  6846. }
  6847. /**
  6848. * Constructs a new buffer attribute node.
  6849. *
  6850. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6851. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6852. * @param {number} [bufferStride=0] - The buffer stride.
  6853. * @param {number} [bufferOffset=0] - The buffer offset.
  6854. */
  6855. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6856. super( value, bufferType );
  6857. /**
  6858. * This flag can be used for type testing.
  6859. *
  6860. * @type {boolean}
  6861. * @readonly
  6862. * @default true
  6863. */
  6864. this.isBufferNode = true;
  6865. /**
  6866. * The buffer type (e.g. `'vec3'`).
  6867. *
  6868. * @type {?string}
  6869. * @default null
  6870. */
  6871. this.bufferType = bufferType;
  6872. /**
  6873. * The buffer stride.
  6874. *
  6875. * @type {number}
  6876. * @default 0
  6877. */
  6878. this.bufferStride = bufferStride;
  6879. /**
  6880. * The buffer offset.
  6881. *
  6882. * @type {number}
  6883. * @default 0
  6884. */
  6885. this.bufferOffset = bufferOffset;
  6886. /**
  6887. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6888. * if you are planning to update the attribute data per frame.
  6889. *
  6890. * @type {number}
  6891. * @default StaticDrawUsage
  6892. */
  6893. this.usage = StaticDrawUsage;
  6894. /**
  6895. * Whether the attribute is instanced or not.
  6896. *
  6897. * @type {boolean}
  6898. * @default false
  6899. */
  6900. this.instanced = false;
  6901. /**
  6902. * A reference to the buffer attribute.
  6903. *
  6904. * @type {?BufferAttribute}
  6905. * @default null
  6906. */
  6907. this.attribute = null;
  6908. /**
  6909. * `BufferAttributeNode` sets this property to `true` by default.
  6910. *
  6911. * @type {boolean}
  6912. * @default true
  6913. */
  6914. this.global = true;
  6915. if ( value && value.isBufferAttribute === true && value.itemSize <= 4 ) {
  6916. this.attribute = value;
  6917. this.usage = value.usage;
  6918. this.instanced = value.isInstancedBufferAttribute;
  6919. }
  6920. }
  6921. /**
  6922. * This method is overwritten since the attribute data might be shared
  6923. * and thus the hash should be shared as well.
  6924. *
  6925. * @param {NodeBuilder} builder - The current node builder.
  6926. * @return {string} The hash.
  6927. */
  6928. getHash( builder ) {
  6929. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6930. let bufferData = builder.globalCache.getData( this.value );
  6931. if ( bufferData === undefined ) {
  6932. bufferData = {
  6933. node: this
  6934. };
  6935. builder.globalCache.setData( this.value, bufferData );
  6936. }
  6937. return bufferData.node.uuid;
  6938. }
  6939. return this.uuid;
  6940. }
  6941. /**
  6942. * This method is overwritten since the node type is inferred from
  6943. * the buffer attribute.
  6944. *
  6945. * @param {NodeBuilder} builder - The current node builder.
  6946. * @return {string} The node type.
  6947. */
  6948. getNodeType( builder ) {
  6949. if ( this.bufferType === null ) {
  6950. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6951. }
  6952. return this.bufferType;
  6953. }
  6954. /**
  6955. * Depending on which value was passed to the node, `setup()` behaves
  6956. * differently. If no instance of `BufferAttribute` was passed, the method
  6957. * creates an internal attribute and configures it respectively.
  6958. *
  6959. * @param {NodeBuilder} builder - The current node builder.
  6960. */
  6961. setup( builder ) {
  6962. if ( this.attribute !== null ) return;
  6963. //
  6964. const type = this.getNodeType( builder );
  6965. const itemSize = builder.getTypeLength( type );
  6966. const value = this.value;
  6967. const stride = this.bufferStride || itemSize;
  6968. const offset = this.bufferOffset;
  6969. let buffer;
  6970. if ( value.isInterleavedBuffer === true ) {
  6971. buffer = value;
  6972. } else if ( value.isBufferAttribute === true ) {
  6973. buffer = _getBufferAttribute( value.array, stride );
  6974. } else {
  6975. buffer = _getBufferAttribute( value, stride );
  6976. }
  6977. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6978. buffer.setUsage( this.usage );
  6979. this.attribute = bufferAttribute;
  6980. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6981. }
  6982. /**
  6983. * Generates the code snippet of the buffer attribute node.
  6984. *
  6985. * @param {NodeBuilder} builder - The current node builder.
  6986. * @return {string} The generated code snippet.
  6987. */
  6988. generate( builder ) {
  6989. const nodeType = this.getNodeType( builder );
  6990. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6991. const propertyName = builder.getPropertyName( nodeAttribute );
  6992. let output = null;
  6993. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6994. this.name = propertyName;
  6995. output = propertyName;
  6996. } else {
  6997. const nodeVarying = varying( this );
  6998. output = nodeVarying.build( builder, nodeType );
  6999. }
  7000. return output;
  7001. }
  7002. /**
  7003. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  7004. *
  7005. * @param {NodeBuilder} builder - The current node builder.
  7006. * @return {string} The input type.
  7007. */
  7008. getInputType( /*builder*/ ) {
  7009. return 'bufferAttribute';
  7010. }
  7011. /**
  7012. * Sets the `usage` property to the given value.
  7013. *
  7014. * @param {number} value - The usage to set.
  7015. * @return {BufferAttributeNode} A reference to this node.
  7016. */
  7017. setUsage( value ) {
  7018. this.usage = value;
  7019. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  7020. this.attribute.usage = value;
  7021. }
  7022. return this;
  7023. }
  7024. /**
  7025. * Sets the `instanced` property to the given value.
  7026. *
  7027. * @param {boolean} value - The value to set.
  7028. * @return {BufferAttributeNode} A reference to this node.
  7029. */
  7030. setInstanced( value ) {
  7031. this.instanced = value;
  7032. return this;
  7033. }
  7034. }
  7035. /**
  7036. * Internal method for creating buffer attribute nodes.
  7037. *
  7038. * @private
  7039. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7040. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7041. * @param {number} [stride=0] - The buffer stride.
  7042. * @param {number} [offset=0] - The buffer offset.
  7043. * @param {number} [usage=StaticDrawUsage] - The buffer usage.
  7044. * @param {boolean} [instanced=false] - Whether the buffer is instanced.
  7045. * @returns {BufferAttributeNode|Node} The buffer attribute node.
  7046. */
  7047. function createBufferAttribute( array, type = null, stride = 0, offset = 0, usage = StaticDrawUsage, instanced = false ) {
  7048. if ( type === 'mat3' || ( type === null && array.itemSize === 9 ) ) {
  7049. return mat3(
  7050. new BufferAttributeNode( array, 'vec3', 9, 0 ).setUsage( usage ).setInstanced( instanced ),
  7051. new BufferAttributeNode( array, 'vec3', 9, 3 ).setUsage( usage ).setInstanced( instanced ),
  7052. new BufferAttributeNode( array, 'vec3', 9, 6 ).setUsage( usage ).setInstanced( instanced )
  7053. );
  7054. } else if ( type === 'mat4' || ( type === null && array.itemSize === 16 ) ) {
  7055. return mat4(
  7056. new BufferAttributeNode( array, 'vec4', 16, 0 ).setUsage( usage ).setInstanced( instanced ),
  7057. new BufferAttributeNode( array, 'vec4', 16, 4 ).setUsage( usage ).setInstanced( instanced ),
  7058. new BufferAttributeNode( array, 'vec4', 16, 8 ).setUsage( usage ).setInstanced( instanced ),
  7059. new BufferAttributeNode( array, 'vec4', 16, 12 ).setUsage( usage ).setInstanced( instanced )
  7060. );
  7061. }
  7062. return new BufferAttributeNode( array, type, stride, offset ).setUsage( usage );
  7063. }
  7064. /**
  7065. * TSL function for creating a buffer attribute node.
  7066. *
  7067. * @tsl
  7068. * @function
  7069. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7070. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7071. * @param {number} [stride=0] - The buffer stride.
  7072. * @param {number} [offset=0] - The buffer offset.
  7073. * @returns {BufferAttributeNode|Node}
  7074. */
  7075. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset );
  7076. /**
  7077. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  7078. * Use this function if attribute data are updated per frame.
  7079. *
  7080. * @tsl
  7081. * @function
  7082. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7083. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7084. * @param {number} [stride=0] - The buffer stride.
  7085. * @param {number} [offset=0] - The buffer offset.
  7086. * @returns {BufferAttributeNode|Node}
  7087. */
  7088. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage );
  7089. /**
  7090. * TSL function for creating a buffer attribute node but with enabled instancing
  7091. *
  7092. * @tsl
  7093. * @function
  7094. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7095. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7096. * @param {number} [stride=0] - The buffer stride.
  7097. * @param {number} [offset=0] - The buffer offset.
  7098. * @returns {BufferAttributeNode|Node}
  7099. */
  7100. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, StaticDrawUsage, true );
  7101. /**
  7102. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  7103. *
  7104. * @tsl
  7105. * @function
  7106. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7107. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7108. * @param {number} [stride=0] - The buffer stride.
  7109. * @param {number} [offset=0] - The buffer offset.
  7110. * @returns {BufferAttributeNode|Node}
  7111. */
  7112. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage, true );
  7113. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  7114. /**
  7115. * TODO
  7116. *
  7117. * @augments Node
  7118. */
  7119. class ComputeNode extends Node {
  7120. static get type() {
  7121. return 'ComputeNode';
  7122. }
  7123. /**
  7124. * Constructs a new compute node.
  7125. *
  7126. * @param {Node} computeNode - TODO
  7127. * @param {Array<number>} workgroupSize - TODO.
  7128. */
  7129. constructor( computeNode, workgroupSize ) {
  7130. super( 'void' );
  7131. /**
  7132. * This flag can be used for type testing.
  7133. *
  7134. * @type {boolean}
  7135. * @readonly
  7136. * @default true
  7137. */
  7138. this.isComputeNode = true;
  7139. /**
  7140. * TODO
  7141. *
  7142. * @type {Node}
  7143. */
  7144. this.computeNode = computeNode;
  7145. /**
  7146. * TODO
  7147. *
  7148. * @type {Array<number>}
  7149. * @default [ 64 ]
  7150. */
  7151. this.workgroupSize = workgroupSize;
  7152. /**
  7153. * TODO
  7154. *
  7155. * @type {number|Array<number>}
  7156. */
  7157. this.count = null;
  7158. /**
  7159. * TODO
  7160. *
  7161. * @type {number}
  7162. */
  7163. this.version = 1;
  7164. /**
  7165. * The name or label of the uniform.
  7166. *
  7167. * @type {string}
  7168. * @default ''
  7169. */
  7170. this.name = '';
  7171. /**
  7172. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  7173. * is executed once per object by default.
  7174. *
  7175. * @type {string}
  7176. * @default 'object'
  7177. */
  7178. this.updateBeforeType = NodeUpdateType.OBJECT;
  7179. /**
  7180. * TODO
  7181. *
  7182. * @type {?Function}
  7183. */
  7184. this.onInitFunction = null;
  7185. }
  7186. /**
  7187. * TODO
  7188. *
  7189. * @param {number|Array<number>} count - Array with [ x, y, z ] values for dispatch or a single number for the count
  7190. * @return {ComputeNode}
  7191. */
  7192. setCount( count ) {
  7193. this.count = count;
  7194. return this;
  7195. }
  7196. /**
  7197. * TODO
  7198. *
  7199. * @return {number|Array<number>}
  7200. */
  7201. getCount() {
  7202. return this.count;
  7203. }
  7204. /**
  7205. * Executes the `dispose` event for this node.
  7206. */
  7207. dispose() {
  7208. this.dispatchEvent( { type: 'dispose' } );
  7209. }
  7210. /**
  7211. * Sets the {@link ComputeNode#name} property.
  7212. *
  7213. * @param {string} name - The name of the uniform.
  7214. * @return {ComputeNode} A reference to this node.
  7215. */
  7216. setName( name ) {
  7217. this.name = name;
  7218. return this;
  7219. }
  7220. /**
  7221. * Sets the {@link ComputeNode#name} property.
  7222. *
  7223. * @deprecated
  7224. * @param {string} name - The name of the uniform.
  7225. * @return {ComputeNode} A reference to this node.
  7226. */
  7227. label( name ) {
  7228. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  7229. return this.setName( name );
  7230. }
  7231. /**
  7232. * TODO
  7233. *
  7234. * @param {Function} callback - TODO.
  7235. * @return {ComputeNode} A reference to this node.
  7236. */
  7237. onInit( callback ) {
  7238. this.onInitFunction = callback;
  7239. return this;
  7240. }
  7241. /**
  7242. * The method execute the compute for this node.
  7243. *
  7244. * @param {NodeFrame} frame - A reference to the current node frame.
  7245. */
  7246. updateBefore( { renderer } ) {
  7247. renderer.compute( this );
  7248. }
  7249. setup( builder ) {
  7250. const result = this.computeNode.build( builder );
  7251. if ( result ) {
  7252. const properties = builder.getNodeProperties( this );
  7253. properties.outputComputeNode = result.outputNode;
  7254. result.outputNode = null;
  7255. }
  7256. return result;
  7257. }
  7258. generate( builder, output ) {
  7259. const { shaderStage } = builder;
  7260. if ( shaderStage === 'compute' ) {
  7261. const snippet = this.computeNode.build( builder, 'void' );
  7262. if ( snippet !== '' ) {
  7263. builder.addLineFlowCode( snippet, this );
  7264. }
  7265. } else {
  7266. const properties = builder.getNodeProperties( this );
  7267. const outputComputeNode = properties.outputComputeNode;
  7268. if ( outputComputeNode ) {
  7269. return outputComputeNode.build( builder, output );
  7270. }
  7271. }
  7272. }
  7273. }
  7274. /**
  7275. * TSL function for creating a compute kernel node.
  7276. *
  7277. * @tsl
  7278. * @function
  7279. * @param {Node} node - TODO
  7280. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7281. * @returns {AtomicFunctionNode}
  7282. */
  7283. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7284. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7285. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements', new StackTrace() );
  7286. }
  7287. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7288. const val = workgroupSize[ i ];
  7289. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7290. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer`, new StackTrace() );
  7291. }
  7292. }
  7293. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7294. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7295. //
  7296. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  7297. };
  7298. /**
  7299. * TSL function for creating a compute node.
  7300. *
  7301. * @tsl
  7302. * @function
  7303. * @param {Node} node - TODO
  7304. * @param {number|Array<number>} count - TODO.
  7305. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7306. * @returns {AtomicFunctionNode}
  7307. */
  7308. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  7309. addMethodChaining( 'compute', compute );
  7310. addMethodChaining( 'computeKernel', computeKernel );
  7311. /**
  7312. * This node can be used as a cache management component for another node.
  7313. * Caching is in general used by default in {@link NodeBuilder} but this node
  7314. * allows the usage of a shared parent cache during the build process.
  7315. *
  7316. * @augments Node
  7317. */
  7318. class IsolateNode extends Node {
  7319. static get type() {
  7320. return 'IsolateNode';
  7321. }
  7322. /**
  7323. * Constructs a new cache node.
  7324. *
  7325. * @param {Node} node - The node that should be cached.
  7326. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7327. */
  7328. constructor( node, parent = true ) {
  7329. super();
  7330. /**
  7331. * The node that should be cached.
  7332. *
  7333. * @type {Node}
  7334. */
  7335. this.node = node;
  7336. /**
  7337. * Whether this node refers to a shared parent cache or not.
  7338. *
  7339. * @type {boolean}
  7340. * @default true
  7341. */
  7342. this.parent = parent;
  7343. /**
  7344. * This flag can be used for type testing.
  7345. *
  7346. * @type {boolean}
  7347. * @readonly
  7348. * @default true
  7349. */
  7350. this.isIsolateNode = true;
  7351. }
  7352. getNodeType( builder ) {
  7353. const previousCache = builder.getCache();
  7354. const cache = builder.getCacheFromNode( this, this.parent );
  7355. builder.setCache( cache );
  7356. const nodeType = this.node.getNodeType( builder );
  7357. builder.setCache( previousCache );
  7358. return nodeType;
  7359. }
  7360. build( builder, ...params ) {
  7361. const previousCache = builder.getCache();
  7362. const cache = builder.getCacheFromNode( this, this.parent );
  7363. builder.setCache( cache );
  7364. const data = this.node.build( builder, ...params );
  7365. builder.setCache( previousCache );
  7366. return data;
  7367. }
  7368. setParent( parent ) {
  7369. this.parent = parent;
  7370. return this;
  7371. }
  7372. getParent() {
  7373. return this.parent;
  7374. }
  7375. }
  7376. /**
  7377. * TSL function for creating a cache node.
  7378. *
  7379. * @tsl
  7380. * @function
  7381. * @param {Node} node - The node that should be cached.
  7382. * @returns {IsolateNode}
  7383. */
  7384. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7385. /**
  7386. * TSL function for creating a cache node.
  7387. *
  7388. * @tsl
  7389. * @function
  7390. * @deprecated
  7391. * @param {Node} node - The node that should be cached.
  7392. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7393. * @returns {IsolateNode}
  7394. */
  7395. function cache( node, parent = true ) {
  7396. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7397. return isolate( node ).setParent( parent );
  7398. }
  7399. addMethodChaining( 'cache', cache );
  7400. addMethodChaining( 'isolate', isolate );
  7401. /**
  7402. * The class generates the code of a given node but returns another node in the output.
  7403. * This can be used to call a method or node that does not return a value, i.e.
  7404. * type `void` on an input where returning a value is required. Example:
  7405. *
  7406. * ```js
  7407. * material.colorNode = myColor.bypass( runVoidFn() )
  7408. *```
  7409. *
  7410. * @augments Node
  7411. */
  7412. class BypassNode extends Node {
  7413. static get type() {
  7414. return 'BypassNode';
  7415. }
  7416. /**
  7417. * Constructs a new bypass node.
  7418. *
  7419. * @param {Node} outputNode - The output node.
  7420. * @param {Node} callNode - The call node.
  7421. */
  7422. constructor( outputNode, callNode ) {
  7423. super();
  7424. /**
  7425. * This flag can be used for type testing.
  7426. *
  7427. * @type {boolean}
  7428. * @readonly
  7429. * @default true
  7430. */
  7431. this.isBypassNode = true;
  7432. /**
  7433. * The output node.
  7434. *
  7435. * @type {Node}
  7436. */
  7437. this.outputNode = outputNode;
  7438. /**
  7439. * The call node.
  7440. *
  7441. * @type {Node}
  7442. */
  7443. this.callNode = callNode;
  7444. }
  7445. getNodeType( builder ) {
  7446. return this.outputNode.getNodeType( builder );
  7447. }
  7448. generate( builder ) {
  7449. const snippet = this.callNode.build( builder, 'void' );
  7450. if ( snippet !== '' ) {
  7451. builder.addLineFlowCode( snippet, this );
  7452. }
  7453. return this.outputNode.build( builder );
  7454. }
  7455. }
  7456. /**
  7457. * TSL function for creating a bypass node.
  7458. *
  7459. * @tsl
  7460. * @function
  7461. * @param {Node} outputNode - The output node.
  7462. * @param {Node} callNode - The call node.
  7463. * @returns {BypassNode}
  7464. */
  7465. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7466. addMethodChaining( 'bypass', bypass );
  7467. /**
  7468. * This node allows to remap a node value from one range into another. E.g a value of
  7469. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7470. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7471. *
  7472. * @augments Node
  7473. */
  7474. class RemapNode extends Node {
  7475. static get type() {
  7476. return 'RemapNode';
  7477. }
  7478. /**
  7479. * Constructs a new remap node.
  7480. *
  7481. * @param {Node} node - The node that should be remapped.
  7482. * @param {Node} inLowNode - The source or current lower bound of the range.
  7483. * @param {Node} inHighNode - The source or current upper bound of the range.
  7484. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7485. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7486. */
  7487. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7488. super();
  7489. /**
  7490. * The node that should be remapped.
  7491. *
  7492. * @type {Node}
  7493. */
  7494. this.node = node;
  7495. /**
  7496. * The source or current lower bound of the range.
  7497. *
  7498. * @type {Node}
  7499. */
  7500. this.inLowNode = inLowNode;
  7501. /**
  7502. * The source or current upper bound of the range.
  7503. *
  7504. * @type {Node}
  7505. */
  7506. this.inHighNode = inHighNode;
  7507. /**
  7508. * The target lower bound of the range.
  7509. *
  7510. * @type {Node}
  7511. * @default float(0)
  7512. */
  7513. this.outLowNode = outLowNode;
  7514. /**
  7515. * The target upper bound of the range.
  7516. *
  7517. * @type {Node}
  7518. * @default float(1)
  7519. */
  7520. this.outHighNode = outHighNode;
  7521. /**
  7522. * Whether the node value should be clamped before
  7523. * remapping it to the target range.
  7524. *
  7525. * @type {boolean}
  7526. * @default true
  7527. */
  7528. this.doClamp = true;
  7529. }
  7530. setup() {
  7531. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7532. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7533. if ( doClamp === true ) t = t.clamp();
  7534. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7535. }
  7536. }
  7537. /**
  7538. * TSL function for creating a remap node.
  7539. *
  7540. * @tsl
  7541. * @function
  7542. * @param {Node} node - The node that should be remapped.
  7543. * @param {Node} inLowNode - The source or current lower bound of the range.
  7544. * @param {Node} inHighNode - The source or current upper bound of the range.
  7545. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7546. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7547. * @returns {RemapNode}
  7548. */
  7549. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7550. /**
  7551. * TSL function for creating a remap node, but with enabled clamping.
  7552. *
  7553. * @tsl
  7554. * @function
  7555. * @param {Node} node - The node that should be remapped.
  7556. * @param {Node} inLowNode - The source or current lower bound of the range.
  7557. * @param {Node} inHighNode - The source or current upper bound of the range.
  7558. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7559. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7560. * @returns {RemapNode}
  7561. */
  7562. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7563. addMethodChaining( 'remap', remap );
  7564. addMethodChaining( 'remapClamp', remapClamp );
  7565. /**
  7566. * This class can be used to implement basic expressions in shader code.
  7567. * Basic examples for that are `return`, `continue` or `discard` statements.
  7568. *
  7569. * @augments Node
  7570. */
  7571. class ExpressionNode extends Node {
  7572. static get type() {
  7573. return 'ExpressionNode';
  7574. }
  7575. /**
  7576. * Constructs a new expression node.
  7577. *
  7578. * @param {string} [snippet=''] - The native code snippet.
  7579. * @param {string} [nodeType='void'] - The node type.
  7580. */
  7581. constructor( snippet = '', nodeType = 'void' ) {
  7582. super( nodeType );
  7583. /**
  7584. * The native code snippet.
  7585. *
  7586. * @type {string}
  7587. * @default ''
  7588. */
  7589. this.snippet = snippet;
  7590. }
  7591. generate( builder, output ) {
  7592. const type = this.getNodeType( builder );
  7593. const snippet = this.snippet;
  7594. if ( type === 'void' ) {
  7595. builder.addLineFlowCode( snippet, this );
  7596. } else {
  7597. return builder.format( snippet, type, output );
  7598. }
  7599. }
  7600. }
  7601. /**
  7602. * TSL function for creating an expression node.
  7603. *
  7604. * @tsl
  7605. * @function
  7606. * @param {string} [snippet] - The native code snippet.
  7607. * @param {?string} [nodeType='void'] - The node type.
  7608. * @returns {ExpressionNode}
  7609. */
  7610. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7611. /**
  7612. * Represents a `discard` shader operation in TSL.
  7613. *
  7614. * @tsl
  7615. * @function
  7616. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7617. * @return {Node} The `discard` expression.
  7618. */
  7619. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7620. /**
  7621. * Represents a `return` shader operation in TSL.
  7622. *
  7623. * @tsl
  7624. * @function
  7625. * @return {ExpressionNode} The `return` expression.
  7626. */
  7627. const Return = () => expression( 'return' ).toStack();
  7628. addMethodChaining( 'discard', Discard );
  7629. /**
  7630. * Normally, tone mapping and color conversion happens automatically
  7631. * before outputting pixel too the default (screen) framebuffer. In certain
  7632. * post processing setups this happens to late because certain effects
  7633. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7634. * to apply tone mapping and color space conversion at an arbitrary point
  7635. * in the effect chain.
  7636. *
  7637. * When applying tone mapping and color space conversion manually with this node,
  7638. * you have to set {@link RenderPipeline#outputColorTransform} to `false`.
  7639. *
  7640. * ```js
  7641. * const postProcessing = new RenderPipeline( renderer );
  7642. * postProcessing.outputColorTransform = false;
  7643. *
  7644. * const scenePass = pass( scene, camera );
  7645. * const outputPass = renderOutput( scenePass );
  7646. *
  7647. * postProcessing.outputNode = outputPass;
  7648. * ```
  7649. *
  7650. * @augments TempNode
  7651. */
  7652. class RenderOutputNode extends TempNode {
  7653. static get type() {
  7654. return 'RenderOutputNode';
  7655. }
  7656. /**
  7657. * Constructs a new render output node.
  7658. *
  7659. * @param {Node} colorNode - The color node to process.
  7660. * @param {?number} toneMapping - The tone mapping type.
  7661. * @param {?string} outputColorSpace - The output color space.
  7662. */
  7663. constructor( colorNode, toneMapping, outputColorSpace ) {
  7664. super( 'vec4' );
  7665. /**
  7666. * The color node to process.
  7667. *
  7668. * @type {Node}
  7669. */
  7670. this.colorNode = colorNode;
  7671. /**
  7672. * The tone mapping type.
  7673. *
  7674. * @private
  7675. * @type {?number}
  7676. */
  7677. this._toneMapping = toneMapping;
  7678. /**
  7679. * The output color space.
  7680. *
  7681. * @type {?string}
  7682. */
  7683. this.outputColorSpace = outputColorSpace;
  7684. /**
  7685. * This flag can be used for type testing.
  7686. *
  7687. * @type {boolean}
  7688. * @readonly
  7689. * @default true
  7690. */
  7691. this.isRenderOutputNode = true;
  7692. }
  7693. /**
  7694. * Sets the tone mapping type.
  7695. *
  7696. * @param {number} value - The tone mapping type.
  7697. * @return {ToneMappingNode} A reference to this node.
  7698. */
  7699. setToneMapping( value ) {
  7700. this._toneMapping = value;
  7701. return this;
  7702. }
  7703. /**
  7704. * Gets the tone mapping type.
  7705. *
  7706. * @returns {number} The tone mapping type.
  7707. */
  7708. getToneMapping() {
  7709. return this._toneMapping;
  7710. }
  7711. setup( { context } ) {
  7712. let outputNode = this.colorNode || context.color;
  7713. // tone mapping
  7714. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  7715. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7716. if ( toneMapping !== NoToneMapping ) {
  7717. outputNode = outputNode.toneMapping( toneMapping );
  7718. }
  7719. // working to output color space
  7720. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7721. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7722. }
  7723. return outputNode;
  7724. }
  7725. }
  7726. /**
  7727. * TSL function for creating a posterize node.
  7728. *
  7729. * @tsl
  7730. * @function
  7731. * @param {Node} color - The color node to process.
  7732. * @param {?number} [toneMapping=null] - The tone mapping type.
  7733. * @param {?string} [outputColorSpace=null] - The output color space.
  7734. * @returns {RenderOutputNode}
  7735. */
  7736. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7737. addMethodChaining( 'renderOutput', renderOutput );
  7738. class DebugNode extends TempNode {
  7739. static get type() {
  7740. return 'DebugNode';
  7741. }
  7742. constructor( node, callback = null ) {
  7743. super();
  7744. this.node = node;
  7745. this.callback = callback;
  7746. }
  7747. getNodeType( builder ) {
  7748. return this.node.getNodeType( builder );
  7749. }
  7750. setup( builder ) {
  7751. return this.node.build( builder );
  7752. }
  7753. analyze( builder ) {
  7754. return this.node.build( builder );
  7755. }
  7756. generate( builder ) {
  7757. const callback = this.callback;
  7758. const snippet = this.node.build( builder );
  7759. if ( callback !== null ) {
  7760. callback( builder, snippet );
  7761. } else {
  7762. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7763. const border = '-'.repeat( title.length );
  7764. let code = '';
  7765. code += '// #' + title + '#\n';
  7766. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7767. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7768. code += '// #' + border + '#\n';
  7769. log$1( code );
  7770. }
  7771. return snippet;
  7772. }
  7773. }
  7774. /**
  7775. * TSL function for creating a debug node.
  7776. *
  7777. * @tsl
  7778. * @function
  7779. * @param {Node} node - The node to debug.
  7780. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7781. * @returns {DebugNode}
  7782. */
  7783. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7784. addMethodChaining( 'debug', debug );
  7785. /**
  7786. * InspectorBase is the base class for all inspectors.
  7787. *
  7788. * @class InspectorBase
  7789. */
  7790. class InspectorBase {
  7791. /**
  7792. * Creates a new InspectorBase.
  7793. */
  7794. constructor() {
  7795. /**
  7796. * The renderer associated with this inspector.
  7797. *
  7798. * @type {WebGLRenderer}
  7799. * @private
  7800. */
  7801. this._renderer = null;
  7802. /**
  7803. * The current frame being processed.
  7804. *
  7805. * @type {Object}
  7806. */
  7807. this.currentFrame = null;
  7808. }
  7809. /**
  7810. * Returns the node frame for the current renderer.
  7811. *
  7812. * @return {Object} The node frame.
  7813. */
  7814. get nodeFrame() {
  7815. return this._renderer._nodes.nodeFrame;
  7816. }
  7817. /**
  7818. * Sets the renderer for this inspector.
  7819. *
  7820. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  7821. * @return {InspectorBase} This inspector instance.
  7822. */
  7823. setRenderer( renderer ) {
  7824. this._renderer = renderer;
  7825. return this;
  7826. }
  7827. /**
  7828. * Returns the renderer associated with this inspector.
  7829. *
  7830. * @return {WebGLRenderer} The associated renderer.
  7831. */
  7832. getRenderer() {
  7833. return this._renderer;
  7834. }
  7835. /**
  7836. * Initializes the inspector.
  7837. */
  7838. init() { }
  7839. /**
  7840. * Called when a frame begins.
  7841. */
  7842. begin() { }
  7843. /**
  7844. * Called when a frame ends.
  7845. */
  7846. finish() { }
  7847. /**
  7848. * Inspects a node.
  7849. *
  7850. * @param {Node} node - The node to inspect.
  7851. */
  7852. inspect( /*node*/ ) { }
  7853. /**
  7854. * When a compute operation is performed.
  7855. *
  7856. * @param {ComputeNode} computeNode - The compute node being executed.
  7857. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  7858. */
  7859. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  7860. /**
  7861. * Called when a compute operation begins.
  7862. *
  7863. * @param {string} uid - A unique identifier for the render context.
  7864. * @param {ComputeNode} computeNode - The compute node being executed.
  7865. */
  7866. beginCompute( /*uid, computeNode*/ ) { }
  7867. /**
  7868. * Called when a compute operation ends.
  7869. *
  7870. * @param {string} uid - A unique identifier for the render context.
  7871. * @param {ComputeNode} computeNode - The compute node being executed.
  7872. */
  7873. finishCompute( /*uid*/ ) { }
  7874. /**
  7875. * Called when a render operation begins.
  7876. *
  7877. * @param {string} uid - A unique identifier for the render context.
  7878. * @param {Scene} scene - The scene being rendered.
  7879. * @param {Camera} camera - The camera being used for rendering.
  7880. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  7881. */
  7882. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  7883. /**
  7884. * Called when an animation loop ends.
  7885. *
  7886. * @param {string} uid - A unique identifier for the render context.
  7887. */
  7888. finishRender( /*uid*/ ) { }
  7889. /**
  7890. * Called when a texture copy operation is performed.
  7891. *
  7892. * @param {Texture} srcTexture - The source texture.
  7893. * @param {Texture} dstTexture - The destination texture.
  7894. */
  7895. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  7896. /**
  7897. * Called when a framebuffer copy operation is performed.
  7898. *
  7899. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  7900. */
  7901. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  7902. }
  7903. /**
  7904. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  7905. * It can be used to debug or analyze node outputs in the rendering pipeline.
  7906. *
  7907. * @augments Node
  7908. */
  7909. class InspectorNode extends Node {
  7910. /**
  7911. * Returns the type of the node.
  7912. *
  7913. * @returns {string}
  7914. */
  7915. static get type() {
  7916. return 'InspectorNode';
  7917. }
  7918. /**
  7919. * Creates an InspectorNode.
  7920. *
  7921. * @param {Node} node - The node to inspect.
  7922. * @param {string} [name=''] - Optional name for the inspector node.
  7923. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7924. */
  7925. constructor( node, name = '', callback = null ) {
  7926. super();
  7927. this.node = node;
  7928. this.name = name;
  7929. this.callback = callback;
  7930. this.updateType = NodeUpdateType.FRAME;
  7931. this.isInspectorNode = true;
  7932. }
  7933. /**
  7934. * Returns the name of the inspector node.
  7935. *
  7936. * @returns {string}
  7937. */
  7938. getName() {
  7939. return this.name || this.node.name;
  7940. }
  7941. /**
  7942. * Updates the inspector node, allowing inspection of the wrapped node.
  7943. *
  7944. * @param {NodeFrame} frame - A reference to the current node frame.
  7945. */
  7946. update( frame ) {
  7947. frame.renderer.inspector.inspect( this );
  7948. }
  7949. /**
  7950. * Returns the type of the wrapped node.
  7951. *
  7952. * @param {NodeBuilder} builder - The node builder.
  7953. * @returns {string}
  7954. */
  7955. getNodeType( builder ) {
  7956. return this.node.getNodeType( builder );
  7957. }
  7958. /**
  7959. * Sets up the inspector node.
  7960. *
  7961. * @param {NodeBuilder} builder - The node builder.
  7962. * @returns {Node} The setup node.
  7963. */
  7964. setup( builder ) {
  7965. let node = this.node;
  7966. if ( builder.context.inspector === true && this.callback !== null ) {
  7967. node = this.callback( node );
  7968. }
  7969. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  7970. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  7971. }
  7972. return node;
  7973. }
  7974. }
  7975. /**
  7976. * Creates an inspector node to wrap around a given node for inspection purposes.
  7977. *
  7978. * @tsl
  7979. * @param {Node} node - The node to inspect.
  7980. * @param {string} [name=''] - Optional name for the inspector node.
  7981. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7982. * @returns {Node} The inspector node.
  7983. */
  7984. function inspector( node, name = '', callback = null ) {
  7985. node = nodeObject( node );
  7986. return node.before( new InspectorNode( node, name, callback ) );
  7987. }
  7988. addMethodChaining( 'toInspector', inspector );
  7989. function addNodeElement( name/*, nodeElement*/ ) {
  7990. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7991. }
  7992. /**
  7993. * Base class for representing shader attributes as nodes.
  7994. *
  7995. * @augments Node
  7996. */
  7997. class AttributeNode extends Node {
  7998. static get type() {
  7999. return 'AttributeNode';
  8000. }
  8001. /**
  8002. * Constructs a new attribute node.
  8003. *
  8004. * @param {string} attributeName - The name of the attribute.
  8005. * @param {?string} nodeType - The node type.
  8006. */
  8007. constructor( attributeName, nodeType = null ) {
  8008. super( nodeType );
  8009. /**
  8010. * `AttributeNode` sets this property to `true` by default.
  8011. *
  8012. * @type {boolean}
  8013. * @default true
  8014. */
  8015. this.global = true;
  8016. this._attributeName = attributeName;
  8017. }
  8018. getHash( builder ) {
  8019. return this.getAttributeName( builder );
  8020. }
  8021. getNodeType( builder ) {
  8022. let nodeType = this.nodeType;
  8023. if ( nodeType === null ) {
  8024. const attributeName = this.getAttributeName( builder );
  8025. if ( builder.hasGeometryAttribute( attributeName ) ) {
  8026. const attribute = builder.geometry.getAttribute( attributeName );
  8027. nodeType = builder.getTypeFromAttribute( attribute );
  8028. } else {
  8029. nodeType = 'float';
  8030. }
  8031. }
  8032. return nodeType;
  8033. }
  8034. /**
  8035. * Sets the attribute name to the given value. The method can be
  8036. * overwritten in derived classes if the final name must be computed
  8037. * analytically.
  8038. *
  8039. * @param {string} attributeName - The name of the attribute.
  8040. * @return {AttributeNode} A reference to this node.
  8041. */
  8042. setAttributeName( attributeName ) {
  8043. this._attributeName = attributeName;
  8044. return this;
  8045. }
  8046. /**
  8047. * Returns the attribute name of this node. The method can be
  8048. * overwritten in derived classes if the final name must be computed
  8049. * analytically.
  8050. *
  8051. * @param {NodeBuilder} builder - The current node builder.
  8052. * @return {string} The attribute name.
  8053. */
  8054. getAttributeName( /*builder*/ ) {
  8055. return this._attributeName;
  8056. }
  8057. generate( builder ) {
  8058. const attributeName = this.getAttributeName( builder );
  8059. const nodeType = this.getNodeType( builder );
  8060. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  8061. if ( geometryAttribute === true ) {
  8062. const attribute = builder.geometry.getAttribute( attributeName );
  8063. const attributeType = builder.getTypeFromAttribute( attribute );
  8064. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  8065. if ( builder.shaderStage === 'vertex' ) {
  8066. return builder.format( nodeAttribute.name, attributeType, nodeType );
  8067. } else {
  8068. const nodeVarying = varying( this );
  8069. return nodeVarying.build( builder, nodeType );
  8070. }
  8071. } else {
  8072. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  8073. return builder.generateConst( nodeType );
  8074. }
  8075. }
  8076. serialize( data ) {
  8077. super.serialize( data );
  8078. data.global = this.global;
  8079. data._attributeName = this._attributeName;
  8080. }
  8081. deserialize( data ) {
  8082. super.deserialize( data );
  8083. this.global = data.global;
  8084. this._attributeName = data._attributeName;
  8085. }
  8086. }
  8087. /**
  8088. * TSL function for creating an attribute node.
  8089. *
  8090. * @tsl
  8091. * @function
  8092. * @param {string} name - The name of the attribute.
  8093. * @param {?string} [nodeType=null] - The node type.
  8094. * @returns {AttributeNode}
  8095. */
  8096. const attribute = ( name, nodeType = null ) => new AttributeNode( name, nodeType );
  8097. /**
  8098. * TSL function for creating an uv attribute node with the given index.
  8099. *
  8100. * @tsl
  8101. * @function
  8102. * @param {number} [index=0] - The uv index.
  8103. * @return {AttributeNode<vec2>} The uv attribute node.
  8104. */
  8105. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  8106. /**
  8107. * A node that represents the dimensions of a texture. The texture size is
  8108. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  8109. * or `textureSize()`.
  8110. *
  8111. * @augments Node
  8112. */
  8113. class TextureSizeNode extends Node {
  8114. static get type() {
  8115. return 'TextureSizeNode';
  8116. }
  8117. /**
  8118. * Constructs a new texture size node.
  8119. *
  8120. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8121. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8122. */
  8123. constructor( textureNode, levelNode = null ) {
  8124. super( 'uvec2' );
  8125. /**
  8126. * This flag can be used for type testing.
  8127. *
  8128. * @type {boolean}
  8129. * @readonly
  8130. * @default true
  8131. */
  8132. this.isTextureSizeNode = true;
  8133. /**
  8134. * A texture node which size should be retrieved.
  8135. *
  8136. * @type {TextureNode}
  8137. */
  8138. this.textureNode = textureNode;
  8139. /**
  8140. * A level node which defines the requested mip.
  8141. *
  8142. * @type {Node<int>}
  8143. * @default null
  8144. */
  8145. this.levelNode = levelNode;
  8146. }
  8147. generate( builder, output ) {
  8148. const textureProperty = this.textureNode.build( builder, 'property' );
  8149. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  8150. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  8151. }
  8152. }
  8153. /**
  8154. * TSL function for creating a texture size node.
  8155. *
  8156. * @tsl
  8157. * @function
  8158. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8159. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8160. * @returns {TextureSizeNode}
  8161. */
  8162. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  8163. /**
  8164. * A special type of uniform node that computes the
  8165. * maximum mipmap level for a given texture node.
  8166. *
  8167. * ```js
  8168. * const level = maxMipLevel( textureNode );
  8169. * ```
  8170. *
  8171. * @augments UniformNode
  8172. */
  8173. class MaxMipLevelNode extends UniformNode {
  8174. static get type() {
  8175. return 'MaxMipLevelNode';
  8176. }
  8177. /**
  8178. * Constructs a new max mip level node.
  8179. *
  8180. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8181. */
  8182. constructor( textureNode ) {
  8183. super( 0 );
  8184. /**
  8185. * The texture node to compute the max mip level for.
  8186. *
  8187. * @private
  8188. * @type {TextureNode}
  8189. */
  8190. this._textureNode = textureNode;
  8191. /**
  8192. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  8193. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  8194. *
  8195. * @type {string}
  8196. * @default 'frame'
  8197. */
  8198. this.updateType = NodeUpdateType.FRAME;
  8199. }
  8200. /**
  8201. * The texture node to compute the max mip level for.
  8202. *
  8203. * @readonly
  8204. * @type {TextureNode}
  8205. */
  8206. get textureNode() {
  8207. return this._textureNode;
  8208. }
  8209. /**
  8210. * The texture.
  8211. *
  8212. * @readonly
  8213. * @type {Texture}
  8214. */
  8215. get texture() {
  8216. return this._textureNode.value;
  8217. }
  8218. update() {
  8219. const texture = this.texture;
  8220. const images = texture.images;
  8221. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  8222. if ( image && image.width !== undefined ) {
  8223. const { width, height } = image;
  8224. this.value = Math.log2( Math.max( width, height ) );
  8225. }
  8226. }
  8227. }
  8228. /**
  8229. * TSL function for creating a max mip level node.
  8230. *
  8231. * @tsl
  8232. * @function
  8233. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8234. * @returns {MaxMipLevelNode}
  8235. */
  8236. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  8237. /**
  8238. * Custom error class for node-related errors, including stack trace information.
  8239. */
  8240. class NodeError extends Error {
  8241. constructor( message, stackTrace = null ) {
  8242. super( message );
  8243. /**
  8244. * The name of the error.
  8245. *
  8246. * @type {string}
  8247. */
  8248. this.name = 'NodeError';
  8249. /**
  8250. * The stack trace associated with the error.
  8251. *
  8252. * @type {?StackTrace}
  8253. */
  8254. this.stackTrace = stackTrace;
  8255. }
  8256. }
  8257. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  8258. /**
  8259. * This type of uniform node represents a 2D texture.
  8260. *
  8261. * @augments UniformNode
  8262. */
  8263. class TextureNode extends UniformNode {
  8264. static get type() {
  8265. return 'TextureNode';
  8266. }
  8267. /**
  8268. * Constructs a new texture node.
  8269. *
  8270. * @param {Texture} [value=EmptyTexture] - The texture.
  8271. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8272. * @param {?Node<int>} [levelNode=null] - The level node.
  8273. * @param {?Node<float>} [biasNode=null] - The bias node.
  8274. */
  8275. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  8276. super( value );
  8277. /**
  8278. * This flag can be used for type testing.
  8279. *
  8280. * @type {boolean}
  8281. * @readonly
  8282. * @default true
  8283. */
  8284. this.isTextureNode = true;
  8285. /**
  8286. * Represents the texture coordinates.
  8287. *
  8288. * @type {?Node<vec2|vec3>}
  8289. * @default null
  8290. */
  8291. this.uvNode = uvNode;
  8292. /**
  8293. * Represents the mip level that should be selected.
  8294. *
  8295. * @type {?Node<int>}
  8296. * @default null
  8297. */
  8298. this.levelNode = levelNode;
  8299. /**
  8300. * Represents the bias to be applied during level-of-detail computation.
  8301. *
  8302. * @type {?Node<float>}
  8303. * @default null
  8304. */
  8305. this.biasNode = biasNode;
  8306. /**
  8307. * Represents a reference value a texture sample is compared to.
  8308. *
  8309. * @type {?Node<float>}
  8310. * @default null
  8311. */
  8312. this.compareNode = null;
  8313. /**
  8314. * When using texture arrays, the depth node defines the layer to select.
  8315. *
  8316. * @type {?Node<int>}
  8317. * @default null
  8318. */
  8319. this.depthNode = null;
  8320. /**
  8321. * When defined, a texture is sampled using explicit gradients.
  8322. *
  8323. * @type {?Array<Node<vec2>>}
  8324. * @default null
  8325. */
  8326. this.gradNode = null;
  8327. /**
  8328. * Represents the optional texel offset applied to the unnormalized texture
  8329. * coordinate before sampling the texture.
  8330. *
  8331. * @type {?Node<ivec2|ivec3>}
  8332. * @default null
  8333. */
  8334. this.offsetNode = null;
  8335. /**
  8336. * Whether texture values should be sampled or fetched.
  8337. *
  8338. * @type {boolean}
  8339. * @default true
  8340. */
  8341. this.sampler = true;
  8342. /**
  8343. * Whether the uv transformation matrix should be
  8344. * automatically updated or not. Use `setUpdateMatrix()`
  8345. * if you want to change the value of the property.
  8346. *
  8347. * @type {boolean}
  8348. * @default false
  8349. */
  8350. this.updateMatrix = false;
  8351. /**
  8352. * By default the `update()` method is not executed. Depending on
  8353. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8354. * is executed per object.
  8355. *
  8356. * @type {string}
  8357. * @default 'none'
  8358. */
  8359. this.updateType = NodeUpdateType.NONE;
  8360. /**
  8361. * The reference node.
  8362. *
  8363. * @type {?Node}
  8364. * @default null
  8365. */
  8366. this.referenceNode = null;
  8367. /**
  8368. * The texture value is stored in a private property.
  8369. *
  8370. * @private
  8371. * @type {Texture}
  8372. */
  8373. this._value = value;
  8374. /**
  8375. * The uniform node that represents the uv transformation matrix.
  8376. *
  8377. * @private
  8378. * @type {?UniformNode<mat3>}
  8379. * @default null
  8380. */
  8381. this._matrixUniform = null;
  8382. /**
  8383. * The uniform node that represents the y-flip. Only required for WebGL.
  8384. *
  8385. * @private
  8386. * @type {?UniformNode<bool>}
  8387. * @default null
  8388. */
  8389. this._flipYUniform = null;
  8390. this.setUpdateMatrix( uvNode === null );
  8391. }
  8392. set value( value ) {
  8393. if ( this.referenceNode ) {
  8394. this.referenceNode.value = value;
  8395. } else {
  8396. this._value = value;
  8397. }
  8398. }
  8399. /**
  8400. * The texture value.
  8401. *
  8402. * @type {Texture}
  8403. */
  8404. get value() {
  8405. return this.referenceNode ? this.referenceNode.value : this._value;
  8406. }
  8407. /**
  8408. * Overwritten since the uniform hash is defined by the texture's UUID.
  8409. *
  8410. * @param {NodeBuilder} builder - The current node builder.
  8411. * @return {string} The uniform hash.
  8412. */
  8413. getUniformHash( /*builder*/ ) {
  8414. return this.value.uuid;
  8415. }
  8416. /**
  8417. * Overwritten since the node type is inferred from the texture type.
  8418. *
  8419. * @param {NodeBuilder} builder - The current node builder.
  8420. * @return {string} The node type.
  8421. */
  8422. getNodeType( /*builder*/ ) {
  8423. if ( this.value.isDepthTexture === true ) return 'float';
  8424. if ( this.value.type === UnsignedIntType ) {
  8425. return 'uvec4';
  8426. } else if ( this.value.type === IntType ) {
  8427. return 'ivec4';
  8428. }
  8429. return 'vec4';
  8430. }
  8431. /**
  8432. * Overwrites the default implementation to return a fixed value `'texture'`.
  8433. *
  8434. * @param {NodeBuilder} builder - The current node builder.
  8435. * @return {string} The input type.
  8436. */
  8437. getInputType( /*builder*/ ) {
  8438. return 'texture';
  8439. }
  8440. /**
  8441. * Returns a default uvs based on the current texture's channel.
  8442. *
  8443. * @return {AttributeNode<vec2>} The default uvs.
  8444. */
  8445. getDefaultUV() {
  8446. return uv$1( this.value.channel );
  8447. }
  8448. /**
  8449. * Overwritten to always return the texture reference of the node.
  8450. *
  8451. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8452. * @return {Texture} The texture reference.
  8453. */
  8454. updateReference( /*state*/ ) {
  8455. return this.value;
  8456. }
  8457. /**
  8458. * Transforms the given uv node with the texture transformation matrix.
  8459. *
  8460. * @param {Node} uvNode - The uv node to transform.
  8461. * @return {Node} The transformed uv node.
  8462. */
  8463. getTransformedUV( uvNode ) {
  8464. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8465. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8466. }
  8467. /**
  8468. * Defines whether the uv transformation matrix should automatically be updated or not.
  8469. *
  8470. * @param {boolean} value - The update toggle.
  8471. * @return {TextureNode} A reference to this node.
  8472. */
  8473. setUpdateMatrix( value ) {
  8474. this.updateMatrix = value;
  8475. return this;
  8476. }
  8477. /**
  8478. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8479. * to modify the uv node for correct sampling.
  8480. *
  8481. * @param {NodeBuilder} builder - The current node builder.
  8482. * @param {Node} uvNode - The uv node to setup.
  8483. * @return {Node} The updated uv node.
  8484. */
  8485. setupUV( builder, uvNode ) {
  8486. if ( builder.isFlipY() ) {
  8487. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8488. uvNode = uvNode.toVar();
  8489. if ( this.sampler ) {
  8490. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8491. } else {
  8492. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8493. }
  8494. }
  8495. return uvNode;
  8496. }
  8497. /**
  8498. * Setups texture node by preparing the internal nodes for code generation.
  8499. *
  8500. * @param {NodeBuilder} builder - The current node builder.
  8501. */
  8502. setup( builder ) {
  8503. const properties = builder.getNodeProperties( this );
  8504. properties.referenceNode = this.referenceNode;
  8505. //
  8506. const texture = this.value;
  8507. if ( ! texture || texture.isTexture !== true ) {
  8508. throw new NodeError( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().', this.stackTrace );
  8509. }
  8510. //
  8511. const uvNode = Fn( () => {
  8512. let uvNode = this.uvNode;
  8513. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8514. uvNode = builder.context.getUV( this, builder );
  8515. }
  8516. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8517. if ( this.updateMatrix === true ) {
  8518. uvNode = this.getTransformedUV( uvNode );
  8519. }
  8520. uvNode = this.setupUV( builder, uvNode );
  8521. //
  8522. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8523. //
  8524. return uvNode;
  8525. } )();
  8526. //
  8527. let levelNode = this.levelNode;
  8528. if ( levelNode === null && builder.context.getTextureLevel ) {
  8529. levelNode = builder.context.getTextureLevel( this );
  8530. }
  8531. //
  8532. let compareNode = null;
  8533. let compareStepNode = null;
  8534. if ( this.compareNode !== null ) {
  8535. if ( builder.renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  8536. compareNode = this.compareNode;
  8537. } else {
  8538. if ( this.value.compareFunction === null || this.value.compareFunction === LessCompare ) {
  8539. compareStepNode = this.compareNode;
  8540. } else {
  8541. compareNode = this.compareNode;
  8542. warnOnce( 'TSL: Only "LessCompare" is supported for depth texture comparison fallback.' );
  8543. }
  8544. }
  8545. }
  8546. properties.uvNode = uvNode;
  8547. properties.levelNode = levelNode;
  8548. properties.biasNode = this.biasNode;
  8549. properties.compareNode = compareNode;
  8550. properties.compareStepNode = compareStepNode;
  8551. properties.gradNode = this.gradNode;
  8552. properties.depthNode = this.depthNode;
  8553. properties.offsetNode = this.offsetNode;
  8554. }
  8555. /**
  8556. * Generates the uv code snippet.
  8557. *
  8558. * @param {NodeBuilder} builder - The current node builder.
  8559. * @param {Node} uvNode - The uv node to generate code for.
  8560. * @return {string} The generated code snippet.
  8561. */
  8562. generateUV( builder, uvNode ) {
  8563. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8564. }
  8565. /**
  8566. * Generates the offset code snippet.
  8567. *
  8568. * @param {NodeBuilder} builder - The current node builder.
  8569. * @param {Node} offsetNode - The offset node to generate code for.
  8570. * @return {string} The generated code snippet.
  8571. */
  8572. generateOffset( builder, offsetNode ) {
  8573. return offsetNode.build( builder, 'ivec2' );
  8574. }
  8575. /**
  8576. * Generates the snippet for the texture sampling.
  8577. *
  8578. * @param {NodeBuilder} builder - The current node builder.
  8579. * @param {string} textureProperty - The texture property.
  8580. * @param {string} uvSnippet - The uv snippet.
  8581. * @param {?string} levelSnippet - The level snippet.
  8582. * @param {?string} biasSnippet - The bias snippet.
  8583. * @param {?string} depthSnippet - The depth snippet.
  8584. * @param {?string} compareSnippet - The compare snippet.
  8585. * @param {?Array<string>} gradSnippet - The grad snippet.
  8586. * @param {?string} offsetSnippet - The offset snippet.
  8587. * @return {string} The generated code snippet.
  8588. */
  8589. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8590. const texture = this.value;
  8591. let snippet;
  8592. if ( biasSnippet ) {
  8593. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8594. } else if ( gradSnippet ) {
  8595. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8596. } else if ( compareSnippet ) {
  8597. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8598. } else if ( this.sampler === false ) {
  8599. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8600. } else if ( levelSnippet ) {
  8601. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8602. } else {
  8603. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8604. }
  8605. return snippet;
  8606. }
  8607. /**
  8608. * Generates the code snippet of the texture node.
  8609. *
  8610. * @param {NodeBuilder} builder - The current node builder.
  8611. * @param {string} output - The current output.
  8612. * @return {string} The generated code snippet.
  8613. */
  8614. generate( builder, output ) {
  8615. const texture = this.value;
  8616. const properties = builder.getNodeProperties( this );
  8617. const textureProperty = super.generate( builder, 'property' );
  8618. if ( /^sampler/.test( output ) ) {
  8619. return textureProperty + '_sampler';
  8620. } else if ( builder.isReference( output ) ) {
  8621. return textureProperty;
  8622. } else {
  8623. const nodeData = builder.getDataFromNode( this );
  8624. const nodeType = this.getNodeType( builder );
  8625. let propertyName = nodeData.propertyName;
  8626. if ( propertyName === undefined ) {
  8627. const { uvNode, levelNode, biasNode, compareNode, compareStepNode, depthNode, gradNode, offsetNode } = properties;
  8628. const uvSnippet = this.generateUV( builder, uvNode );
  8629. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8630. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8631. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8632. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8633. const compareStepSnippet = compareStepNode ? compareStepNode.build( builder, 'float' ) : null;
  8634. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8635. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8636. const nodeVar = builder.getVarFromNode( this );
  8637. propertyName = builder.getPropertyName( nodeVar );
  8638. let snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8639. if ( compareStepSnippet !== null ) {
  8640. snippet = step( expression( compareStepSnippet, 'float' ), expression( snippet, nodeType ) ).build( builder, nodeType );
  8641. }
  8642. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8643. nodeData.snippet = snippet;
  8644. nodeData.propertyName = propertyName;
  8645. }
  8646. let snippet = propertyName;
  8647. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8648. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8649. }
  8650. return builder.format( snippet, nodeType, output );
  8651. }
  8652. }
  8653. /**
  8654. * Sets the sampler value.
  8655. *
  8656. * @param {boolean} value - The sampler value to set.
  8657. * @return {TextureNode} A reference to this texture node.
  8658. */
  8659. setSampler( value ) {
  8660. this.sampler = value;
  8661. return this;
  8662. }
  8663. /**
  8664. * Returns the sampler value.
  8665. *
  8666. * @return {boolean} The sampler value.
  8667. */
  8668. getSampler() {
  8669. return this.sampler;
  8670. }
  8671. // @TODO: Move to TSL
  8672. /**
  8673. * Samples the texture with the given uv node.
  8674. *
  8675. * @param {Node} uvNode - The uv node.
  8676. * @return {TextureNode} A texture node representing the texture sample.
  8677. */
  8678. sample( uvNode ) {
  8679. const textureNode = this.clone();
  8680. textureNode.uvNode = nodeObject( uvNode );
  8681. textureNode.referenceNode = this.getBase();
  8682. return nodeObject( textureNode );
  8683. }
  8684. /**
  8685. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8686. *
  8687. * @param {Node<uvec2>} uvNode - The uv node.
  8688. * @returns {TextureNode} A texture node representing the texture load.
  8689. */
  8690. load( uvNode ) {
  8691. return this.sample( uvNode ).setSampler( false );
  8692. }
  8693. /**
  8694. * Samples a blurred version of the texture by defining an internal bias.
  8695. *
  8696. * @param {Node<float>} amountNode - How blurred the texture should be.
  8697. * @return {TextureNode} A texture node representing the texture sample.
  8698. */
  8699. blur( amountNode ) {
  8700. const textureNode = this.clone();
  8701. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8702. textureNode.referenceNode = this.getBase();
  8703. const map = textureNode.value;
  8704. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8705. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8706. textureNode.biasNode = null;
  8707. }
  8708. return nodeObject( textureNode );
  8709. }
  8710. /**
  8711. * Samples a specific mip of the texture.
  8712. *
  8713. * @param {Node<int>} levelNode - The mip level to sample.
  8714. * @return {TextureNode} A texture node representing the texture sample.
  8715. */
  8716. level( levelNode ) {
  8717. const textureNode = this.clone();
  8718. textureNode.levelNode = nodeObject( levelNode );
  8719. textureNode.referenceNode = this.getBase();
  8720. return nodeObject( textureNode );
  8721. }
  8722. /**
  8723. * Returns the texture size of the requested level.
  8724. *
  8725. * @param {Node<int>} levelNode - The level to compute the size for.
  8726. * @return {TextureSizeNode} The texture size.
  8727. */
  8728. size( levelNode ) {
  8729. return textureSize( this, levelNode );
  8730. }
  8731. /**
  8732. * Samples the texture with the given bias.
  8733. *
  8734. * @param {Node<float>} biasNode - The bias node.
  8735. * @return {TextureNode} A texture node representing the texture sample.
  8736. */
  8737. bias( biasNode ) {
  8738. const textureNode = this.clone();
  8739. textureNode.biasNode = nodeObject( biasNode );
  8740. textureNode.referenceNode = this.getBase();
  8741. return nodeObject( textureNode );
  8742. }
  8743. /**
  8744. * Returns the base texture of this node.
  8745. * @return {TextureNode} The base texture node.
  8746. */
  8747. getBase() {
  8748. return this.referenceNode ? this.referenceNode.getBase() : this;
  8749. }
  8750. /**
  8751. * Samples the texture by executing a compare operation.
  8752. *
  8753. * @param {Node<float>} compareNode - The node that defines the compare value.
  8754. * @return {TextureNode} A texture node representing the texture sample.
  8755. */
  8756. compare( compareNode ) {
  8757. const textureNode = this.clone();
  8758. textureNode.compareNode = nodeObject( compareNode );
  8759. textureNode.referenceNode = this.getBase();
  8760. return nodeObject( textureNode );
  8761. }
  8762. /**
  8763. * Samples the texture using an explicit gradient.
  8764. *
  8765. * @param {Node<vec2>} gradNodeX - The gradX node.
  8766. * @param {Node<vec2>} gradNodeY - The gradY node.
  8767. * @return {TextureNode} A texture node representing the texture sample.
  8768. */
  8769. grad( gradNodeX, gradNodeY ) {
  8770. const textureNode = this.clone();
  8771. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8772. textureNode.referenceNode = this.getBase();
  8773. return nodeObject( textureNode );
  8774. }
  8775. /**
  8776. * Samples the texture by defining a depth node.
  8777. *
  8778. * @param {Node<int>} depthNode - The depth node.
  8779. * @return {TextureNode} A texture node representing the texture sample.
  8780. */
  8781. depth( depthNode ) {
  8782. const textureNode = this.clone();
  8783. textureNode.depthNode = nodeObject( depthNode );
  8784. textureNode.referenceNode = this.getBase();
  8785. return nodeObject( textureNode );
  8786. }
  8787. /**
  8788. * Samples the texture by defining an offset node.
  8789. *
  8790. * @param {Node<ivec2>} offsetNode - The offset node.
  8791. * @return {TextureNode} A texture node representing the texture sample.
  8792. */
  8793. offset( offsetNode ) {
  8794. const textureNode = this.clone();
  8795. textureNode.offsetNode = nodeObject( offsetNode );
  8796. textureNode.referenceNode = this.getBase();
  8797. return nodeObject( textureNode );
  8798. }
  8799. // --
  8800. serialize( data ) {
  8801. super.serialize( data );
  8802. data.value = this.value.toJSON( data.meta ).uuid;
  8803. data.sampler = this.sampler;
  8804. data.updateMatrix = this.updateMatrix;
  8805. data.updateType = this.updateType;
  8806. }
  8807. deserialize( data ) {
  8808. super.deserialize( data );
  8809. this.value = data.meta.textures[ data.value ];
  8810. this.sampler = data.sampler;
  8811. this.updateMatrix = data.updateMatrix;
  8812. this.updateType = data.updateType;
  8813. }
  8814. /**
  8815. * The update is used to implement the update of the uv transformation matrix.
  8816. */
  8817. update() {
  8818. const texture = this.value;
  8819. const matrixUniform = this._matrixUniform;
  8820. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8821. if ( texture.matrixAutoUpdate === true ) {
  8822. texture.updateMatrix();
  8823. }
  8824. //
  8825. const flipYUniform = this._flipYUniform;
  8826. if ( flipYUniform !== null ) {
  8827. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  8828. }
  8829. }
  8830. /**
  8831. * Clones the texture node.
  8832. *
  8833. * @return {TextureNode} The cloned texture node.
  8834. */
  8835. clone() {
  8836. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8837. newNode.sampler = this.sampler;
  8838. newNode.depthNode = this.depthNode;
  8839. newNode.compareNode = this.compareNode;
  8840. newNode.gradNode = this.gradNode;
  8841. newNode.offsetNode = this.offsetNode;
  8842. return newNode;
  8843. }
  8844. }
  8845. /**
  8846. * TSL function for creating a texture node.
  8847. *
  8848. * @tsl
  8849. * @function
  8850. * @param {?Texture} value - The texture.
  8851. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8852. * @param {?Node<int>} [levelNode=null] - The level node.
  8853. * @param {?Node<float>} [biasNode=null] - The bias node.
  8854. * @returns {TextureNode}
  8855. */
  8856. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8857. /**
  8858. * TSL function for creating a texture node or sample a texture node already existing.
  8859. *
  8860. * @tsl
  8861. * @function
  8862. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8863. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8864. * @param {?Node<int>} [levelNode=null] - The level node.
  8865. * @param {?Node<float>} [biasNode=null] - The bias node.
  8866. * @returns {TextureNode}
  8867. */
  8868. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8869. let textureNode;
  8870. if ( value && value.isTextureNode === true ) {
  8871. textureNode = nodeObject( value.clone() );
  8872. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8873. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8874. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8875. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8876. } else {
  8877. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8878. }
  8879. return textureNode;
  8880. };
  8881. /**
  8882. * TSL function for creating a uniform texture node.
  8883. *
  8884. * @tsl
  8885. * @function
  8886. * @param {?Texture} value - The texture.
  8887. * @returns {TextureNode}
  8888. */
  8889. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8890. /**
  8891. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8892. *
  8893. * @tsl
  8894. * @function
  8895. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8896. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8897. * @param {?Node<int>} [levelNode=null] - The level node.
  8898. * @param {?Node<float>} [biasNode=null] - The bias node.
  8899. * @returns {TextureNode}
  8900. */
  8901. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8902. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8903. /**
  8904. * Converts a texture or texture node to a sampler.
  8905. *
  8906. * @tsl
  8907. * @function
  8908. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8909. * @returns {Node}
  8910. */
  8911. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8912. /**
  8913. * Converts a texture or texture node to a sampler comparison.
  8914. *
  8915. * @tsl
  8916. * @function
  8917. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8918. * @returns {Node}
  8919. */
  8920. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8921. /**
  8922. * A special type of uniform node which represents array-like data
  8923. * as uniform buffers. The access usually happens via `element()`
  8924. * which returns an instance of {@link ArrayElementNode}. For example:
  8925. *
  8926. * ```js
  8927. * const bufferNode = buffer( array, 'mat4', count );
  8928. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8929. * ```
  8930. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8931. * since it handles more input types and automatically cares about buffer paddings.
  8932. *
  8933. * @augments UniformNode
  8934. */
  8935. class BufferNode extends UniformNode {
  8936. static get type() {
  8937. return 'BufferNode';
  8938. }
  8939. /**
  8940. * Constructs a new buffer node.
  8941. *
  8942. * @param {Array<number>} value - Array-like buffer data.
  8943. * @param {string} bufferType - The data type of the buffer.
  8944. * @param {number} [bufferCount=0] - The count of buffer elements.
  8945. */
  8946. constructor( value, bufferType, bufferCount = 0 ) {
  8947. super( value, bufferType );
  8948. /**
  8949. * This flag can be used for type testing.
  8950. *
  8951. * @type {boolean}
  8952. * @readonly
  8953. * @default true
  8954. */
  8955. this.isBufferNode = true;
  8956. /**
  8957. * The data type of the buffer.
  8958. *
  8959. * @type {string}
  8960. */
  8961. this.bufferType = bufferType;
  8962. /**
  8963. * The uniform node that holds the value of the reference node.
  8964. *
  8965. * @type {number}
  8966. * @default 0
  8967. */
  8968. this.bufferCount = bufferCount;
  8969. /**
  8970. * An array of update ranges.
  8971. *
  8972. * @type {Array<{start: number, count: number}>}
  8973. */
  8974. this.updateRanges = [];
  8975. }
  8976. /**
  8977. * Adds a range of data in the data array to be updated on the GPU.
  8978. *
  8979. * @param {number} start - Position at which to start update.
  8980. * @param {number} count - The number of components to update.
  8981. */
  8982. addUpdateRange( start, count ) {
  8983. this.updateRanges.push( { start, count } );
  8984. }
  8985. /**
  8986. * Clears the update ranges.
  8987. */
  8988. clearUpdateRanges() {
  8989. this.updateRanges.length = 0;
  8990. }
  8991. /**
  8992. * The data type of the buffer elements.
  8993. *
  8994. * @param {NodeBuilder} builder - The current node builder.
  8995. * @return {string} The element type.
  8996. */
  8997. getElementType( builder ) {
  8998. return this.getNodeType( builder );
  8999. }
  9000. /**
  9001. * Overwrites the default implementation to return a fixed value `'buffer'`.
  9002. *
  9003. * @param {NodeBuilder} builder - The current node builder.
  9004. * @return {string} The input type.
  9005. */
  9006. getInputType( /*builder*/ ) {
  9007. return 'buffer';
  9008. }
  9009. }
  9010. /**
  9011. * TSL function for creating a buffer node.
  9012. *
  9013. * @tsl
  9014. * @function
  9015. * @param {Array<number>} value - Array-like buffer data.
  9016. * @param {string} type - The data type of a buffer element.
  9017. * @param {number} count - The count of buffer elements.
  9018. * @returns {BufferNode}
  9019. */
  9020. const buffer = ( value, type, count ) => new BufferNode( value, type, count );
  9021. /**
  9022. * Represents the element access on uniform array nodes.
  9023. *
  9024. * @augments ArrayElementNode
  9025. */
  9026. class UniformArrayElementNode extends ArrayElementNode {
  9027. static get type() {
  9028. return 'UniformArrayElementNode';
  9029. }
  9030. /**
  9031. * Constructs a new buffer node.
  9032. *
  9033. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  9034. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  9035. */
  9036. constructor( uniformArrayNode, indexNode ) {
  9037. super( uniformArrayNode, indexNode );
  9038. /**
  9039. * This flag can be used for type testing.
  9040. *
  9041. * @type {boolean}
  9042. * @readonly
  9043. * @default true
  9044. */
  9045. this.isArrayBufferElementNode = true;
  9046. }
  9047. generate( builder ) {
  9048. const snippet = super.generate( builder );
  9049. const type = this.getNodeType();
  9050. const paddedType = this.node.getPaddedType();
  9051. return builder.format( snippet, paddedType, type );
  9052. }
  9053. }
  9054. /**
  9055. * Similar to {@link BufferNode} this module represents array-like data as
  9056. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  9057. * data types in the array (e.g `three.js` primitives) and automatically
  9058. * manage buffer padding. It should be the first choice when working with
  9059. * uniforms buffers.
  9060. * ```js
  9061. * const tintColors = uniformArray( [
  9062. * new Color( 1, 0, 0 ),
  9063. * new Color( 0, 1, 0 ),
  9064. * new Color( 0, 0, 1 )
  9065. * ], 'color' );
  9066. *
  9067. * const redColor = tintColors.element( 0 );
  9068. *
  9069. * @augments BufferNode
  9070. */
  9071. class UniformArrayNode extends BufferNode {
  9072. static get type() {
  9073. return 'UniformArrayNode';
  9074. }
  9075. /**
  9076. * Constructs a new uniform array node.
  9077. *
  9078. * @param {Array<any>} value - Array holding the buffer data.
  9079. * @param {?string} [elementType=null] - The data type of a buffer element.
  9080. */
  9081. constructor( value, elementType = null ) {
  9082. super( null );
  9083. /**
  9084. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  9085. * hold number primitives as well as three.js objects like vectors, matrices
  9086. * or colors.
  9087. *
  9088. * @type {Array<any>}
  9089. */
  9090. this.array = value;
  9091. /**
  9092. * The data type of an array element.
  9093. *
  9094. * @type {string}
  9095. */
  9096. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  9097. /**
  9098. * The padded type. Uniform buffers must conform to a certain buffer layout
  9099. * so a separate type is computed to ensure correct buffer size.
  9100. *
  9101. * @type {string}
  9102. */
  9103. this.paddedType = this.getPaddedType();
  9104. /**
  9105. * Overwritten since uniform array nodes are updated per render.
  9106. *
  9107. * @type {string}
  9108. * @default 'render'
  9109. */
  9110. this.updateType = NodeUpdateType.RENDER;
  9111. /**
  9112. * This flag can be used for type testing.
  9113. *
  9114. * @type {boolean}
  9115. * @readonly
  9116. * @default true
  9117. */
  9118. this.isArrayBufferNode = true;
  9119. }
  9120. /**
  9121. * This method is overwritten since the node type is inferred from the
  9122. * {@link UniformArrayNode#paddedType}.
  9123. *
  9124. * @param {NodeBuilder} builder - The current node builder.
  9125. * @return {string} The node type.
  9126. */
  9127. getNodeType( /*builder*/ ) {
  9128. return this.paddedType;
  9129. }
  9130. /**
  9131. * The data type of the array elements.
  9132. *
  9133. * @param {NodeBuilder} builder - The current node builder.
  9134. * @return {string} The element type.
  9135. */
  9136. getElementType() {
  9137. return this.elementType;
  9138. }
  9139. /**
  9140. * Returns the padded type based on the element type.
  9141. *
  9142. * @return {string} The padded type.
  9143. */
  9144. getPaddedType() {
  9145. const elementType = this.elementType;
  9146. let paddedType = 'vec4';
  9147. if ( elementType === 'mat2' ) {
  9148. paddedType = 'mat2';
  9149. } else if ( /mat/.test( elementType ) === true ) {
  9150. paddedType = 'mat4';
  9151. } else if ( elementType.charAt( 0 ) === 'i' ) {
  9152. paddedType = 'ivec4';
  9153. } else if ( elementType.charAt( 0 ) === 'u' ) {
  9154. paddedType = 'uvec4';
  9155. }
  9156. return paddedType;
  9157. }
  9158. /**
  9159. * The update makes sure to correctly transfer the data from the (complex) objects
  9160. * in the array to the internal, correctly padded value buffer.
  9161. *
  9162. * @param {NodeFrame} frame - A reference to the current node frame.
  9163. */
  9164. update( /*frame*/ ) {
  9165. const { array, value } = this;
  9166. const elementType = this.elementType;
  9167. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  9168. for ( let i = 0; i < array.length; i ++ ) {
  9169. const index = i * 4;
  9170. value[ index ] = array[ i ];
  9171. }
  9172. } else if ( elementType === 'color' ) {
  9173. for ( let i = 0; i < array.length; i ++ ) {
  9174. const index = i * 4;
  9175. const vector = array[ i ];
  9176. value[ index ] = vector.r;
  9177. value[ index + 1 ] = vector.g;
  9178. value[ index + 2 ] = vector.b || 0;
  9179. //value[ index + 3 ] = vector.a || 0;
  9180. }
  9181. } else if ( elementType === 'mat2' ) {
  9182. for ( let i = 0; i < array.length; i ++ ) {
  9183. const index = i * 4;
  9184. const matrix = array[ i ];
  9185. value[ index ] = matrix.elements[ 0 ];
  9186. value[ index + 1 ] = matrix.elements[ 1 ];
  9187. value[ index + 2 ] = matrix.elements[ 2 ];
  9188. value[ index + 3 ] = matrix.elements[ 3 ];
  9189. }
  9190. } else if ( elementType === 'mat3' ) {
  9191. for ( let i = 0; i < array.length; i ++ ) {
  9192. const index = i * 16;
  9193. const matrix = array[ i ];
  9194. value[ index ] = matrix.elements[ 0 ];
  9195. value[ index + 1 ] = matrix.elements[ 1 ];
  9196. value[ index + 2 ] = matrix.elements[ 2 ];
  9197. value[ index + 4 ] = matrix.elements[ 3 ];
  9198. value[ index + 5 ] = matrix.elements[ 4 ];
  9199. value[ index + 6 ] = matrix.elements[ 5 ];
  9200. value[ index + 8 ] = matrix.elements[ 6 ];
  9201. value[ index + 9 ] = matrix.elements[ 7 ];
  9202. value[ index + 10 ] = matrix.elements[ 8 ];
  9203. value[ index + 15 ] = 1;
  9204. }
  9205. } else if ( elementType === 'mat4' ) {
  9206. for ( let i = 0; i < array.length; i ++ ) {
  9207. const index = i * 16;
  9208. const matrix = array[ i ];
  9209. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  9210. value[ index + i ] = matrix.elements[ i ];
  9211. }
  9212. }
  9213. } else {
  9214. for ( let i = 0; i < array.length; i ++ ) {
  9215. const index = i * 4;
  9216. const vector = array[ i ];
  9217. value[ index ] = vector.x;
  9218. value[ index + 1 ] = vector.y;
  9219. value[ index + 2 ] = vector.z || 0;
  9220. value[ index + 3 ] = vector.w || 0;
  9221. }
  9222. }
  9223. }
  9224. /**
  9225. * Implement the value buffer creation based on the array data.
  9226. *
  9227. * @param {NodeBuilder} builder - A reference to the current node builder.
  9228. * @return {null}
  9229. */
  9230. setup( builder ) {
  9231. const length = this.array.length;
  9232. const elementType = this.elementType;
  9233. let arrayType = Float32Array;
  9234. const paddedType = this.paddedType;
  9235. const paddedElementLength = builder.getTypeLength( paddedType );
  9236. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  9237. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  9238. this.value = new arrayType( length * paddedElementLength );
  9239. this.bufferCount = length;
  9240. this.bufferType = paddedType;
  9241. this.update(); // initialize the buffer values
  9242. return super.setup( builder );
  9243. }
  9244. /**
  9245. * Overwrites the default `element()` method to provide element access
  9246. * based on {@link UniformArrayNode}.
  9247. *
  9248. * @param {IndexNode} indexNode - The index node.
  9249. * @return {UniformArrayElementNode}
  9250. */
  9251. element( indexNode ) {
  9252. return new UniformArrayElementNode( this, nodeObject( indexNode ) );
  9253. }
  9254. }
  9255. /**
  9256. * TSL function for creating an uniform array node.
  9257. *
  9258. * @tsl
  9259. * @function
  9260. * @param {Array<any>} values - Array-like data.
  9261. * @param {?string} [nodeType] - The data type of the array elements.
  9262. * @returns {UniformArrayNode}
  9263. */
  9264. const uniformArray = ( values, nodeType ) => new UniformArrayNode( values, nodeType );
  9265. /**
  9266. * The node allows to set values for built-in shader variables. That is
  9267. * required for features like hardware-accelerated vertex clipping.
  9268. *
  9269. * @augments Node
  9270. */
  9271. class BuiltinNode extends Node {
  9272. /**
  9273. * Constructs a new builtin node.
  9274. *
  9275. * @param {string} name - The name of the built-in shader variable.
  9276. */
  9277. constructor( name ) {
  9278. super( 'float' );
  9279. /**
  9280. * The name of the built-in shader variable.
  9281. *
  9282. * @type {string}
  9283. */
  9284. this.name = name;
  9285. /**
  9286. * This flag can be used for type testing.
  9287. *
  9288. * @type {boolean}
  9289. * @readonly
  9290. * @default true
  9291. */
  9292. this.isBuiltinNode = true;
  9293. }
  9294. /**
  9295. * Generates the code snippet of the builtin node.
  9296. *
  9297. * @param {NodeBuilder} builder - The current node builder.
  9298. * @return {string} The generated code snippet.
  9299. */
  9300. generate( /* builder */ ) {
  9301. return this.name;
  9302. }
  9303. }
  9304. /**
  9305. * TSL function for creating a builtin node.
  9306. *
  9307. * @tsl
  9308. * @function
  9309. * @param {string} name - The name of the built-in shader variable.
  9310. * @returns {BuiltinNode}
  9311. */
  9312. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  9313. let _screenSizeVec, _viewportVec;
  9314. /**
  9315. * This node provides a collection of screen related metrics.
  9316. * Depending on {@link ScreenNode#scope}, the nodes can represent
  9317. * resolution or viewport data as well as fragment or uv coordinates.
  9318. *
  9319. * @augments Node
  9320. */
  9321. class ScreenNode extends Node {
  9322. static get type() {
  9323. return 'ScreenNode';
  9324. }
  9325. /**
  9326. * Constructs a new screen node.
  9327. *
  9328. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  9329. */
  9330. constructor( scope ) {
  9331. super();
  9332. /**
  9333. * The node represents different metric depending on which scope is selected.
  9334. *
  9335. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9336. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9337. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9338. * - `ScreenNode.UV`: Normalized coordinates.
  9339. * - `ScreenNode.DPR`: Device pixel ratio.
  9340. *
  9341. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9342. */
  9343. this.scope = scope;
  9344. /**
  9345. * This output node.
  9346. *
  9347. * @private
  9348. * @type {?Node}
  9349. * @default null
  9350. */
  9351. this._output = null;
  9352. /**
  9353. * This flag can be used for type testing.
  9354. *
  9355. * @type {boolean}
  9356. * @readonly
  9357. * @default true
  9358. */
  9359. this.isViewportNode = true;
  9360. }
  9361. /**
  9362. * This method is overwritten since the node type depends on the selected scope.
  9363. *
  9364. * @return {('float'|'vec2'|'vec4')} The node type.
  9365. */
  9366. getNodeType() {
  9367. if ( this.scope === ScreenNode.DPR ) return 'float';
  9368. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9369. else return 'vec2';
  9370. }
  9371. /**
  9372. * This method is overwritten since the node's update type depends on the selected scope.
  9373. *
  9374. * @return {NodeUpdateType} The update type.
  9375. */
  9376. getUpdateType() {
  9377. let updateType = NodeUpdateType.NONE;
  9378. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9379. updateType = NodeUpdateType.RENDER;
  9380. }
  9381. this.updateType = updateType;
  9382. return updateType;
  9383. }
  9384. /**
  9385. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9386. * from the current renderer.
  9387. *
  9388. * @param {NodeFrame} frame - A reference to the current node frame.
  9389. */
  9390. update( { renderer } ) {
  9391. const renderTarget = renderer.getRenderTarget();
  9392. if ( this.scope === ScreenNode.VIEWPORT ) {
  9393. if ( renderTarget !== null ) {
  9394. _viewportVec.copy( renderTarget.viewport );
  9395. } else {
  9396. renderer.getViewport( _viewportVec );
  9397. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9398. }
  9399. } else if ( this.scope === ScreenNode.DPR ) {
  9400. this._output.value = renderer.getPixelRatio();
  9401. } else {
  9402. if ( renderTarget !== null ) {
  9403. _screenSizeVec.width = renderTarget.width;
  9404. _screenSizeVec.height = renderTarget.height;
  9405. } else {
  9406. renderer.getDrawingBufferSize( _screenSizeVec );
  9407. }
  9408. }
  9409. }
  9410. setup( /*builder*/ ) {
  9411. const scope = this.scope;
  9412. let output = null;
  9413. if ( scope === ScreenNode.SIZE ) {
  9414. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9415. } else if ( scope === ScreenNode.VIEWPORT ) {
  9416. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9417. } else if ( scope === ScreenNode.DPR ) {
  9418. output = uniform( 1 );
  9419. } else {
  9420. output = vec2( screenCoordinate.div( screenSize ) );
  9421. }
  9422. this._output = output;
  9423. return output;
  9424. }
  9425. generate( builder ) {
  9426. if ( this.scope === ScreenNode.COORDINATE ) {
  9427. let coord = builder.getFragCoord();
  9428. if ( builder.isFlipY() ) {
  9429. // follow webgpu standards
  9430. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9431. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9432. }
  9433. return coord;
  9434. }
  9435. return super.generate( builder );
  9436. }
  9437. }
  9438. ScreenNode.COORDINATE = 'coordinate';
  9439. ScreenNode.VIEWPORT = 'viewport';
  9440. ScreenNode.SIZE = 'size';
  9441. ScreenNode.UV = 'uv';
  9442. ScreenNode.DPR = 'dpr';
  9443. // Screen
  9444. /**
  9445. * TSL object that represents the current DPR.
  9446. *
  9447. * @tsl
  9448. * @type {ScreenNode<float>}
  9449. */
  9450. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9451. /**
  9452. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9453. *
  9454. * @tsl
  9455. * @type {ScreenNode<vec2>}
  9456. */
  9457. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9458. /**
  9459. * TSL object that represents the screen resolution in physical pixel units.
  9460. *
  9461. * @tsl
  9462. * @type {ScreenNode<vec2>}
  9463. */
  9464. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9465. /**
  9466. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9467. *
  9468. * @tsl
  9469. * @type {ScreenNode<vec2>}
  9470. */
  9471. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9472. // Viewport
  9473. /**
  9474. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9475. *
  9476. * @tsl
  9477. * @type {ScreenNode<vec4>}
  9478. */
  9479. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9480. /**
  9481. * TSL object that represents the viewport resolution in physical pixel units.
  9482. *
  9483. * @tsl
  9484. * @type {ScreenNode<vec2>}
  9485. */
  9486. const viewportSize = viewport.zw;
  9487. /**
  9488. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9489. *
  9490. * @tsl
  9491. * @type {ScreenNode<vec2>}
  9492. */
  9493. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9494. /**
  9495. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9496. *
  9497. * @tsl
  9498. * @type {ScreenNode<vec2>}
  9499. */
  9500. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9501. // Deprecated
  9502. /**
  9503. * @deprecated since r169. Use {@link screenSize} instead.
  9504. */
  9505. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9506. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.', new StackTrace() );
  9507. return screenSize;
  9508. }, 'vec2' ).once() )();
  9509. // Cache node uniforms
  9510. let _cameraProjectionMatrixBase = null;
  9511. let _cameraProjectionMatrixArray = null;
  9512. let _cameraProjectionMatrixInverseBase = null;
  9513. let _cameraProjectionMatrixInverseArray = null;
  9514. let _cameraViewMatrixBase = null;
  9515. let _cameraViewMatrixArray = null;
  9516. let _cameraWorldMatrixBase = null;
  9517. let _cameraWorldMatrixArray = null;
  9518. let _cameraNormalMatrixBase = null;
  9519. let _cameraNormalMatrixArray = null;
  9520. let _cameraPositionBase = null;
  9521. let _cameraPositionArray = null;
  9522. let _cameraViewportBase = null;
  9523. let _cameraViewportArray = null;
  9524. /**
  9525. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9526. *
  9527. * @tsl
  9528. * @type {UniformNode<uint>}
  9529. */
  9530. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9531. /**
  9532. * TSL object that represents the `near` value of the camera used for the current render.
  9533. *
  9534. * @tsl
  9535. * @type {UniformNode<float>}
  9536. */
  9537. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9538. /**
  9539. * TSL object that represents the `far` value of the camera used for the current render.
  9540. *
  9541. * @tsl
  9542. * @type {UniformNode<float>}
  9543. */
  9544. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9545. /**
  9546. * TSL object that represents the projection matrix of the camera used for the current render.
  9547. *
  9548. * @tsl
  9549. * @type {UniformNode<mat4>}
  9550. */
  9551. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9552. let cameraProjectionMatrix;
  9553. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9554. const matrices = [];
  9555. for ( const subCamera of camera.cameras ) {
  9556. matrices.push( subCamera.projectionMatrix );
  9557. }
  9558. if ( _cameraProjectionMatrixArray === null ) {
  9559. _cameraProjectionMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9560. } else {
  9561. _cameraProjectionMatrixArray.array = matrices;
  9562. }
  9563. cameraProjectionMatrix = _cameraProjectionMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9564. } else {
  9565. if ( _cameraProjectionMatrixBase === null ) {
  9566. _cameraProjectionMatrixBase = uniform( camera.projectionMatrix ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9567. }
  9568. cameraProjectionMatrix = _cameraProjectionMatrixBase;
  9569. }
  9570. return cameraProjectionMatrix;
  9571. } ).once() )();
  9572. /**
  9573. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9574. *
  9575. * @tsl
  9576. * @type {UniformNode<mat4>}
  9577. */
  9578. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9579. let cameraProjectionMatrixInverse;
  9580. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9581. const matrices = [];
  9582. for ( const subCamera of camera.cameras ) {
  9583. matrices.push( subCamera.projectionMatrixInverse );
  9584. }
  9585. if ( _cameraProjectionMatrixInverseArray === null ) {
  9586. _cameraProjectionMatrixInverseArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9587. } else {
  9588. _cameraProjectionMatrixInverseArray.array = matrices;
  9589. }
  9590. cameraProjectionMatrixInverse = _cameraProjectionMatrixInverseArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9591. } else {
  9592. if ( _cameraProjectionMatrixInverseBase === null ) {
  9593. _cameraProjectionMatrixInverseBase = uniform( camera.projectionMatrixInverse ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9594. }
  9595. cameraProjectionMatrixInverse = _cameraProjectionMatrixInverseBase;
  9596. }
  9597. return cameraProjectionMatrixInverse;
  9598. } ).once() )();
  9599. /**
  9600. * TSL object that represents the view matrix of the camera used for the current render.
  9601. *
  9602. * @tsl
  9603. * @type {UniformNode<mat4>}
  9604. */
  9605. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9606. let cameraViewMatrix;
  9607. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9608. const matrices = [];
  9609. for ( const subCamera of camera.cameras ) {
  9610. matrices.push( subCamera.matrixWorldInverse );
  9611. }
  9612. if ( _cameraViewMatrixArray === null ) {
  9613. _cameraViewMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9614. } else {
  9615. _cameraViewMatrixArray.array = matrices;
  9616. }
  9617. cameraViewMatrix = _cameraViewMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9618. } else {
  9619. if ( _cameraViewMatrixBase === null ) {
  9620. _cameraViewMatrixBase = uniform( camera.matrixWorldInverse ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9621. }
  9622. cameraViewMatrix = _cameraViewMatrixBase;
  9623. }
  9624. return cameraViewMatrix;
  9625. } ).once() )();
  9626. /**
  9627. * TSL object that represents the world matrix of the camera used for the current render.
  9628. *
  9629. * @tsl
  9630. * @type {UniformNode<mat4>}
  9631. */
  9632. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9633. let cameraWorldMatrix;
  9634. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9635. const matrices = [];
  9636. for ( const subCamera of camera.cameras ) {
  9637. matrices.push( subCamera.matrixWorld );
  9638. }
  9639. if ( _cameraWorldMatrixArray === null ) {
  9640. _cameraWorldMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9641. } else {
  9642. _cameraWorldMatrixArray.array = matrices;
  9643. }
  9644. cameraWorldMatrix = _cameraWorldMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9645. } else {
  9646. if ( _cameraWorldMatrixBase === null ) {
  9647. _cameraWorldMatrixBase = uniform( camera.matrixWorld ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9648. }
  9649. cameraWorldMatrix = _cameraWorldMatrixBase;
  9650. }
  9651. return cameraWorldMatrix;
  9652. } ).once() )();
  9653. /**
  9654. * TSL object that represents the normal matrix of the camera used for the current render.
  9655. *
  9656. * @tsl
  9657. * @type {UniformNode<mat3>}
  9658. */
  9659. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9660. let cameraNormalMatrix;
  9661. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9662. const matrices = [];
  9663. for ( const subCamera of camera.cameras ) {
  9664. matrices.push( subCamera.normalMatrix );
  9665. }
  9666. if ( _cameraNormalMatrixArray === null ) {
  9667. _cameraNormalMatrixArray = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9668. } else {
  9669. _cameraNormalMatrixArray.array = matrices;
  9670. }
  9671. cameraNormalMatrix = _cameraNormalMatrixArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9672. } else {
  9673. if ( _cameraNormalMatrixBase === null ) {
  9674. _cameraNormalMatrixBase = uniform( camera.normalMatrix ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9675. }
  9676. cameraNormalMatrix = _cameraNormalMatrixBase;
  9677. }
  9678. return cameraNormalMatrix;
  9679. } ).once() )();
  9680. /**
  9681. * TSL object that represents the position in world space of the camera used for the current render.
  9682. *
  9683. * @tsl
  9684. * @type {UniformNode<vec3>}
  9685. */
  9686. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9687. let cameraPosition;
  9688. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9689. const positions = [];
  9690. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9691. positions.push( new Vector3() );
  9692. }
  9693. if ( _cameraPositionArray === null ) {
  9694. _cameraPositionArray = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9695. const subCameras = camera.cameras;
  9696. const array = self.array;
  9697. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9698. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9699. }
  9700. } );
  9701. } else {
  9702. _cameraPositionArray.array = positions;
  9703. }
  9704. cameraPosition = _cameraPositionArray.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9705. } else {
  9706. if ( _cameraPositionBase === null ) {
  9707. _cameraPositionBase = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9708. }
  9709. cameraPosition = _cameraPositionBase;
  9710. }
  9711. return cameraPosition;
  9712. } ).once() )();
  9713. /**
  9714. * TSL object that represents the viewport of the camera used for the current render.
  9715. *
  9716. * @tsl
  9717. * @type {UniformNode<vec4>}
  9718. */
  9719. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9720. let cameraViewport;
  9721. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9722. const viewports = [];
  9723. for ( const subCamera of camera.cameras ) {
  9724. viewports.push( subCamera.viewport );
  9725. }
  9726. if ( _cameraViewportArray === null ) {
  9727. _cameraViewportArray = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  9728. } else {
  9729. _cameraViewportArray.array = viewports;
  9730. }
  9731. cameraViewport = _cameraViewportArray.element( cameraIndex ).toConst( 'cameraViewport' );
  9732. } else {
  9733. if ( _cameraViewportBase === null ) {
  9734. // Fallback for single camera
  9735. _cameraViewportBase = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  9736. }
  9737. cameraViewport = _cameraViewportBase;
  9738. }
  9739. return cameraViewport;
  9740. } ).once() )();
  9741. const _sphere = /*@__PURE__*/ new Sphere();
  9742. /**
  9743. * This node can be used to access transformation related metrics of 3D objects.
  9744. * Depending on the selected scope, a different metric is represented as a uniform
  9745. * in the shader. The following scopes are supported:
  9746. *
  9747. * - `POSITION`: The object's position in world space.
  9748. * - `VIEW_POSITION`: The object's position in view/camera space.
  9749. * - `DIRECTION`: The object's direction in world space.
  9750. * - `SCALE`: The object's scale in world space.
  9751. * - `WORLD_MATRIX`: The object's matrix in world space.
  9752. *
  9753. * @augments Node
  9754. */
  9755. class Object3DNode extends Node {
  9756. static get type() {
  9757. return 'Object3DNode';
  9758. }
  9759. /**
  9760. * Constructs a new object 3D node.
  9761. *
  9762. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9763. * @param {?Object3D} [object3d=null] - The 3D object.
  9764. */
  9765. constructor( scope, object3d = null ) {
  9766. super();
  9767. /**
  9768. * The node reports a different type of transformation depending on the scope.
  9769. *
  9770. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9771. */
  9772. this.scope = scope;
  9773. /**
  9774. * The 3D object.
  9775. *
  9776. * @type {?Object3D}
  9777. * @default null
  9778. */
  9779. this.object3d = object3d;
  9780. /**
  9781. * Overwritten since this type of node is updated per object.
  9782. *
  9783. * @type {string}
  9784. * @default 'object'
  9785. */
  9786. this.updateType = NodeUpdateType.OBJECT;
  9787. /**
  9788. * Holds the value of the node as a uniform.
  9789. *
  9790. * @type {UniformNode}
  9791. */
  9792. this.uniformNode = new UniformNode( null );
  9793. }
  9794. /**
  9795. * Overwritten since the node type is inferred from the scope.
  9796. *
  9797. * @return {('mat4'|'vec3'|'float')} The node type.
  9798. */
  9799. getNodeType() {
  9800. const scope = this.scope;
  9801. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9802. return 'mat4';
  9803. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9804. return 'vec3';
  9805. } else if ( scope === Object3DNode.RADIUS ) {
  9806. return 'float';
  9807. }
  9808. }
  9809. /**
  9810. * Updates the uniform value depending on the scope.
  9811. *
  9812. * @param {NodeFrame} frame - The current node frame.
  9813. */
  9814. update( frame ) {
  9815. const object = this.object3d;
  9816. const uniformNode = this.uniformNode;
  9817. const scope = this.scope;
  9818. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9819. uniformNode.value = object.matrixWorld;
  9820. } else if ( scope === Object3DNode.POSITION ) {
  9821. uniformNode.value = uniformNode.value || new Vector3();
  9822. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9823. } else if ( scope === Object3DNode.SCALE ) {
  9824. uniformNode.value = uniformNode.value || new Vector3();
  9825. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9826. } else if ( scope === Object3DNode.DIRECTION ) {
  9827. uniformNode.value = uniformNode.value || new Vector3();
  9828. object.getWorldDirection( uniformNode.value );
  9829. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9830. const camera = frame.camera;
  9831. uniformNode.value = uniformNode.value || new Vector3();
  9832. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9833. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9834. } else if ( scope === Object3DNode.RADIUS ) {
  9835. const geometry = frame.object.geometry;
  9836. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9837. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9838. uniformNode.value = _sphere.radius;
  9839. }
  9840. }
  9841. /**
  9842. * Generates the code snippet of the uniform node. The node type of the uniform
  9843. * node also depends on the selected scope.
  9844. *
  9845. * @param {NodeBuilder} builder - The current node builder.
  9846. * @return {string} The generated code snippet.
  9847. */
  9848. generate( builder ) {
  9849. const scope = this.scope;
  9850. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9851. this.uniformNode.nodeType = 'mat4';
  9852. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9853. this.uniformNode.nodeType = 'vec3';
  9854. } else if ( scope === Object3DNode.RADIUS ) {
  9855. this.uniformNode.nodeType = 'float';
  9856. }
  9857. return this.uniformNode.build( builder );
  9858. }
  9859. serialize( data ) {
  9860. super.serialize( data );
  9861. data.scope = this.scope;
  9862. }
  9863. deserialize( data ) {
  9864. super.deserialize( data );
  9865. this.scope = data.scope;
  9866. }
  9867. }
  9868. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9869. Object3DNode.POSITION = 'position';
  9870. Object3DNode.SCALE = 'scale';
  9871. Object3DNode.VIEW_POSITION = 'viewPosition';
  9872. Object3DNode.DIRECTION = 'direction';
  9873. Object3DNode.RADIUS = 'radius';
  9874. /**
  9875. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9876. *
  9877. * @tsl
  9878. * @function
  9879. * @param {?Object3D} [object3d] - The 3D object.
  9880. * @returns {Object3DNode<vec3>}
  9881. */
  9882. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9883. /**
  9884. * TSL function for creating an object 3D node that represents the object's world matrix.
  9885. *
  9886. * @tsl
  9887. * @function
  9888. * @param {?Object3D} [object3d] - The 3D object.
  9889. * @returns {Object3DNode<mat4>}
  9890. */
  9891. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9892. /**
  9893. * TSL function for creating an object 3D node that represents the object's position in world space.
  9894. *
  9895. * @tsl
  9896. * @function
  9897. * @param {?Object3D} [object3d] - The 3D object.
  9898. * @returns {Object3DNode<vec3>}
  9899. */
  9900. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9901. /**
  9902. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9903. *
  9904. * @tsl
  9905. * @function
  9906. * @param {?Object3D} [object3d] - The 3D object.
  9907. * @returns {Object3DNode<vec3>}
  9908. */
  9909. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9910. /**
  9911. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9912. *
  9913. * @tsl
  9914. * @function
  9915. * @param {?Object3D} [object3d] - The 3D object.
  9916. * @returns {Object3DNode<vec3>}
  9917. */
  9918. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9919. /**
  9920. * TSL function for creating an object 3D node that represents the object's radius.
  9921. *
  9922. * @tsl
  9923. * @function
  9924. * @param {?Object3D} [object3d] - The 3D object.
  9925. * @returns {Object3DNode<float>}
  9926. */
  9927. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9928. /**
  9929. * This type of node is a specialized version of `Object3DNode`
  9930. * with larger set of model related metrics. Unlike `Object3DNode`,
  9931. * `ModelNode` extracts the reference to the 3D object from the
  9932. * current node frame state.
  9933. *
  9934. * @augments Object3DNode
  9935. */
  9936. class ModelNode extends Object3DNode {
  9937. static get type() {
  9938. return 'ModelNode';
  9939. }
  9940. /**
  9941. * Constructs a new object model node.
  9942. *
  9943. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9944. */
  9945. constructor( scope ) {
  9946. super( scope );
  9947. }
  9948. /**
  9949. * Extracts the model reference from the frame state and then
  9950. * updates the uniform value depending on the scope.
  9951. *
  9952. * @param {NodeFrame} frame - The current node frame.
  9953. */
  9954. update( frame ) {
  9955. this.object3d = frame.object;
  9956. super.update( frame );
  9957. }
  9958. }
  9959. /**
  9960. * TSL object that represents the object's direction in world space.
  9961. *
  9962. * @tsl
  9963. * @type {ModelNode<vec3>}
  9964. */
  9965. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9966. /**
  9967. * TSL object that represents the object's world matrix.
  9968. *
  9969. * @tsl
  9970. * @type {ModelNode<mat4>}
  9971. */
  9972. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9973. /**
  9974. * TSL object that represents the object's position in world space.
  9975. *
  9976. * @tsl
  9977. * @type {ModelNode<vec3>}
  9978. */
  9979. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9980. /**
  9981. * TSL object that represents the object's scale in world space.
  9982. *
  9983. * @tsl
  9984. * @type {ModelNode<vec3>}
  9985. */
  9986. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9987. /**
  9988. * TSL object that represents the object's position in view/camera space.
  9989. *
  9990. * @tsl
  9991. * @type {ModelNode<vec3>}
  9992. */
  9993. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9994. /**
  9995. * TSL object that represents the object's radius.
  9996. *
  9997. * @tsl
  9998. * @type {ModelNode<float>}
  9999. */
  10000. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  10001. /**
  10002. * TSL object that represents the object's normal matrix.
  10003. *
  10004. * @tsl
  10005. * @type {UniformNode<mat3>}
  10006. */
  10007. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  10008. /**
  10009. * TSL object that represents the object's inverse world matrix.
  10010. *
  10011. * @tsl
  10012. * @type {UniformNode<mat4>}
  10013. */
  10014. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  10015. /**
  10016. * TSL object that represents the object's model view matrix.
  10017. *
  10018. * @tsl
  10019. * @type {Node<mat4>}
  10020. */
  10021. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10022. return builder.context.modelViewMatrix || mediumpModelViewMatrix;
  10023. } ).once() )().toVar( 'modelViewMatrix' );
  10024. // GPU Precision
  10025. /**
  10026. * TSL object that represents the object's model view in `mediump` precision.
  10027. *
  10028. * @tsl
  10029. * @type {Node<mat4>}
  10030. */
  10031. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  10032. // CPU Precision
  10033. /**
  10034. * TSL object that represents the object's model view in `highp` precision
  10035. * which is achieved by computing the matrix in JS and not in the shader.
  10036. *
  10037. * @tsl
  10038. * @type {Node<mat4>}
  10039. */
  10040. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10041. builder.context.isHighPrecisionModelViewMatrix = true;
  10042. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  10043. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  10044. } );
  10045. } ).once() )().toVar( 'highpModelViewMatrix' );
  10046. /**
  10047. * TSL object that represents the object's model normal view in `highp` precision
  10048. * which is achieved by computing the matrix in JS and not in the shader.
  10049. *
  10050. * @tsl
  10051. * @type {Node<mat3>}
  10052. */
  10053. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  10054. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  10055. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  10056. if ( isHighPrecisionModelViewMatrix !== true ) {
  10057. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  10058. }
  10059. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  10060. } );
  10061. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  10062. /**
  10063. * TSL object that represents the clip space position of the current rendered object.
  10064. *
  10065. * @tsl
  10066. * @type {VaryingNode<vec4>}
  10067. */
  10068. const clipSpace = /*@__PURE__*/ ( Fn( ( builder ) => {
  10069. if ( builder.shaderStage !== 'fragment' ) {
  10070. warnOnce( 'TSL: `clipSpace` is only available in fragment stage.' );
  10071. return vec4();
  10072. }
  10073. return builder.context.clipSpace.toVarying( 'v_clipSpace' );
  10074. } ).once() )();
  10075. /**
  10076. * TSL object that represents the position attribute of the current rendered object.
  10077. *
  10078. * @tsl
  10079. * @type {AttributeNode<vec3>}
  10080. */
  10081. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  10082. /**
  10083. * TSL object that represents the vertex position in local space of the current rendered object.
  10084. *
  10085. * @tsl
  10086. * @type {AttributeNode<vec3>}
  10087. */
  10088. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  10089. /**
  10090. * TSL object that represents the previous vertex position in local space of the current rendered object.
  10091. * Used in context of {@link VelocityNode} for rendering motion vectors.
  10092. *
  10093. * @tsl
  10094. * @type {AttributeNode<vec3>}
  10095. */
  10096. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  10097. /**
  10098. * TSL object that represents the vertex position in world space of the current rendered object.
  10099. *
  10100. * @tsl
  10101. * @type {VaryingNode<vec3>}
  10102. */
  10103. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  10104. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  10105. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10106. /**
  10107. * TSL object that represents the position world direction of the current rendered object.
  10108. *
  10109. * @tsl
  10110. * @type {Node<vec3>}
  10111. */
  10112. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  10113. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  10114. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  10115. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10116. /**
  10117. * TSL object that represents the vertex position in view space of the current rendered object.
  10118. *
  10119. * @tsl
  10120. * @type {VaryingNode<vec3>}
  10121. */
  10122. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  10123. if ( builder.shaderStage === 'fragment' && builder.material.vertexNode ) {
  10124. // reconstruct view position from clip space
  10125. const viewPos = cameraProjectionMatrixInverse.mul( clipSpace );
  10126. return viewPos.xyz.div( viewPos.w ).toVar( 'positionView' );
  10127. }
  10128. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  10129. }, 'vec3' ).once( [ 'POSITION', 'VERTEX' ] ) )();
  10130. /**
  10131. * TSL object that represents the position view direction of the current rendered object.
  10132. *
  10133. * @tsl
  10134. * @type {VaryingNode<vec3>}
  10135. */
  10136. const positionViewDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10137. let output;
  10138. if ( builder.camera.isOrthographicCamera ) {
  10139. output = vec3( 0, 0, 1 );
  10140. } else {
  10141. output = positionView.negate().toVarying( 'v_positionViewDirection' ).normalize();
  10142. }
  10143. return output.toVar( 'positionViewDirection' );
  10144. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  10145. /**
  10146. * This node can be used to evaluate whether a primitive is front or back facing.
  10147. *
  10148. * @augments Node
  10149. */
  10150. class FrontFacingNode extends Node {
  10151. static get type() {
  10152. return 'FrontFacingNode';
  10153. }
  10154. /**
  10155. * Constructs a new front facing node.
  10156. */
  10157. constructor() {
  10158. super( 'bool' );
  10159. /**
  10160. * This flag can be used for type testing.
  10161. *
  10162. * @type {boolean}
  10163. * @readonly
  10164. * @default true
  10165. */
  10166. this.isFrontFacingNode = true;
  10167. }
  10168. generate( builder ) {
  10169. if ( builder.shaderStage !== 'fragment' ) return 'true';
  10170. //
  10171. const { material } = builder;
  10172. if ( material.side === BackSide ) {
  10173. return 'false';
  10174. }
  10175. return builder.getFrontFacing();
  10176. }
  10177. }
  10178. /**
  10179. * TSL object that represents whether a primitive is front or back facing
  10180. *
  10181. * @tsl
  10182. * @type {FrontFacingNode<bool>}
  10183. */
  10184. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  10185. /**
  10186. * TSL object that represents the front facing status as a number instead of a bool.
  10187. * `1` means front facing, `-1` means back facing.
  10188. *
  10189. * @tsl
  10190. * @type {Node<float>}
  10191. */
  10192. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  10193. /**
  10194. * Converts a direction vector to a face direction vector based on the material's side.
  10195. *
  10196. * If the material is set to `BackSide`, the direction is inverted.
  10197. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  10198. *
  10199. * @tsl
  10200. * @param {Node<vec3>} direction - The direction vector to convert.
  10201. * @returns {Node<vec3>} The converted direction vector.
  10202. */
  10203. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  10204. const side = material.side;
  10205. if ( side === BackSide ) {
  10206. direction = direction.mul( -1 );
  10207. } else if ( side === DoubleSide ) {
  10208. direction = direction.mul( faceDirection );
  10209. }
  10210. return direction;
  10211. } );
  10212. /**
  10213. * TSL object that represents the normal attribute of the current rendered object in local space.
  10214. *
  10215. * @tsl
  10216. * @type {Node<vec3>}
  10217. */
  10218. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  10219. /**
  10220. * TSL object that represents the vertex normal of the current rendered object in local space.
  10221. *
  10222. * @tsl
  10223. * @type {Node<vec3>}
  10224. */
  10225. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  10226. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  10227. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  10228. return vec3( 0, 1, 0 );
  10229. }
  10230. return normalGeometry;
  10231. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  10232. /**
  10233. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  10234. *
  10235. * @tsl
  10236. * @type {Node<vec3>}
  10237. */
  10238. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  10239. /**
  10240. * TSL object that represents the vertex normal of the current rendered object in view space.
  10241. *
  10242. * @tsl
  10243. * @type {Node<vec3>}
  10244. */
  10245. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10246. let node;
  10247. if ( builder.isFlatShading() ) {
  10248. node = normalFlat;
  10249. } else {
  10250. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  10251. }
  10252. return node;
  10253. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  10254. /**
  10255. * TSL object that represents the vertex normal of the current rendered object in world space.
  10256. *
  10257. * @tsl
  10258. * @type {Node<vec3>}
  10259. */
  10260. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10261. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  10262. if ( builder.isFlatShading() !== true ) {
  10263. normal = normal.toVarying( 'v_normalWorldGeometry' );
  10264. }
  10265. return normal.normalize().toVar( 'normalWorldGeometry' );
  10266. }, 'vec3' ).once() )();
  10267. /**
  10268. * TSL object that represents the vertex normal of the current rendered object in view space.
  10269. *
  10270. * @tsl
  10271. * @type {Node<vec3>}
  10272. */
  10273. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  10274. let node;
  10275. if ( builder.subBuildFn === 'NORMAL' || builder.subBuildFn === 'VERTEX' ) {
  10276. node = normalViewGeometry;
  10277. if ( builder.isFlatShading() !== true ) {
  10278. node = directionToFaceDirection( node );
  10279. }
  10280. } else {
  10281. // Use custom context to avoid side effects from nodes overwriting getUV, getTextureLevel in the context (e.g. EnvironmentNode)
  10282. node = builder.context.setupNormal().context( { getUV: null, getTextureLevel: null } );
  10283. }
  10284. return node;
  10285. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  10286. /**
  10287. * TSL object that represents the vertex normal of the current rendered object in world space.
  10288. *
  10289. * @tsl
  10290. * @type {Node<vec3>}
  10291. */
  10292. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  10293. /**
  10294. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  10295. *
  10296. * @tsl
  10297. * @type {Node<vec3>}
  10298. */
  10299. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  10300. let node;
  10301. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10302. node = normalView;
  10303. } else {
  10304. // Use custom context to avoid side effects from nodes overwriting getUV, getTextureLevel in the context (e.g. EnvironmentNode)
  10305. node = context.setupClearcoatNormal().context( { getUV: null, getTextureLevel: null } );
  10306. }
  10307. return node;
  10308. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  10309. /**
  10310. * Transforms the normal with the given matrix.
  10311. *
  10312. * @tsl
  10313. * @function
  10314. * @param {Node<vec3>} normal - The normal.
  10315. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  10316. * @return {Node<vec3>} The transformed normal.
  10317. */
  10318. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  10319. const m = mat3( matrix );
  10320. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  10321. return m.mul( transformedNormal ).xyz;
  10322. } );
  10323. /**
  10324. * Transforms the given normal from local to view space.
  10325. *
  10326. * @tsl
  10327. * @function
  10328. * @param {Node<vec3>} normal - The normal.
  10329. * @param {NodeBuilder} builder - The current node builder.
  10330. * @return {Node<vec3>} The transformed normal.
  10331. */
  10332. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  10333. const modelNormalViewMatrix = builder.context.modelNormalViewMatrix;
  10334. if ( modelNormalViewMatrix ) {
  10335. return modelNormalViewMatrix.transformDirection( normal );
  10336. }
  10337. //
  10338. const transformedNormal = modelNormalMatrix.mul( normal );
  10339. return cameraViewMatrix.transformDirection( transformedNormal );
  10340. } );
  10341. // Deprecated
  10342. /**
  10343. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  10344. *
  10345. * @tsl
  10346. * @type {Node<vec3>}
  10347. * @deprecated since r178. Use `normalView` instead.
  10348. */
  10349. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  10350. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  10351. return normalView;
  10352. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10353. /**
  10354. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  10355. *
  10356. * @tsl
  10357. * @type {Node<vec3>}
  10358. * @deprecated since r178. Use `normalWorld` instead.
  10359. */
  10360. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  10361. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  10362. return normalWorld;
  10363. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10364. /**
  10365. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  10366. *
  10367. * @tsl
  10368. * @type {Node<vec3>}
  10369. * @deprecated since r178. Use `clearcoatNormalView` instead.
  10370. */
  10371. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  10372. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  10373. return clearcoatNormalView;
  10374. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10375. const _e1$1 = /*@__PURE__*/ new Euler();
  10376. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10377. /**
  10378. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  10379. *
  10380. * @tsl
  10381. * @type {UniformNode<float>}
  10382. */
  10383. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  10384. /**
  10385. * TSL object that represents the intensity of environment maps of PBR materials.
  10386. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  10387. *
  10388. * @tsl
  10389. * @type {Node<float>}
  10390. */
  10391. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  10392. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  10393. } );
  10394. /**
  10395. * TSL object that represents the rotation of environment maps.
  10396. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  10397. * rotation of `scene.environment` instead.
  10398. *
  10399. * @tsl
  10400. * @type {Node<mat4>}
  10401. */
  10402. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  10403. return frame.material;
  10404. } ).onObjectUpdate( function ( { material, scene } ) {
  10405. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10406. if ( rotation ) {
  10407. _e1$1.copy( rotation );
  10408. _m1$1.makeRotationFromEuler( _e1$1 );
  10409. } else {
  10410. _m1$1.identity();
  10411. }
  10412. return _m1$1;
  10413. } );
  10414. /**
  10415. * The reflect vector in view space.
  10416. *
  10417. * @tsl
  10418. * @type {Node<vec3>}
  10419. */
  10420. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  10421. /**
  10422. * The refract vector in view space.
  10423. *
  10424. * @tsl
  10425. * @type {Node<vec3>}
  10426. */
  10427. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10428. /**
  10429. * Used for sampling cube maps when using cube reflection mapping.
  10430. *
  10431. * @tsl
  10432. * @type {Node<vec3>}
  10433. */
  10434. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10435. /**
  10436. * Used for sampling cube maps when using cube refraction mapping.
  10437. *
  10438. * @tsl
  10439. * @type {Node<vec3>}
  10440. */
  10441. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10442. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  10443. /**
  10444. * This type of uniform node represents a cube texture.
  10445. *
  10446. * @augments TextureNode
  10447. */
  10448. class CubeTextureNode extends TextureNode {
  10449. static get type() {
  10450. return 'CubeTextureNode';
  10451. }
  10452. /**
  10453. * Constructs a new cube texture node.
  10454. *
  10455. * @param {CubeTexture} value - The cube texture.
  10456. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10457. * @param {?Node<int>} [levelNode=null] - The level node.
  10458. * @param {?Node<float>} [biasNode=null] - The bias node.
  10459. */
  10460. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10461. super( value, uvNode, levelNode, biasNode );
  10462. /**
  10463. * This flag can be used for type testing.
  10464. *
  10465. * @type {boolean}
  10466. * @readonly
  10467. * @default true
  10468. */
  10469. this.isCubeTextureNode = true;
  10470. }
  10471. /**
  10472. * Overwrites the default implementation to return the appropriate cube texture type.
  10473. *
  10474. * @param {NodeBuilder} builder - The current node builder.
  10475. * @return {string} The input type.
  10476. */
  10477. getInputType( /*builder*/ ) {
  10478. if ( this.value.isDepthTexture === true ) {
  10479. return 'cubeDepthTexture';
  10480. }
  10481. return 'cubeTexture';
  10482. }
  10483. /**
  10484. * Returns a default uvs based on the mapping type of the cube texture.
  10485. *
  10486. * @return {Node<vec3>} The default uv attribute.
  10487. */
  10488. getDefaultUV() {
  10489. const texture = this.value;
  10490. if ( texture.mapping === CubeReflectionMapping ) {
  10491. return reflectVector;
  10492. } else if ( texture.mapping === CubeRefractionMapping ) {
  10493. return refractVector;
  10494. } else {
  10495. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10496. return vec3( 0, 0, 0 );
  10497. }
  10498. }
  10499. /**
  10500. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10501. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10502. *
  10503. * @param {boolean} value - The update toggle.
  10504. */
  10505. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10506. /**
  10507. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10508. * to modify the uv node for correct sampling.
  10509. *
  10510. * @param {NodeBuilder} builder - The current node builder.
  10511. * @param {Node} uvNode - The uv node to setup.
  10512. * @return {Node} The updated uv node.
  10513. */
  10514. setupUV( builder, uvNode ) {
  10515. const texture = this.value;
  10516. // Depth textures (shadow maps) - no environment rotation, Y flip for WebGPU
  10517. if ( texture.isDepthTexture === true ) {
  10518. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  10519. return vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  10520. }
  10521. return uvNode;
  10522. }
  10523. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10524. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10525. }
  10526. return materialEnvRotation.mul( uvNode );
  10527. }
  10528. /**
  10529. * Generates the uv code snippet.
  10530. *
  10531. * @param {NodeBuilder} builder - The current node builder.
  10532. * @param {Node} cubeUV - The uv node to generate code for.
  10533. * @return {string} The generated code snippet.
  10534. */
  10535. generateUV( builder, cubeUV ) {
  10536. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10537. }
  10538. }
  10539. /**
  10540. * TSL function for creating a cube texture node.
  10541. *
  10542. * @tsl
  10543. * @function
  10544. * @param {CubeTexture} value - The cube texture.
  10545. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10546. * @param {?Node<int>} [levelNode=null] - The level node.
  10547. * @param {?Node<float>} [biasNode=null] - The bias node.
  10548. * @returns {CubeTextureNode}
  10549. */
  10550. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10551. /**
  10552. * TSL function for creating a cube texture uniform node.
  10553. *
  10554. * @tsl
  10555. * @function
  10556. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10557. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10558. * @param {?Node<int>} [levelNode=null] - The level node.
  10559. * @param {?Node<float>} [biasNode=null] - The bias node.
  10560. * @returns {CubeTextureNode}
  10561. */
  10562. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10563. let textureNode;
  10564. if ( value && value.isCubeTextureNode === true ) {
  10565. textureNode = nodeObject( value.clone() );
  10566. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10567. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10568. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10569. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10570. } else {
  10571. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10572. }
  10573. return textureNode;
  10574. };
  10575. /**
  10576. * TSL function for creating a uniform cube texture node.
  10577. *
  10578. * @tsl
  10579. * @function
  10580. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10581. * @returns {CubeTextureNode}
  10582. */
  10583. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10584. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  10585. /**
  10586. * This class is only relevant if the referenced property is array-like.
  10587. * In this case, `ReferenceElementNode` allows to refer to a specific
  10588. * element inside the data structure via an index.
  10589. *
  10590. * @augments ArrayElementNode
  10591. */
  10592. class ReferenceElementNode extends ArrayElementNode {
  10593. static get type() {
  10594. return 'ReferenceElementNode';
  10595. }
  10596. /**
  10597. * Constructs a new reference element node.
  10598. *
  10599. * @param {?ReferenceNode} referenceNode - The reference node.
  10600. * @param {Node} indexNode - The index node that defines the element access.
  10601. */
  10602. constructor( referenceNode, indexNode ) {
  10603. super( referenceNode, indexNode );
  10604. /**
  10605. * Similar to {@link ReferenceNode#reference}, an additional
  10606. * property references to the current node.
  10607. *
  10608. * @type {?ReferenceNode}
  10609. * @default null
  10610. */
  10611. this.referenceNode = referenceNode;
  10612. /**
  10613. * This flag can be used for type testing.
  10614. *
  10615. * @type {boolean}
  10616. * @readonly
  10617. * @default true
  10618. */
  10619. this.isReferenceElementNode = true;
  10620. }
  10621. /**
  10622. * This method is overwritten since the node type is inferred from
  10623. * the uniform type of the reference node.
  10624. *
  10625. * @return {string} The node type.
  10626. */
  10627. getNodeType() {
  10628. return this.referenceNode.uniformType;
  10629. }
  10630. generate( builder ) {
  10631. const snippet = super.generate( builder );
  10632. const arrayType = this.referenceNode.getNodeType();
  10633. const elementType = this.getNodeType();
  10634. return builder.format( snippet, arrayType, elementType );
  10635. }
  10636. }
  10637. /**
  10638. * This type of node establishes a reference to a property of another object.
  10639. * In this way, the value of the node is automatically linked to the value of
  10640. * referenced object. Reference nodes internally represent the linked value
  10641. * as a uniform.
  10642. *
  10643. * @augments Node
  10644. */
  10645. class ReferenceNode extends Node {
  10646. static get type() {
  10647. return 'ReferenceNode';
  10648. }
  10649. /**
  10650. * Constructs a new reference node.
  10651. *
  10652. * @param {string} property - The name of the property the node refers to.
  10653. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10654. * @param {?Object} [object=null] - The object the property belongs to.
  10655. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10656. */
  10657. constructor( property, uniformType, object = null, count = null ) {
  10658. super();
  10659. /**
  10660. * The name of the property the node refers to.
  10661. *
  10662. * @type {string}
  10663. */
  10664. this.property = property;
  10665. /**
  10666. * The uniform type that should be used to represent the property value.
  10667. *
  10668. * @type {string}
  10669. */
  10670. this.uniformType = uniformType;
  10671. /**
  10672. * The object the property belongs to.
  10673. *
  10674. * @type {?Object}
  10675. * @default null
  10676. */
  10677. this.object = object;
  10678. /**
  10679. * When the linked property is an array, this parameter defines its length.
  10680. *
  10681. * @type {?number}
  10682. * @default null
  10683. */
  10684. this.count = count;
  10685. /**
  10686. * The property name might have dots so nested properties can be referred.
  10687. * The hierarchy of the names is stored inside this array.
  10688. *
  10689. * @type {Array<string>}
  10690. */
  10691. this.properties = property.split( '.' );
  10692. /**
  10693. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10694. * since the final reference might be updated from calling code.
  10695. *
  10696. * @type {?Object}
  10697. * @default null
  10698. */
  10699. this.reference = object;
  10700. /**
  10701. * The uniform node that holds the value of the reference node.
  10702. *
  10703. * @type {UniformNode}
  10704. * @default null
  10705. */
  10706. this.node = null;
  10707. /**
  10708. * The uniform group of the internal uniform.
  10709. *
  10710. * @type {UniformGroupNode}
  10711. * @default null
  10712. */
  10713. this.group = null;
  10714. /**
  10715. * An optional label of the internal uniform node.
  10716. *
  10717. * @type {?string}
  10718. * @default null
  10719. */
  10720. this.name = null;
  10721. /**
  10722. * Overwritten since reference nodes are updated per object.
  10723. *
  10724. * @type {string}
  10725. * @default 'object'
  10726. */
  10727. this.updateType = NodeUpdateType.OBJECT;
  10728. }
  10729. /**
  10730. * When the referred property is array-like, this method can be used
  10731. * to access elements via an index node.
  10732. *
  10733. * @param {IndexNode} indexNode - indexNode.
  10734. * @return {ReferenceElementNode} A reference to an element.
  10735. */
  10736. element( indexNode ) {
  10737. return new ReferenceElementNode( this, nodeObject( indexNode ) );
  10738. }
  10739. /**
  10740. * Sets the uniform group for this reference node.
  10741. *
  10742. * @param {UniformGroupNode} group - The uniform group to set.
  10743. * @return {ReferenceNode} A reference to this node.
  10744. */
  10745. setGroup( group ) {
  10746. this.group = group;
  10747. return this;
  10748. }
  10749. /**
  10750. * Sets the name for the internal uniform.
  10751. *
  10752. * @param {string} name - The label to set.
  10753. * @return {ReferenceNode} A reference to this node.
  10754. */
  10755. setName( name ) {
  10756. this.name = name;
  10757. return this;
  10758. }
  10759. /**
  10760. * Sets the label for the internal uniform.
  10761. *
  10762. * @deprecated
  10763. * @param {string} name - The label to set.
  10764. * @return {ReferenceNode} A reference to this node.
  10765. */
  10766. label( name ) {
  10767. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  10768. return this.setName( name );
  10769. }
  10770. /**
  10771. * Sets the node type which automatically defines the internal
  10772. * uniform type.
  10773. *
  10774. * @param {string} uniformType - The type to set.
  10775. */
  10776. setNodeType( uniformType ) {
  10777. let node = null;
  10778. if ( this.count !== null ) {
  10779. node = buffer( null, uniformType, this.count );
  10780. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  10781. node = uniformArray( null, uniformType );
  10782. } else if ( uniformType === 'texture' ) {
  10783. node = texture( null );
  10784. } else if ( uniformType === 'cubeTexture' ) {
  10785. node = cubeTexture( null );
  10786. } else {
  10787. node = uniform( null, uniformType );
  10788. }
  10789. if ( this.group !== null ) {
  10790. node.setGroup( this.group );
  10791. }
  10792. if ( this.name !== null ) node.setName( this.name );
  10793. this.node = node;
  10794. }
  10795. /**
  10796. * This method is overwritten since the node type is inferred from
  10797. * the type of the reference node.
  10798. *
  10799. * @param {NodeBuilder} builder - The current node builder.
  10800. * @return {string} The node type.
  10801. */
  10802. getNodeType( builder ) {
  10803. if ( this.node === null ) {
  10804. this.updateReference( builder );
  10805. this.updateValue();
  10806. }
  10807. return this.node.getNodeType( builder );
  10808. }
  10809. /**
  10810. * Returns the property value from the given referred object.
  10811. *
  10812. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10813. * @return {any} The value.
  10814. */
  10815. getValueFromReference( object = this.reference ) {
  10816. const { properties } = this;
  10817. let value = object[ properties[ 0 ] ];
  10818. for ( let i = 1; i < properties.length; i ++ ) {
  10819. value = value[ properties[ i ] ];
  10820. }
  10821. return value;
  10822. }
  10823. /**
  10824. * Allows to update the reference based on the given state. The state is only
  10825. * evaluated {@link ReferenceNode#object} is not set.
  10826. *
  10827. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10828. * @return {Object} The updated reference.
  10829. */
  10830. updateReference( state ) {
  10831. this.reference = this.object !== null ? this.object : state.object;
  10832. return this.reference;
  10833. }
  10834. /**
  10835. * The output of the reference node is the internal uniform node.
  10836. *
  10837. * @param {NodeBuilder} builder - The current node builder.
  10838. * @return {UniformNode} The output node.
  10839. */
  10840. setup( /* builder */ ) {
  10841. this.updateValue();
  10842. return this.node;
  10843. }
  10844. /**
  10845. * Overwritten to update the internal uniform value.
  10846. *
  10847. * @param {NodeFrame} frame - A reference to the current node frame.
  10848. */
  10849. update( /*frame*/ ) {
  10850. this.updateValue();
  10851. }
  10852. /**
  10853. * Retrieves the value from the referred object property and uses it
  10854. * to updated the internal uniform.
  10855. */
  10856. updateValue() {
  10857. if ( this.node === null ) this.setNodeType( this.uniformType );
  10858. const value = this.getValueFromReference();
  10859. if ( Array.isArray( value ) ) {
  10860. this.node.array = value;
  10861. } else {
  10862. this.node.value = value;
  10863. }
  10864. }
  10865. }
  10866. /**
  10867. * TSL function for creating a reference node.
  10868. *
  10869. * @tsl
  10870. * @function
  10871. * @param {string} name - The name of the property the node refers to.
  10872. * @param {string} type - The uniform type that should be used to represent the property value.
  10873. * @param {?Object} [object] - The object the property belongs to.
  10874. * @returns {ReferenceNode}
  10875. */
  10876. const reference = ( name, type, object ) => new ReferenceNode( name, type, object );
  10877. /**
  10878. * TSL function for creating a reference node. Use this function if you want need a reference
  10879. * to an array-like property that should be represented as a uniform buffer.
  10880. *
  10881. * @tsl
  10882. * @function
  10883. * @param {string} name - The name of the property the node refers to.
  10884. * @param {string} type - The uniform type that should be used to represent the property value.
  10885. * @param {number} count - The number of value inside the array-like object.
  10886. * @param {Object} object - An array-like object the property belongs to.
  10887. * @returns {ReferenceNode}
  10888. */
  10889. const referenceBuffer = ( name, type, count, object ) => new ReferenceNode( name, type, object, count );
  10890. /**
  10891. * This node is a special type of reference node which is intended
  10892. * for linking material properties with node values.
  10893. * ```js
  10894. * const opacityNode = materialReference( 'opacity', 'float', material );
  10895. * ```
  10896. * When changing `material.opacity`, the node value of `opacityNode` will
  10897. * automatically be updated.
  10898. *
  10899. * @augments ReferenceNode
  10900. */
  10901. class MaterialReferenceNode extends ReferenceNode {
  10902. static get type() {
  10903. return 'MaterialReferenceNode';
  10904. }
  10905. /**
  10906. * Constructs a new material reference node.
  10907. *
  10908. * @param {string} property - The name of the property the node refers to.
  10909. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10910. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10911. * the node refers to the material of the current rendered object.
  10912. */
  10913. constructor( property, inputType, material = null ) {
  10914. super( property, inputType, material );
  10915. /**
  10916. * The material the property belongs to. When no material is set,
  10917. * the node refers to the material of the current rendered object.
  10918. *
  10919. * @type {?Material}
  10920. * @default null
  10921. */
  10922. this.material = material;
  10923. /**
  10924. * This flag can be used for type testing.
  10925. *
  10926. * @type {boolean}
  10927. * @readonly
  10928. * @default true
  10929. */
  10930. this.isMaterialReferenceNode = true;
  10931. }
  10932. /**
  10933. * Updates the reference based on the given state. The state is only evaluated
  10934. * {@link MaterialReferenceNode#material} is not set.
  10935. *
  10936. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10937. * @return {Object} The updated reference.
  10938. */
  10939. updateReference( state ) {
  10940. this.reference = this.material !== null ? this.material : state.material;
  10941. return this.reference;
  10942. }
  10943. }
  10944. /**
  10945. * TSL function for creating a material reference node.
  10946. *
  10947. * @tsl
  10948. * @function
  10949. * @param {string} name - The name of the property the node refers to.
  10950. * @param {string} type - The uniform type that should be used to represent the property value.
  10951. * @param {?Material} [material=null] - The material the property belongs to.
  10952. * When no material is set, the node refers to the material of the current rendered object.
  10953. * @returns {MaterialReferenceNode}
  10954. */
  10955. const materialReference = ( name, type, material = null ) => new MaterialReferenceNode( name, type, material );
  10956. // Normal Mapping Without Precomputed Tangents
  10957. // http://www.thetenthplanet.de/archives/1180
  10958. const uv = uv$1();
  10959. const q0 = positionView.dFdx();
  10960. const q1 = positionView.dFdy();
  10961. const st0 = uv.dFdx();
  10962. const st1 = uv.dFdy();
  10963. const N = normalView;
  10964. const q1perp = q1.cross( N );
  10965. const q0perp = N.cross( q0 );
  10966. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10967. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10968. const det = T.dot( T ).max( B.dot( B ) );
  10969. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10970. /**
  10971. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10972. * Useful for normal mapping without precomputed tangents.
  10973. *
  10974. * Reference: http://www.thetenthplanet.de/archives/1180
  10975. *
  10976. * @tsl
  10977. * @type {Node<vec3>}
  10978. */
  10979. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10980. /**
  10981. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10982. * Complements the tangentViewFrame for constructing the tangent space basis.
  10983. *
  10984. * Reference: http://www.thetenthplanet.de/archives/1180
  10985. *
  10986. * @tsl
  10987. * @type {Node<vec3>}
  10988. */
  10989. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10990. /**
  10991. * TSL object that represents the tangent attribute of the current rendered object.
  10992. *
  10993. * @tsl
  10994. * @type {Node<vec4>}
  10995. */
  10996. const tangentGeometry = /*@__PURE__*/ attribute( 'tangent', 'vec4' );
  10997. /**
  10998. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10999. *
  11000. * @tsl
  11001. * @type {Node<vec3>}
  11002. */
  11003. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  11004. /**
  11005. * TSL object that represents the vertex tangent in view space of the current rendered object.
  11006. *
  11007. * @tsl
  11008. * @type {Node<vec3>}
  11009. */
  11010. const tangentView = /*@__PURE__*/ ( Fn( ( builder ) => {
  11011. let node;
  11012. if ( builder.subBuildFn === 'VERTEX' || builder.geometry.hasAttribute( 'tangent' ) ) {
  11013. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  11014. } else {
  11015. node = tangentViewFrame;
  11016. }
  11017. if ( builder.isFlatShading() !== true ) {
  11018. node = directionToFaceDirection( node );
  11019. }
  11020. return node;
  11021. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  11022. /**
  11023. * TSL object that represents the vertex tangent in world space of the current rendered object.
  11024. *
  11025. * @tsl
  11026. * @type {Node<vec3>}
  11027. */
  11028. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  11029. /**
  11030. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  11031. *
  11032. * @tsl
  11033. * @private
  11034. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  11035. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  11036. * @returns {Node<vec3>} The bitangent node.
  11037. */
  11038. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], builder ) => {
  11039. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  11040. if ( builder.subBuildFn === 'NORMAL' && builder.isFlatShading() !== true ) {
  11041. bitangent = bitangent.toVarying( varyingName );
  11042. }
  11043. return bitangent;
  11044. } ).once( [ 'NORMAL' ] );
  11045. /**
  11046. * TSL object that represents the bitangent attribute of the current rendered object.
  11047. *
  11048. * @tsl
  11049. * @type {Node<vec3>}
  11050. */
  11051. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  11052. /**
  11053. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  11054. *
  11055. * @tsl
  11056. * @type {Node<vec3>}
  11057. */
  11058. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  11059. /**
  11060. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  11061. *
  11062. * @tsl
  11063. * @type {Node<vec3>}
  11064. */
  11065. const bitangentView = /*@__PURE__*/ ( Fn( ( builder ) => {
  11066. let node;
  11067. if ( builder.subBuildFn === 'VERTEX' || builder.geometry.hasAttribute( 'tangent' ) ) {
  11068. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  11069. } else {
  11070. node = bitangentViewFrame;
  11071. }
  11072. if ( builder.isFlatShading() !== true ) {
  11073. node = directionToFaceDirection( node );
  11074. }
  11075. return node;
  11076. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  11077. /**
  11078. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  11079. *
  11080. * @tsl
  11081. * @type {Node<vec3>}
  11082. */
  11083. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  11084. /**
  11085. * TSL object that represents the TBN matrix in view space.
  11086. *
  11087. * @tsl
  11088. * @type {Node<mat3>}
  11089. */
  11090. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  11091. /**
  11092. * TSL object that represents the parallax direction.
  11093. *
  11094. * @tsl
  11095. * @type {Node<mat3>}
  11096. */
  11097. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  11098. /**
  11099. * TSL function for computing parallax uv coordinates.
  11100. *
  11101. * @tsl
  11102. * @function
  11103. * @param {Node<vec2>} uv - A uv node.
  11104. * @param {Node<vec2>} scale - A scale node.
  11105. * @returns {Node<vec2>} Parallax uv coordinates.
  11106. */
  11107. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  11108. /**
  11109. * TSL function for computing bent normals.
  11110. *
  11111. * @tsl
  11112. * @function
  11113. * @returns {Node<vec3>} Bent normals.
  11114. */
  11115. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  11116. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  11117. let bentNormal = anisotropyB.cross( positionViewDirection );
  11118. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  11119. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  11120. return bentNormal;
  11121. } ).once() )();
  11122. /**
  11123. * Packs a direction vector into a color value.
  11124. *
  11125. * @tsl
  11126. * @function
  11127. * @param {Node<vec3>} node - The direction to pack.
  11128. * @return {Node<vec3>} The color.
  11129. */
  11130. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  11131. /**
  11132. * Unpacks a color value into a direction vector.
  11133. *
  11134. * @tsl
  11135. * @function
  11136. * @param {Node<vec3>} node - The color to unpack.
  11137. * @return {Node<vec3>} The direction.
  11138. */
  11139. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  11140. /**
  11141. * Unpacks a tangent space normal, reconstructing the Z component by projecting the X,Y coordinates onto the hemisphere.
  11142. * The X,Y coordinates are expected to be in the [-1, 1] range.
  11143. *
  11144. * @tsl
  11145. * @function
  11146. * @param {Node<vec2>} xy - The X,Y coordinates of the normal.
  11147. * @return {Node<vec3>} The resulting normal.
  11148. */
  11149. const unpackNormal = ( xy ) => vec3( xy, sqrt( saturate( float( 1.0 ).sub( dot( xy, xy ) ) ) ) );
  11150. /**
  11151. * This class can be used for applying normals maps to materials.
  11152. *
  11153. * ```js
  11154. * material.normalNode = normalMap( texture( normalTex ) );
  11155. * ```
  11156. *
  11157. * @augments TempNode
  11158. */
  11159. class NormalMapNode extends TempNode {
  11160. static get type() {
  11161. return 'NormalMapNode';
  11162. }
  11163. /**
  11164. * Constructs a new normal map node.
  11165. *
  11166. * @param {Node<vec3>} node - Represents the normal map data.
  11167. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11168. */
  11169. constructor( node, scaleNode = null ) {
  11170. super( 'vec3' );
  11171. /**
  11172. * Represents the normal map data.
  11173. *
  11174. * @type {Node<vec3>}
  11175. */
  11176. this.node = node;
  11177. /**
  11178. * Controls the intensity of the effect.
  11179. *
  11180. * @type {?Node<vec2>}
  11181. * @default null
  11182. */
  11183. this.scaleNode = scaleNode;
  11184. /**
  11185. * The normal map type.
  11186. *
  11187. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  11188. * @default TangentSpaceNormalMap
  11189. */
  11190. this.normalMapType = TangentSpaceNormalMap;
  11191. /**
  11192. * Controls how to unpack the sampled normal map values.
  11193. *
  11194. * @type {string}
  11195. * @default NoNormalPacking
  11196. */
  11197. this.unpackNormalMode = NoNormalPacking;
  11198. }
  11199. setup( builder ) {
  11200. const { normalMapType, scaleNode, unpackNormalMode } = this;
  11201. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  11202. if ( normalMapType === TangentSpaceNormalMap ) {
  11203. if ( unpackNormalMode === NormalRGPacking ) {
  11204. normalMap = unpackNormal( normalMap.xy );
  11205. } else if ( unpackNormalMode === NormalGAPacking ) {
  11206. normalMap = unpackNormal( normalMap.yw );
  11207. } else if ( unpackNormalMode !== NoNormalPacking ) {
  11208. console.error( `THREE.NodeMaterial: Unexpected unpack normal mode: ${ unpackNormalMode }` );
  11209. }
  11210. } else {
  11211. if ( unpackNormalMode !== NoNormalPacking ) {
  11212. console.error( `THREE.NodeMaterial: Normal map type '${ normalMapType }' is not compatible with unpack normal mode '${ unpackNormalMode }'` );
  11213. }
  11214. }
  11215. if ( scaleNode !== null ) {
  11216. let scale = scaleNode;
  11217. if ( builder.isFlatShading() === true ) {
  11218. scale = directionToFaceDirection( scale );
  11219. }
  11220. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  11221. }
  11222. let output = null;
  11223. if ( normalMapType === ObjectSpaceNormalMap ) {
  11224. output = transformNormalToView( normalMap );
  11225. } else if ( normalMapType === TangentSpaceNormalMap ) {
  11226. output = TBNViewMatrix.mul( normalMap ).normalize();
  11227. } else {
  11228. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  11229. output = normalView; // Fallback to default normal view
  11230. }
  11231. return output;
  11232. }
  11233. }
  11234. /**
  11235. * TSL function for creating a normal map node.
  11236. *
  11237. * @tsl
  11238. * @function
  11239. * @param {Node<vec3>} node - Represents the normal map data.
  11240. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11241. * @returns {NormalMapNode}
  11242. */
  11243. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  11244. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  11245. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  11246. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  11247. // It's used to preserve the same TextureNode instance
  11248. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  11249. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  11250. return vec2(
  11251. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  11252. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  11253. ).mul( bumpScale );
  11254. } );
  11255. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  11256. const perturbNormalArb = Fn( ( inputs ) => {
  11257. const { surf_pos, surf_norm, dHdxy } = inputs;
  11258. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  11259. const vSigmaX = surf_pos.dFdx().normalize();
  11260. const vSigmaY = surf_pos.dFdy().normalize();
  11261. const vN = surf_norm; // normalized
  11262. const R1 = vSigmaY.cross( vN );
  11263. const R2 = vN.cross( vSigmaX );
  11264. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  11265. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  11266. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  11267. } );
  11268. /**
  11269. * This class can be used for applying bump maps to materials.
  11270. *
  11271. * ```js
  11272. * material.normalNode = bumpMap( texture( bumpTex ) );
  11273. * ```
  11274. *
  11275. * @augments TempNode
  11276. */
  11277. class BumpMapNode extends TempNode {
  11278. static get type() {
  11279. return 'BumpMapNode';
  11280. }
  11281. /**
  11282. * Constructs a new bump map node.
  11283. *
  11284. * @param {Node<float>} textureNode - Represents the bump map data.
  11285. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11286. */
  11287. constructor( textureNode, scaleNode = null ) {
  11288. super( 'vec3' );
  11289. /**
  11290. * Represents the bump map data.
  11291. *
  11292. * @type {Node<float>}
  11293. */
  11294. this.textureNode = textureNode;
  11295. /**
  11296. * Controls the intensity of the bump effect.
  11297. *
  11298. * @type {?Node<float>}
  11299. * @default null
  11300. */
  11301. this.scaleNode = scaleNode;
  11302. }
  11303. setup() {
  11304. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  11305. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  11306. return perturbNormalArb( {
  11307. surf_pos: positionView,
  11308. surf_norm: normalView,
  11309. dHdxy
  11310. } );
  11311. }
  11312. }
  11313. /**
  11314. * TSL function for creating a bump map node.
  11315. *
  11316. * @tsl
  11317. * @function
  11318. * @param {Node<float>} textureNode - Represents the bump map data.
  11319. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11320. * @returns {BumpMapNode}
  11321. */
  11322. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  11323. const _propertyCache = new Map();
  11324. /**
  11325. * This class should simplify the node access to material properties.
  11326. * It internal uses reference nodes to make sure changes to material
  11327. * properties are automatically reflected to predefined TSL objects
  11328. * like e.g. `materialColor`.
  11329. *
  11330. * @augments Node
  11331. */
  11332. class MaterialNode extends Node {
  11333. static get type() {
  11334. return 'MaterialNode';
  11335. }
  11336. /**
  11337. * Constructs a new material node.
  11338. *
  11339. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  11340. */
  11341. constructor( scope ) {
  11342. super();
  11343. /**
  11344. * The scope defines what material property is referred by the node.
  11345. *
  11346. * @type {string}
  11347. */
  11348. this.scope = scope;
  11349. }
  11350. /**
  11351. * Returns a cached reference node for the given property and type.
  11352. *
  11353. * @param {string} property - The name of the material property.
  11354. * @param {string} type - The uniform type of the property.
  11355. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11356. */
  11357. getCache( property, type ) {
  11358. let node = _propertyCache.get( property );
  11359. if ( node === undefined ) {
  11360. node = materialReference( property, type );
  11361. _propertyCache.set( property, node );
  11362. }
  11363. return node;
  11364. }
  11365. /**
  11366. * Returns a float-typed material reference node for the given property name.
  11367. *
  11368. * @param {string} property - The name of the material property.
  11369. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  11370. */
  11371. getFloat( property ) {
  11372. return this.getCache( property, 'float' );
  11373. }
  11374. /**
  11375. * Returns a color-typed material reference node for the given property name.
  11376. *
  11377. * @param {string} property - The name of the material property.
  11378. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  11379. */
  11380. getColor( property ) {
  11381. return this.getCache( property, 'color' );
  11382. }
  11383. /**
  11384. * Returns a texture-typed material reference node for the given property name.
  11385. *
  11386. * @param {string} property - The name of the material property.
  11387. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11388. */
  11389. getTexture( property ) {
  11390. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  11391. }
  11392. /**
  11393. * The node setup is done depending on the selected scope. Multiple material properties
  11394. * might be grouped into a single node composition if they logically belong together.
  11395. *
  11396. * @param {NodeBuilder} builder - The current node builder.
  11397. * @return {Node} The node representing the selected scope.
  11398. */
  11399. setup( builder ) {
  11400. const material = builder.context.material;
  11401. const scope = this.scope;
  11402. let node = null;
  11403. if ( scope === MaterialNode.COLOR ) {
  11404. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  11405. if ( material.map && material.map.isTexture === true ) {
  11406. node = colorNode.mul( this.getTexture( 'map' ) );
  11407. } else {
  11408. node = colorNode;
  11409. }
  11410. } else if ( scope === MaterialNode.OPACITY ) {
  11411. const opacityNode = this.getFloat( scope );
  11412. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  11413. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  11414. } else {
  11415. node = opacityNode;
  11416. }
  11417. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  11418. if ( material.specularMap && material.specularMap.isTexture === true ) {
  11419. node = this.getTexture( 'specular' ).r;
  11420. } else {
  11421. node = float( 1 );
  11422. }
  11423. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  11424. const specularIntensityNode = this.getFloat( scope );
  11425. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  11426. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  11427. } else {
  11428. node = specularIntensityNode;
  11429. }
  11430. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  11431. const specularColorNode = this.getColor( scope );
  11432. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  11433. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  11434. } else {
  11435. node = specularColorNode;
  11436. }
  11437. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  11438. const roughnessNode = this.getFloat( scope );
  11439. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  11440. node = roughnessNode.mul( this.getTexture( scope ).g );
  11441. } else {
  11442. node = roughnessNode;
  11443. }
  11444. } else if ( scope === MaterialNode.METALNESS ) {
  11445. const metalnessNode = this.getFloat( scope );
  11446. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  11447. node = metalnessNode.mul( this.getTexture( scope ).b );
  11448. } else {
  11449. node = metalnessNode;
  11450. }
  11451. } else if ( scope === MaterialNode.EMISSIVE ) {
  11452. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  11453. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  11454. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  11455. node = emissiveNode.mul( this.getTexture( scope ) );
  11456. } else {
  11457. node = emissiveNode;
  11458. }
  11459. } else if ( scope === MaterialNode.NORMAL ) {
  11460. if ( material.normalMap ) {
  11461. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  11462. node.normalMapType = material.normalMapType;
  11463. if ( material.normalMap.format == RGFormat || material.normalMap.format == RED_GREEN_RGTC2_Format || material.normalMap.format == RG11_EAC_Format ) {
  11464. node.unpackNormalMode = NormalRGPacking;
  11465. }
  11466. } else if ( material.bumpMap ) {
  11467. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  11468. } else {
  11469. node = normalView;
  11470. }
  11471. } else if ( scope === MaterialNode.CLEARCOAT ) {
  11472. const clearcoatNode = this.getFloat( scope );
  11473. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  11474. node = clearcoatNode.mul( this.getTexture( scope ).r );
  11475. } else {
  11476. node = clearcoatNode;
  11477. }
  11478. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  11479. const clearcoatRoughnessNode = this.getFloat( scope );
  11480. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  11481. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  11482. } else {
  11483. node = clearcoatRoughnessNode;
  11484. }
  11485. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  11486. if ( material.clearcoatNormalMap ) {
  11487. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  11488. } else {
  11489. node = normalView;
  11490. }
  11491. } else if ( scope === MaterialNode.SHEEN ) {
  11492. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  11493. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  11494. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  11495. } else {
  11496. node = sheenNode;
  11497. }
  11498. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  11499. const sheenRoughnessNode = this.getFloat( scope );
  11500. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  11501. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  11502. } else {
  11503. node = sheenRoughnessNode;
  11504. }
  11505. node = node.clamp( 0.0001, 1.0 );
  11506. } else if ( scope === MaterialNode.ANISOTROPY ) {
  11507. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  11508. const anisotropyPolar = this.getTexture( scope );
  11509. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  11510. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  11511. } else {
  11512. node = materialAnisotropyVector;
  11513. }
  11514. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  11515. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  11516. if ( material.iridescenceThicknessMap ) {
  11517. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  11518. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  11519. } else {
  11520. node = iridescenceThicknessMaximum;
  11521. }
  11522. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11523. const transmissionNode = this.getFloat( scope );
  11524. if ( material.transmissionMap ) {
  11525. node = transmissionNode.mul( this.getTexture( scope ).r );
  11526. } else {
  11527. node = transmissionNode;
  11528. }
  11529. } else if ( scope === MaterialNode.THICKNESS ) {
  11530. const thicknessNode = this.getFloat( scope );
  11531. if ( material.thicknessMap ) {
  11532. node = thicknessNode.mul( this.getTexture( scope ).g );
  11533. } else {
  11534. node = thicknessNode;
  11535. }
  11536. } else if ( scope === MaterialNode.IOR ) {
  11537. node = this.getFloat( scope );
  11538. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11539. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11540. } else if ( scope === MaterialNode.AO ) {
  11541. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11542. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11543. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11544. } else {
  11545. const outputType = this.getNodeType( builder );
  11546. node = this.getCache( scope, outputType );
  11547. }
  11548. return node;
  11549. }
  11550. }
  11551. MaterialNode.ALPHA_TEST = 'alphaTest';
  11552. MaterialNode.COLOR = 'color';
  11553. MaterialNode.OPACITY = 'opacity';
  11554. MaterialNode.SHININESS = 'shininess';
  11555. MaterialNode.SPECULAR = 'specular';
  11556. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11557. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11558. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11559. MaterialNode.REFLECTIVITY = 'reflectivity';
  11560. MaterialNode.ROUGHNESS = 'roughness';
  11561. MaterialNode.METALNESS = 'metalness';
  11562. MaterialNode.NORMAL = 'normal';
  11563. MaterialNode.CLEARCOAT = 'clearcoat';
  11564. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11565. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11566. MaterialNode.EMISSIVE = 'emissive';
  11567. MaterialNode.ROTATION = 'rotation';
  11568. MaterialNode.SHEEN = 'sheen';
  11569. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11570. MaterialNode.ANISOTROPY = 'anisotropy';
  11571. MaterialNode.IRIDESCENCE = 'iridescence';
  11572. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11573. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11574. MaterialNode.IOR = 'ior';
  11575. MaterialNode.TRANSMISSION = 'transmission';
  11576. MaterialNode.THICKNESS = 'thickness';
  11577. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11578. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11579. MaterialNode.LINE_SCALE = 'scale';
  11580. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11581. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11582. MaterialNode.LINE_WIDTH = 'linewidth';
  11583. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11584. MaterialNode.POINT_SIZE = 'size';
  11585. MaterialNode.DISPERSION = 'dispersion';
  11586. MaterialNode.LIGHT_MAP = 'light';
  11587. MaterialNode.AO = 'ao';
  11588. /**
  11589. * TSL object that represents alpha test of the current material.
  11590. *
  11591. * @tsl
  11592. * @type {Node<float>}
  11593. */
  11594. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11595. /**
  11596. * TSL object that represents the diffuse color of the current material.
  11597. * The value is composed via `color` * `map`.
  11598. *
  11599. * @tsl
  11600. * @type {Node<vec3>}
  11601. */
  11602. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11603. /**
  11604. * TSL object that represents the shininess of the current material.
  11605. *
  11606. * @tsl
  11607. * @type {Node<float>}
  11608. */
  11609. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11610. /**
  11611. * TSL object that represents the emissive color of the current material.
  11612. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11613. *
  11614. * @tsl
  11615. * @type {Node<vec3>}
  11616. */
  11617. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  11618. /**
  11619. * TSL object that represents the opacity of the current material.
  11620. * The value is composed via `opacity` * `alphaMap`.
  11621. *
  11622. * @tsl
  11623. * @type {Node<float>}
  11624. */
  11625. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  11626. /**
  11627. * TSL object that represents the specular of the current material.
  11628. *
  11629. * @tsl
  11630. * @type {Node<vec3>}
  11631. */
  11632. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  11633. /**
  11634. * TSL object that represents the specular intensity of the current material.
  11635. * The value is composed via `specularIntensity` * `specularMap.a`.
  11636. *
  11637. * @tsl
  11638. * @type {Node<float>}
  11639. */
  11640. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  11641. /**
  11642. * TSL object that represents the specular color of the current material.
  11643. * The value is composed via `specularColor` * `specularMap.rgb`.
  11644. *
  11645. * @tsl
  11646. * @type {Node<vec3>}
  11647. */
  11648. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  11649. /**
  11650. * TSL object that represents the specular strength of the current material.
  11651. * The value is composed via `specularMap.r`.
  11652. *
  11653. * @tsl
  11654. * @type {Node<float>}
  11655. */
  11656. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  11657. /**
  11658. * TSL object that represents the reflectivity of the current material.
  11659. *
  11660. * @tsl
  11661. * @type {Node<float>}
  11662. */
  11663. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  11664. /**
  11665. * TSL object that represents the roughness of the current material.
  11666. * The value is composed via `roughness` * `roughnessMap.g`.
  11667. *
  11668. * @tsl
  11669. * @type {Node<float>}
  11670. */
  11671. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  11672. /**
  11673. * TSL object that represents the metalness of the current material.
  11674. * The value is composed via `metalness` * `metalnessMap.b`.
  11675. *
  11676. * @tsl
  11677. * @type {Node<float>}
  11678. */
  11679. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  11680. /**
  11681. * TSL object that represents the normal of the current material.
  11682. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  11683. *
  11684. * @tsl
  11685. * @type {Node<vec3>}
  11686. */
  11687. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11688. /**
  11689. * TSL object that represents the clearcoat of the current material.
  11690. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11691. *
  11692. * @tsl
  11693. * @type {Node<float>}
  11694. */
  11695. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11696. /**
  11697. * TSL object that represents the clearcoat roughness of the current material.
  11698. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11699. *
  11700. * @tsl
  11701. * @type {Node<float>}
  11702. */
  11703. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11704. /**
  11705. * TSL object that represents the clearcoat normal of the current material.
  11706. * The value will be either `clearcoatNormalMap` or `normalView`.
  11707. *
  11708. * @tsl
  11709. * @type {Node<vec3>}
  11710. */
  11711. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  11712. /**
  11713. * TSL object that represents the rotation of the current sprite material.
  11714. *
  11715. * @tsl
  11716. * @type {Node<float>}
  11717. */
  11718. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  11719. /**
  11720. * TSL object that represents the sheen color of the current material.
  11721. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  11722. *
  11723. * @tsl
  11724. * @type {Node<vec3>}
  11725. */
  11726. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  11727. /**
  11728. * TSL object that represents the sheen roughness of the current material.
  11729. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  11730. *
  11731. * @tsl
  11732. * @type {Node<float>}
  11733. */
  11734. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  11735. /**
  11736. * TSL object that represents the anisotropy of the current material.
  11737. *
  11738. * @tsl
  11739. * @type {Node<vec2>}
  11740. */
  11741. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  11742. /**
  11743. * TSL object that represents the iridescence of the current material.
  11744. *
  11745. * @tsl
  11746. * @type {Node<float>}
  11747. */
  11748. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  11749. /**
  11750. * TSL object that represents the iridescence IOR of the current material.
  11751. *
  11752. * @tsl
  11753. * @type {Node<float>}
  11754. */
  11755. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  11756. /**
  11757. * TSL object that represents the iridescence thickness of the current material.
  11758. *
  11759. * @tsl
  11760. * @type {Node<float>}
  11761. */
  11762. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  11763. /**
  11764. * TSL object that represents the transmission of the current material.
  11765. * The value is composed via `transmission` * `transmissionMap.r`.
  11766. *
  11767. * @tsl
  11768. * @type {Node<float>}
  11769. */
  11770. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  11771. /**
  11772. * TSL object that represents the thickness of the current material.
  11773. * The value is composed via `thickness` * `thicknessMap.g`.
  11774. *
  11775. * @tsl
  11776. * @type {Node<float>}
  11777. */
  11778. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  11779. /**
  11780. * TSL object that represents the IOR of the current material.
  11781. *
  11782. * @tsl
  11783. * @type {Node<float>}
  11784. */
  11785. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  11786. /**
  11787. * TSL object that represents the attenuation distance of the current material.
  11788. *
  11789. * @tsl
  11790. * @type {Node<float>}
  11791. */
  11792. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  11793. /**
  11794. * TSL object that represents the attenuation color of the current material.
  11795. *
  11796. * @tsl
  11797. * @type {Node<vec3>}
  11798. */
  11799. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  11800. /**
  11801. * TSL object that represents the scale of the current dashed line material.
  11802. *
  11803. * @tsl
  11804. * @type {Node<float>}
  11805. */
  11806. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  11807. /**
  11808. * TSL object that represents the dash size of the current dashed line material.
  11809. *
  11810. * @tsl
  11811. * @type {Node<float>}
  11812. */
  11813. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  11814. /**
  11815. * TSL object that represents the gap size of the current dashed line material.
  11816. *
  11817. * @tsl
  11818. * @type {Node<float>}
  11819. */
  11820. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  11821. /**
  11822. * TSL object that represents the line width of the current line material.
  11823. *
  11824. * @tsl
  11825. * @type {Node<float>}
  11826. */
  11827. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  11828. /**
  11829. * TSL object that represents the dash offset of the current line material.
  11830. *
  11831. * @tsl
  11832. * @type {Node<float>}
  11833. */
  11834. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11835. /**
  11836. * TSL object that represents the point size of the current points material.
  11837. *
  11838. * @tsl
  11839. * @type {Node<float>}
  11840. */
  11841. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11842. /**
  11843. * TSL object that represents the dispersion of the current material.
  11844. *
  11845. * @tsl
  11846. * @type {Node<float>}
  11847. */
  11848. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11849. /**
  11850. * TSL object that represents the light map of the current material.
  11851. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11852. *
  11853. * @tsl
  11854. * @type {Node<vec3>}
  11855. */
  11856. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11857. /**
  11858. * TSL object that represents the ambient occlusion map of the current material.
  11859. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11860. *
  11861. * @tsl
  11862. * @type {Node<float>}
  11863. */
  11864. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11865. /**
  11866. * TSL object that represents the anisotropy vector of the current material.
  11867. *
  11868. * @tsl
  11869. * @type {Node<vec2>}
  11870. */
  11871. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11872. return frame.material;
  11873. } ).onRenderUpdate( function ( { material } ) {
  11874. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11875. } );
  11876. /**
  11877. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11878. *
  11879. * @tsl
  11880. * @type {VaryingNode<vec4>}
  11881. */
  11882. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11883. return builder.context.setupModelViewProjection();
  11884. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11885. /**
  11886. * This class enables element access on instances of {@link StorageBufferNode}.
  11887. * In most cases, it is indirectly used when accessing elements with the
  11888. * {@link StorageBufferNode#element} method.
  11889. *
  11890. * ```js
  11891. * const position = positionStorage.element( instanceIndex );
  11892. * ```
  11893. *
  11894. * @augments ArrayElementNode
  11895. */
  11896. class StorageArrayElementNode extends ArrayElementNode {
  11897. static get type() {
  11898. return 'StorageArrayElementNode';
  11899. }
  11900. /**
  11901. * Constructs storage buffer element node.
  11902. *
  11903. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11904. * @param {Node} indexNode - The index node that defines the element access.
  11905. */
  11906. constructor( storageBufferNode, indexNode ) {
  11907. super( storageBufferNode, indexNode );
  11908. /**
  11909. * This flag can be used for type testing.
  11910. *
  11911. * @type {boolean}
  11912. * @readonly
  11913. * @default true
  11914. */
  11915. this.isStorageArrayElementNode = true;
  11916. }
  11917. /**
  11918. * The storage buffer node.
  11919. *
  11920. * @param {Node} value
  11921. * @type {StorageBufferNode}
  11922. */
  11923. set storageBufferNode( value ) {
  11924. this.node = value;
  11925. }
  11926. get storageBufferNode() {
  11927. return this.node;
  11928. }
  11929. getMemberType( builder, name ) {
  11930. const structTypeNode = this.storageBufferNode.structTypeNode;
  11931. if ( structTypeNode ) {
  11932. return structTypeNode.getMemberType( builder, name );
  11933. }
  11934. return 'void';
  11935. }
  11936. setup( builder ) {
  11937. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11938. if ( this.node.isPBO === true ) {
  11939. builder.setupPBO( this.node );
  11940. }
  11941. }
  11942. return super.setup( builder );
  11943. }
  11944. generate( builder, output ) {
  11945. let snippet;
  11946. const isAssignContext = builder.context.assign;
  11947. //
  11948. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11949. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11950. snippet = builder.generatePBO( this );
  11951. } else {
  11952. snippet = this.node.build( builder );
  11953. }
  11954. } else {
  11955. snippet = super.generate( builder );
  11956. }
  11957. if ( isAssignContext !== true ) {
  11958. const type = this.getNodeType( builder );
  11959. snippet = builder.format( snippet, type, output );
  11960. }
  11961. return snippet;
  11962. }
  11963. }
  11964. /**
  11965. * TSL function for creating a storage element node.
  11966. *
  11967. * @tsl
  11968. * @function
  11969. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11970. * @param {Node} indexNode - The index node that defines the element access.
  11971. * @returns {StorageArrayElementNode}
  11972. */
  11973. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11974. /**
  11975. * This node is used in context of compute shaders and allows to define a
  11976. * storage buffer for data. A typical workflow is to create instances of
  11977. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11978. * setup up a compute shader that writes into the buffers and then convert
  11979. * the storage buffers to attribute nodes for rendering.
  11980. *
  11981. * ```js
  11982. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11983. *
  11984. * const computeInit = Fn( () => { // the compute shader
  11985. *
  11986. * const position = positionBuffer.element( instanceIndex );
  11987. *
  11988. * // compute position data
  11989. *
  11990. * position.x = 1;
  11991. * position.y = 1;
  11992. * position.z = 1;
  11993. *
  11994. * } )().compute( particleCount );
  11995. *
  11996. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11997. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11998. *
  11999. * renderer.computeAsync( computeInit );
  12000. *
  12001. * ```
  12002. *
  12003. * @augments BufferNode
  12004. */
  12005. class StorageBufferNode extends BufferNode {
  12006. static get type() {
  12007. return 'StorageBufferNode';
  12008. }
  12009. /**
  12010. * Constructs a new storage buffer node.
  12011. *
  12012. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12013. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  12014. * @param {number} [bufferCount=0] - The buffer count.
  12015. */
  12016. constructor( value, bufferType = null, bufferCount = 0 ) {
  12017. let nodeType, structTypeNode = null;
  12018. if ( bufferType && bufferType.isStruct ) {
  12019. nodeType = 'struct';
  12020. structTypeNode = bufferType.layout;
  12021. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  12022. bufferCount = value.count;
  12023. }
  12024. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  12025. nodeType = getTypeFromLength( value.itemSize );
  12026. bufferCount = value.count;
  12027. } else {
  12028. nodeType = bufferType;
  12029. }
  12030. super( value, nodeType, bufferCount );
  12031. /**
  12032. * This flag can be used for type testing.
  12033. *
  12034. * @type {boolean}
  12035. * @readonly
  12036. * @default true
  12037. */
  12038. this.isStorageBufferNode = true;
  12039. /**
  12040. * The buffer struct type.
  12041. *
  12042. * @type {?StructTypeNode}
  12043. * @default null
  12044. */
  12045. this.structTypeNode = structTypeNode;
  12046. /**
  12047. * The access type of the texture node.
  12048. *
  12049. * @type {string}
  12050. * @default 'readWrite'
  12051. */
  12052. this.access = NodeAccess.READ_WRITE;
  12053. /**
  12054. * Whether the node is atomic or not.
  12055. *
  12056. * @type {boolean}
  12057. * @default false
  12058. */
  12059. this.isAtomic = false;
  12060. /**
  12061. * Whether the node represents a PBO or not.
  12062. * Only relevant for WebGL.
  12063. *
  12064. * @type {boolean}
  12065. * @default false
  12066. */
  12067. this.isPBO = false;
  12068. /**
  12069. * A reference to the internal buffer attribute node.
  12070. *
  12071. * @private
  12072. * @type {?BufferAttributeNode}
  12073. * @default null
  12074. */
  12075. this._attribute = null;
  12076. /**
  12077. * A reference to the internal varying node.
  12078. *
  12079. * @private
  12080. * @type {?VaryingNode}
  12081. * @default null
  12082. */
  12083. this._varying = null;
  12084. /**
  12085. * `StorageBufferNode` sets this property to `true` by default.
  12086. *
  12087. * @type {boolean}
  12088. * @default true
  12089. */
  12090. this.global = true;
  12091. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  12092. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  12093. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  12094. else value.isStorageBufferAttribute = true;
  12095. }
  12096. }
  12097. /**
  12098. * This method is overwritten since the buffer data might be shared
  12099. * and thus the hash should be shared as well.
  12100. *
  12101. * @param {NodeBuilder} builder - The current node builder.
  12102. * @return {string} The hash.
  12103. */
  12104. getHash( builder ) {
  12105. if ( this.bufferCount === 0 ) {
  12106. let bufferData = builder.globalCache.getData( this.value );
  12107. if ( bufferData === undefined ) {
  12108. bufferData = {
  12109. node: this
  12110. };
  12111. builder.globalCache.setData( this.value, bufferData );
  12112. }
  12113. return bufferData.node.uuid;
  12114. }
  12115. return this.uuid;
  12116. }
  12117. /**
  12118. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  12119. *
  12120. * @param {NodeBuilder} builder - The current node builder.
  12121. * @return {string} The input type.
  12122. */
  12123. getInputType( /*builder*/ ) {
  12124. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  12125. }
  12126. /**
  12127. * Enables element access with the given index node.
  12128. *
  12129. * @param {IndexNode} indexNode - The index node.
  12130. * @return {StorageArrayElementNode} A node representing the element access.
  12131. */
  12132. element( indexNode ) {
  12133. return storageElement( this, indexNode );
  12134. }
  12135. /**
  12136. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  12137. *
  12138. * @param {boolean} value - The value so set.
  12139. * @return {StorageBufferNode} A reference to this node.
  12140. */
  12141. setPBO( value ) {
  12142. this.isPBO = value;
  12143. return this;
  12144. }
  12145. /**
  12146. * Returns the `isPBO` value.
  12147. *
  12148. * @return {boolean} Whether the node represents a PBO or not.
  12149. */
  12150. getPBO() {
  12151. return this.isPBO;
  12152. }
  12153. /**
  12154. * Defines the node access.
  12155. *
  12156. * @param {string} value - The node access.
  12157. * @return {StorageBufferNode} A reference to this node.
  12158. */
  12159. setAccess( value ) {
  12160. this.access = value;
  12161. return this;
  12162. }
  12163. /**
  12164. * Convenience method for configuring a read-only node access.
  12165. *
  12166. * @return {StorageBufferNode} A reference to this node.
  12167. */
  12168. toReadOnly() {
  12169. return this.setAccess( NodeAccess.READ_ONLY );
  12170. }
  12171. /**
  12172. * Defines whether the node is atomic or not.
  12173. *
  12174. * @param {boolean} value - The atomic flag.
  12175. * @return {StorageBufferNode} A reference to this node.
  12176. */
  12177. setAtomic( value ) {
  12178. this.isAtomic = value;
  12179. return this;
  12180. }
  12181. /**
  12182. * Convenience method for making this node atomic.
  12183. *
  12184. * @return {StorageBufferNode} A reference to this node.
  12185. */
  12186. toAtomic() {
  12187. return this.setAtomic( true );
  12188. }
  12189. /**
  12190. * Returns attribute data for this storage buffer node.
  12191. *
  12192. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  12193. */
  12194. getAttributeData() {
  12195. if ( this._attribute === null ) {
  12196. this._attribute = bufferAttribute( this.value );
  12197. this._varying = varying( this._attribute );
  12198. }
  12199. return {
  12200. attribute: this._attribute,
  12201. varying: this._varying
  12202. };
  12203. }
  12204. /**
  12205. * This method is overwritten since the node type from the availability of storage buffers
  12206. * and the attribute data.
  12207. *
  12208. * @param {NodeBuilder} builder - The current node builder.
  12209. * @return {string} The node type.
  12210. */
  12211. getNodeType( builder ) {
  12212. if ( this.structTypeNode !== null ) {
  12213. return this.structTypeNode.getNodeType( builder );
  12214. }
  12215. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12216. return super.getNodeType( builder );
  12217. }
  12218. const { attribute } = this.getAttributeData();
  12219. return attribute.getNodeType( builder );
  12220. }
  12221. /**
  12222. * Returns the type of a member of the struct.
  12223. *
  12224. * @param {NodeBuilder} builder - The current node builder.
  12225. * @param {string} name - The name of the member.
  12226. * @return {string} The type of the member.
  12227. */
  12228. getMemberType( builder, name ) {
  12229. if ( this.structTypeNode !== null ) {
  12230. return this.structTypeNode.getMemberType( builder, name );
  12231. }
  12232. return 'void';
  12233. }
  12234. /**
  12235. * Generates the code snippet of the storage buffer node.
  12236. *
  12237. * @param {NodeBuilder} builder - The current node builder.
  12238. * @return {string} The generated code snippet.
  12239. */
  12240. generate( builder ) {
  12241. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12242. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12243. return super.generate( builder );
  12244. }
  12245. const { attribute, varying } = this.getAttributeData();
  12246. const output = varying.build( builder );
  12247. builder.registerTransform( output, attribute );
  12248. return output;
  12249. }
  12250. }
  12251. /**
  12252. * TSL function for creating a storage buffer node.
  12253. *
  12254. * @tsl
  12255. * @function
  12256. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12257. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12258. * @param {number} [count=0] - The buffer count.
  12259. * @returns {StorageBufferNode}
  12260. */
  12261. const storage = ( value, type = null, count = 0 ) => new StorageBufferNode( value, type, count );
  12262. /**
  12263. * This class represents shader indices of different types. The following predefined node
  12264. * objects cover frequent use cases:
  12265. *
  12266. * - `vertexIndex`: The index of a vertex within a mesh.
  12267. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  12268. * - `drawIndex`: The index of a draw call.
  12269. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  12270. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  12271. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  12272. *
  12273. * @augments Node
  12274. */
  12275. class IndexNode extends Node {
  12276. static get type() {
  12277. return 'IndexNode';
  12278. }
  12279. /**
  12280. * Constructs a new index node.
  12281. *
  12282. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  12283. */
  12284. constructor( scope ) {
  12285. super( 'uint' );
  12286. /**
  12287. * The scope of the index node.
  12288. *
  12289. * @type {string}
  12290. */
  12291. this.scope = scope;
  12292. /**
  12293. * This flag can be used for type testing.
  12294. *
  12295. * @type {boolean}
  12296. * @readonly
  12297. * @default true
  12298. */
  12299. this.isIndexNode = true;
  12300. }
  12301. generate( builder ) {
  12302. const nodeType = this.getNodeType( builder );
  12303. const scope = this.scope;
  12304. let propertyName;
  12305. if ( scope === IndexNode.VERTEX ) {
  12306. propertyName = builder.getVertexIndex();
  12307. } else if ( scope === IndexNode.INSTANCE ) {
  12308. propertyName = builder.getInstanceIndex();
  12309. } else if ( scope === IndexNode.DRAW ) {
  12310. propertyName = builder.getDrawIndex();
  12311. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  12312. propertyName = builder.getInvocationLocalIndex();
  12313. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  12314. propertyName = builder.getInvocationSubgroupIndex();
  12315. } else if ( scope === IndexNode.SUBGROUP ) {
  12316. propertyName = builder.getSubgroupIndex();
  12317. } else {
  12318. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  12319. }
  12320. let output;
  12321. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  12322. output = propertyName;
  12323. } else {
  12324. const nodeVarying = varying( this );
  12325. output = nodeVarying.build( builder, nodeType );
  12326. }
  12327. return output;
  12328. }
  12329. }
  12330. IndexNode.VERTEX = 'vertex';
  12331. IndexNode.INSTANCE = 'instance';
  12332. IndexNode.SUBGROUP = 'subgroup';
  12333. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  12334. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  12335. IndexNode.DRAW = 'draw';
  12336. /**
  12337. * TSL object that represents the index of a vertex within a mesh.
  12338. *
  12339. * @tsl
  12340. * @type {IndexNode}
  12341. */
  12342. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  12343. /**
  12344. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  12345. *
  12346. * @tsl
  12347. * @type {IndexNode}
  12348. */
  12349. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  12350. /**
  12351. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  12352. *
  12353. * @tsl
  12354. * @type {IndexNode}
  12355. */
  12356. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  12357. /**
  12358. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  12359. *
  12360. * @tsl
  12361. * @type {IndexNode}
  12362. */
  12363. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  12364. /**
  12365. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  12366. *
  12367. * @tsl
  12368. * @type {IndexNode}
  12369. */
  12370. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  12371. /**
  12372. * TSL object that represents the index of a draw call.
  12373. *
  12374. * @tsl
  12375. * @type {IndexNode}
  12376. */
  12377. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  12378. /**
  12379. * This node implements the vertex shader logic which is required
  12380. * when rendering 3D objects via instancing. The code makes sure
  12381. * vertex positions, normals and colors can be modified via instanced
  12382. * data.
  12383. *
  12384. * @augments Node
  12385. */
  12386. class InstanceNode extends Node {
  12387. static get type() {
  12388. return 'InstanceNode';
  12389. }
  12390. /**
  12391. * Constructs a new instance node.
  12392. *
  12393. * @param {number} count - The number of instances.
  12394. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12395. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12396. */
  12397. constructor( count, instanceMatrix, instanceColor = null ) {
  12398. super( 'void' );
  12399. /**
  12400. * The number of instances.
  12401. *
  12402. * @type {number}
  12403. */
  12404. this.count = count;
  12405. /**
  12406. * Instanced buffer attribute representing the transformation of instances.
  12407. *
  12408. * @type {InstancedBufferAttribute}
  12409. */
  12410. this.instanceMatrix = instanceMatrix;
  12411. /**
  12412. * Instanced buffer attribute representing the color of instances.
  12413. *
  12414. * @type {InstancedBufferAttribute}
  12415. */
  12416. this.instanceColor = instanceColor;
  12417. /**
  12418. * The node that represents the instance matrix data.
  12419. *
  12420. * @type {?Node}
  12421. */
  12422. this.instanceMatrixNode = null;
  12423. /**
  12424. * The node that represents the instance color data.
  12425. *
  12426. * @type {?Node}
  12427. * @default null
  12428. */
  12429. this.instanceColorNode = null;
  12430. /**
  12431. * The update type is set to `frame` since an update
  12432. * of instanced buffer data must be checked per frame.
  12433. *
  12434. * @type {string}
  12435. * @default 'frame'
  12436. */
  12437. this.updateType = NodeUpdateType.FRAME;
  12438. /**
  12439. * A reference to a buffer that is used by `instanceMatrixNode`.
  12440. *
  12441. * @type {?InstancedInterleavedBuffer}
  12442. */
  12443. this.buffer = null;
  12444. /**
  12445. * A reference to a buffer that is used by `instanceColorNode`.
  12446. *
  12447. * @type {?InstancedBufferAttribute}
  12448. */
  12449. this.bufferColor = null;
  12450. /**
  12451. * The previous instance matrices. Required for computing motion vectors.
  12452. *
  12453. * @type {?Node}
  12454. * @default null
  12455. */
  12456. this.previousInstanceMatrixNode = null;
  12457. }
  12458. /**
  12459. * Tracks whether the matrix data is provided via a storage buffer.
  12460. *
  12461. * @type {boolean}
  12462. */
  12463. get isStorageMatrix() {
  12464. const { instanceMatrix } = this;
  12465. return instanceMatrix && instanceMatrix.isStorageInstancedBufferAttribute === true;
  12466. }
  12467. /**
  12468. * Tracks whether the color data is provided via a storage buffer.
  12469. *
  12470. * @type {boolean}
  12471. */
  12472. get isStorageColor() {
  12473. const { instanceColor } = this;
  12474. return instanceColor && instanceColor.isStorageInstancedBufferAttribute === true;
  12475. }
  12476. /**
  12477. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12478. * to predefined node variables for accumulation. That follows the same patterns
  12479. * like with morph and skinning nodes.
  12480. *
  12481. * @param {NodeBuilder} builder - The current node builder.
  12482. */
  12483. setup( builder ) {
  12484. let { instanceMatrixNode, instanceColorNode } = this;
  12485. // instance matrix
  12486. if ( instanceMatrixNode === null ) {
  12487. instanceMatrixNode = this._createInstanceMatrixNode( true, builder );
  12488. this.instanceMatrixNode = instanceMatrixNode;
  12489. }
  12490. // instance color
  12491. const { instanceColor, isStorageColor } = this;
  12492. if ( instanceColor && instanceColorNode === null ) {
  12493. if ( isStorageColor ) {
  12494. instanceColorNode = storage( instanceColor, 'vec3', Math.max( instanceColor.count, 1 ) ).element( instanceIndex );
  12495. } else {
  12496. const bufferAttribute = new InstancedBufferAttribute( instanceColor.array, 3 );
  12497. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12498. this.bufferColor = bufferAttribute;
  12499. instanceColorNode = vec3( bufferFn( bufferAttribute, 'vec3', 3, 0 ) );
  12500. }
  12501. this.instanceColorNode = instanceColorNode;
  12502. }
  12503. // POSITION
  12504. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  12505. positionLocal.assign( instancePosition );
  12506. if ( builder.needsPreviousData() ) {
  12507. positionPrevious.assign( this.getPreviousInstancedPosition( builder ) );
  12508. }
  12509. // NORMAL
  12510. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12511. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  12512. // ASSIGNS
  12513. normalLocal.assign( instanceNormal );
  12514. }
  12515. // COLOR
  12516. if ( this.instanceColorNode !== null ) {
  12517. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  12518. }
  12519. }
  12520. /**
  12521. * Checks if the internal buffers require an update.
  12522. *
  12523. * @param {NodeFrame} frame - The current node frame.
  12524. */
  12525. update( frame ) {
  12526. if ( this.buffer !== null && this.isStorageMatrix !== true ) {
  12527. this.buffer.clearUpdateRanges();
  12528. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  12529. // update version if necessary
  12530. if ( this.instanceMatrix.version !== this.buffer.version ) {
  12531. this.buffer.version = this.instanceMatrix.version;
  12532. }
  12533. }
  12534. if ( this.instanceColor && this.bufferColor !== null && this.isStorageColor !== true ) {
  12535. this.bufferColor.clearUpdateRanges();
  12536. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  12537. if ( this.instanceColor.version !== this.bufferColor.version ) {
  12538. this.bufferColor.version = this.instanceColor.version;
  12539. }
  12540. }
  12541. if ( this.previousInstanceMatrixNode !== null ) {
  12542. frame.object.previousInstanceMatrix.array.set( this.instanceMatrix.array );
  12543. }
  12544. }
  12545. /**
  12546. * Computes the transformed/instanced vertex position of the previous frame.
  12547. *
  12548. * @param {NodeBuilder} builder - The current node builder.
  12549. * @return {Node<vec3>} The instanced position from the previous frame.
  12550. */
  12551. getPreviousInstancedPosition( builder ) {
  12552. const instancedMesh = builder.object;
  12553. if ( this.previousInstanceMatrixNode === null ) {
  12554. instancedMesh.previousInstanceMatrix = this.instanceMatrix.clone();
  12555. this.previousInstanceMatrixNode = this._createInstanceMatrixNode( false, builder );
  12556. }
  12557. return this.previousInstanceMatrixNode.mul( positionPrevious ).xyz;
  12558. }
  12559. /**
  12560. * Creates a node representing the instance matrix data.
  12561. *
  12562. * @private
  12563. * @param {boolean} assignBuffer - Whether the created interleaved buffer should be assigned to the `buffer` member or not.
  12564. * @param {NodeBuilder} builder - A reference to the current node builder.
  12565. * @return {Node} The instance matrix node.
  12566. */
  12567. _createInstanceMatrixNode( assignBuffer, builder ) {
  12568. let instanceMatrixNode;
  12569. const { instanceMatrix } = this;
  12570. const { count } = instanceMatrix;
  12571. if ( this.isStorageMatrix ) {
  12572. instanceMatrixNode = storage( instanceMatrix, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12573. } else {
  12574. const uniformBufferSize = count * 16 * 4; // count * 16 components * 4 bytes (float)
  12575. if ( uniformBufferSize <= builder.getUniformBufferLimit() ) {
  12576. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12577. } else {
  12578. const interleaved = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  12579. if ( assignBuffer === true ) this.buffer = interleaved;
  12580. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12581. const instanceBuffers = [
  12582. bufferFn( interleaved, 'vec4', 16, 0 ),
  12583. bufferFn( interleaved, 'vec4', 16, 4 ),
  12584. bufferFn( interleaved, 'vec4', 16, 8 ),
  12585. bufferFn( interleaved, 'vec4', 16, 12 )
  12586. ];
  12587. instanceMatrixNode = mat4( ...instanceBuffers );
  12588. }
  12589. }
  12590. return instanceMatrixNode;
  12591. }
  12592. }
  12593. /**
  12594. * TSL function for creating an instance node.
  12595. *
  12596. * @tsl
  12597. * @function
  12598. * @param {number} count - The number of instances.
  12599. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12600. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12601. * @returns {InstanceNode}
  12602. */
  12603. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  12604. /**
  12605. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  12606. * It allows an easier setup of the instance node.
  12607. *
  12608. * @augments InstanceNode
  12609. */
  12610. class InstancedMeshNode extends InstanceNode {
  12611. static get type() {
  12612. return 'InstancedMeshNode';
  12613. }
  12614. /**
  12615. * Constructs a new instanced mesh node.
  12616. *
  12617. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  12618. */
  12619. constructor( instancedMesh ) {
  12620. const { count, instanceMatrix, instanceColor } = instancedMesh;
  12621. super( count, instanceMatrix, instanceColor );
  12622. /**
  12623. * A reference to the instanced mesh.
  12624. *
  12625. * @type {InstancedMesh}
  12626. */
  12627. this.instancedMesh = instancedMesh;
  12628. }
  12629. }
  12630. /**
  12631. * TSL function for creating an instanced mesh node.
  12632. *
  12633. * @tsl
  12634. * @function
  12635. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  12636. * @returns {InstancedMeshNode}
  12637. */
  12638. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  12639. /**
  12640. * This node implements the vertex shader logic which is required
  12641. * when rendering 3D objects via batching. `BatchNode` must be used
  12642. * with instances of {@link BatchedMesh}.
  12643. *
  12644. * @augments Node
  12645. */
  12646. class BatchNode extends Node {
  12647. static get type() {
  12648. return 'BatchNode';
  12649. }
  12650. /**
  12651. * Constructs a new batch node.
  12652. *
  12653. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12654. */
  12655. constructor( batchMesh ) {
  12656. super( 'void' );
  12657. /**
  12658. * A reference to batched mesh.
  12659. *
  12660. * @type {BatchedMesh}
  12661. */
  12662. this.batchMesh = batchMesh;
  12663. /**
  12664. * The batching index node.
  12665. *
  12666. * @type {?IndexNode}
  12667. * @default null
  12668. */
  12669. this.batchingIdNode = null;
  12670. }
  12671. /**
  12672. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12673. * to predefined node variables for accumulation. That follows the same patterns
  12674. * like with morph and skinning nodes.
  12675. *
  12676. * @param {NodeBuilder} builder - The current node builder.
  12677. */
  12678. setup( builder ) {
  12679. if ( this.batchingIdNode === null ) {
  12680. if ( builder.getDrawIndex() === null ) {
  12681. this.batchingIdNode = instanceIndex;
  12682. } else {
  12683. this.batchingIdNode = drawIndex;
  12684. }
  12685. }
  12686. const getIndirectIndex = Fn( ( [ id ] ) => {
  12687. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x ).toConst();
  12688. const x = int( id ).mod( size ).toConst();
  12689. const y = int( id ).div( size ).toConst();
  12690. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  12691. } ).setLayout( {
  12692. name: 'getIndirectIndex',
  12693. type: 'uint',
  12694. inputs: [
  12695. { name: 'id', type: 'int' }
  12696. ]
  12697. } );
  12698. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  12699. const matricesTexture = this.batchMesh._matricesTexture;
  12700. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x ).toConst();
  12701. const j = float( indirectId ).mul( 4 ).toInt().toConst();
  12702. const x = j.mod( size ).toConst();
  12703. const y = j.div( size ).toConst();
  12704. const batchingMatrix = mat4(
  12705. textureLoad( matricesTexture, ivec2( x, y ) ),
  12706. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  12707. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  12708. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  12709. );
  12710. const colorsTexture = this.batchMesh._colorsTexture;
  12711. if ( colorsTexture !== null ) {
  12712. const getBatchingColor = Fn( ( [ id ] ) => {
  12713. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x ).toConst();
  12714. const j = id;
  12715. const x = j.mod( size ).toConst();
  12716. const y = j.div( size ).toConst();
  12717. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  12718. } ).setLayout( {
  12719. name: 'getBatchingColor',
  12720. type: 'vec3',
  12721. inputs: [
  12722. { name: 'id', type: 'int' }
  12723. ]
  12724. } );
  12725. const color = getBatchingColor( indirectId );
  12726. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  12727. }
  12728. const bm = mat3( batchingMatrix );
  12729. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  12730. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  12731. const batchingNormal = bm.mul( transformedNormal ).xyz;
  12732. normalLocal.assign( batchingNormal );
  12733. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12734. tangentLocal.mulAssign( bm );
  12735. }
  12736. }
  12737. }
  12738. /**
  12739. * TSL function for creating a batch node.
  12740. *
  12741. * @tsl
  12742. * @function
  12743. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12744. * @returns {BatchNode}
  12745. */
  12746. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  12747. const _frameId = new WeakMap();
  12748. /**
  12749. * This node implements the vertex transformation shader logic which is required
  12750. * for skinning/skeletal animation.
  12751. *
  12752. * @augments Node
  12753. */
  12754. class SkinningNode extends Node {
  12755. static get type() {
  12756. return 'SkinningNode';
  12757. }
  12758. /**
  12759. * Constructs a new skinning node.
  12760. *
  12761. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12762. */
  12763. constructor( skinnedMesh ) {
  12764. super( 'void' );
  12765. /**
  12766. * The skinned mesh.
  12767. *
  12768. * @type {SkinnedMesh}
  12769. */
  12770. this.skinnedMesh = skinnedMesh;
  12771. /**
  12772. * The update type overwritten since skinning nodes are updated per object.
  12773. *
  12774. * @type {string}
  12775. */
  12776. this.updateType = NodeUpdateType.OBJECT;
  12777. //
  12778. /**
  12779. * The skin index attribute.
  12780. *
  12781. * @type {AttributeNode}
  12782. */
  12783. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12784. /**
  12785. * The skin weight attribute.
  12786. *
  12787. * @type {AttributeNode}
  12788. */
  12789. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12790. /**
  12791. * The bind matrix node.
  12792. *
  12793. * @type {Node<mat4>}
  12794. */
  12795. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12796. /**
  12797. * The bind matrix inverse node.
  12798. *
  12799. * @type {Node<mat4>}
  12800. */
  12801. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12802. /**
  12803. * The bind matrices as a uniform buffer node.
  12804. *
  12805. * @type {Node}
  12806. */
  12807. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12808. /**
  12809. * The current vertex position in local space.
  12810. *
  12811. * @type {Node<vec3>}
  12812. */
  12813. this.positionNode = positionLocal;
  12814. /**
  12815. * The result of vertex position in local space.
  12816. *
  12817. * @type {Node<vec3>}
  12818. */
  12819. this.toPositionNode = positionLocal;
  12820. /**
  12821. * The previous bind matrices as a uniform buffer node.
  12822. * Required for computing motion vectors.
  12823. *
  12824. * @type {?Node}
  12825. * @default null
  12826. */
  12827. this.previousBoneMatricesNode = null;
  12828. }
  12829. /**
  12830. * Transforms the given vertex position via skinning.
  12831. *
  12832. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12833. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  12834. * @return {Node<vec3>} The transformed vertex position.
  12835. */
  12836. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  12837. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12838. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12839. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12840. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12841. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12842. // POSITION
  12843. const skinVertex = bindMatrixNode.mul( position );
  12844. const skinned = add(
  12845. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  12846. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  12847. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  12848. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  12849. );
  12850. return bindMatrixInverseNode.mul( skinned ).xyz;
  12851. }
  12852. /**
  12853. * Transforms the given vertex normal and tangent via skinning.
  12854. *
  12855. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12856. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  12857. * @param {Node<vec3>} [tangent=tangentLocal] - The vertex tangent in local space.
  12858. * @return {{skinNormal: Node<vec3>, skinTangent:Node<vec3>}} The transformed vertex normal and tangent.
  12859. */
  12860. getSkinnedNormalAndTangent( boneMatrices = this.boneMatricesNode, normal = normalLocal, tangent = tangentLocal ) {
  12861. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12862. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12863. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12864. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12865. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12866. // NORMAL and TANGENT
  12867. let skinMatrix = add(
  12868. skinWeightNode.x.mul( boneMatX ),
  12869. skinWeightNode.y.mul( boneMatY ),
  12870. skinWeightNode.z.mul( boneMatZ ),
  12871. skinWeightNode.w.mul( boneMatW )
  12872. );
  12873. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  12874. const skinNormal = skinMatrix.transformDirection( normal ).xyz;
  12875. const skinTangent = skinMatrix.transformDirection( tangent ).xyz;
  12876. return { skinNormal, skinTangent };
  12877. }
  12878. /**
  12879. * Computes the transformed/skinned vertex position of the previous frame.
  12880. *
  12881. * @param {NodeBuilder} builder - The current node builder.
  12882. * @return {Node<vec3>} The skinned position from the previous frame.
  12883. */
  12884. getPreviousSkinnedPosition( builder ) {
  12885. const skinnedMesh = builder.object;
  12886. if ( this.previousBoneMatricesNode === null ) {
  12887. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  12888. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12889. }
  12890. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12891. }
  12892. /**
  12893. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12894. *
  12895. * @param {NodeBuilder} builder - The current node builder.
  12896. * @return {Node<vec3>} The transformed vertex position.
  12897. */
  12898. setup( builder ) {
  12899. if ( builder.needsPreviousData() ) {
  12900. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12901. }
  12902. const skinPosition = this.getSkinnedPosition();
  12903. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12904. //
  12905. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12906. const { skinNormal, skinTangent } = this.getSkinnedNormalAndTangent();
  12907. normalLocal.assign( skinNormal );
  12908. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12909. tangentLocal.assign( skinTangent );
  12910. }
  12911. }
  12912. return skinPosition;
  12913. }
  12914. /**
  12915. * Generates the code snippet of the skinning node.
  12916. *
  12917. * @param {NodeBuilder} builder - The current node builder.
  12918. * @param {string} output - The current output.
  12919. * @return {string} The generated code snippet.
  12920. */
  12921. generate( builder, output ) {
  12922. if ( output !== 'void' ) {
  12923. return super.generate( builder, output );
  12924. }
  12925. }
  12926. /**
  12927. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12928. *
  12929. * @param {NodeFrame} frame - The current node frame.
  12930. */
  12931. update( frame ) {
  12932. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12933. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12934. _frameId.set( skeleton, frame.frameId );
  12935. if ( this.previousBoneMatricesNode !== null ) {
  12936. if ( skeleton.previousBoneMatrices === null ) {
  12937. // cloned skeletons miss "previousBoneMatrices" in their first updated
  12938. skeleton.previousBoneMatrices = new Float32Array( skeleton.boneMatrices );
  12939. }
  12940. skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12941. }
  12942. skeleton.update();
  12943. }
  12944. }
  12945. /**
  12946. * TSL function for creating a skinning node.
  12947. *
  12948. * @tsl
  12949. * @function
  12950. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12951. * @returns {SkinningNode}
  12952. */
  12953. const skinning = ( skinnedMesh ) => new SkinningNode( skinnedMesh );
  12954. /**
  12955. * TSL function for computing skinning.
  12956. *
  12957. * @tsl
  12958. * @function
  12959. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12960. * @param {Node<vec3>} [toPosition=null] - The target position.
  12961. * @returns {SkinningNode}
  12962. */
  12963. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12964. const node = new SkinningNode( skinnedMesh );
  12965. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12966. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12967. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12968. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12969. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12970. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12971. node.toPositionNode = toPosition;
  12972. return nodeObject( node );
  12973. };
  12974. /**
  12975. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12976. * ```js
  12977. * Loop( count, ( { i } ) => {
  12978. *
  12979. * } );
  12980. * ```
  12981. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12982. * ```js
  12983. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12984. *
  12985. * } );
  12986. *```
  12987. * Nested loops can be defined in a compacted form:
  12988. * ```js
  12989. * Loop( 10, 5, ( { i, j } ) => {
  12990. *
  12991. * } );
  12992. * ```
  12993. * Loops that should run backwards can be defined like so:
  12994. * ```js
  12995. * Loop( { start: 10 }, () => {} );
  12996. * ```
  12997. * It is possible to execute with boolean values, similar to the `while` syntax.
  12998. * ```js
  12999. * const value = float( 0 ).toVar();
  13000. *
  13001. * Loop( value.lessThan( 10 ), () => {
  13002. *
  13003. * value.addAssign( 1 );
  13004. *
  13005. * } );
  13006. * ```
  13007. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  13008. * @augments Node
  13009. */
  13010. class LoopNode extends Node {
  13011. static get type() {
  13012. return 'LoopNode';
  13013. }
  13014. /**
  13015. * Constructs a new loop node.
  13016. *
  13017. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  13018. */
  13019. constructor( params = [] ) {
  13020. super( 'void' );
  13021. this.params = params;
  13022. }
  13023. /**
  13024. * Returns a loop variable name based on an index. The pattern is
  13025. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  13026. *
  13027. * @param {number} index - The index.
  13028. * @return {string} The loop variable name.
  13029. */
  13030. getVarName( index ) {
  13031. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  13032. }
  13033. /**
  13034. * Returns properties about this node.
  13035. *
  13036. * @param {NodeBuilder} builder - The current node builder.
  13037. * @return {Object} The node properties.
  13038. */
  13039. getProperties( builder ) {
  13040. const properties = builder.getNodeProperties( this );
  13041. if ( properties.stackNode !== undefined ) return properties;
  13042. //
  13043. const inputs = {};
  13044. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  13045. const param = this.params[ i ];
  13046. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  13047. const type = ( param.isNode !== true && param.type ) || 'int';
  13048. inputs[ name ] = expression( name, type );
  13049. }
  13050. const stack = builder.addStack();
  13051. const fnCall = this.params[ this.params.length - 1 ]( inputs );
  13052. properties.returnsNode = fnCall.context( { nodeLoop: fnCall } );
  13053. properties.stackNode = stack;
  13054. const baseParam = this.params[ 0 ];
  13055. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  13056. const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs );
  13057. properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } );
  13058. }
  13059. builder.removeStack();
  13060. return properties;
  13061. }
  13062. setup( builder ) {
  13063. // setup properties
  13064. this.getProperties( builder );
  13065. if ( builder.fnCall ) {
  13066. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  13067. shaderNodeData.hasLoop = true;
  13068. }
  13069. }
  13070. generate( builder ) {
  13071. const properties = this.getProperties( builder );
  13072. const params = this.params;
  13073. const stackNode = properties.stackNode;
  13074. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  13075. const param = params[ i ];
  13076. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  13077. if ( param.isNode ) {
  13078. if ( param.getNodeType( builder ) === 'bool' ) {
  13079. isWhile = true;
  13080. type = 'bool';
  13081. end = param.build( builder, type );
  13082. } else {
  13083. type = 'int';
  13084. name = this.getVarName( i );
  13085. start = '0';
  13086. end = param.build( builder, type );
  13087. condition = '<';
  13088. }
  13089. } else {
  13090. type = param.type || 'int';
  13091. name = param.name || this.getVarName( i );
  13092. start = param.start;
  13093. end = param.end;
  13094. condition = param.condition;
  13095. update = param.update;
  13096. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  13097. else if ( start && start.isNode ) start = start.build( builder, type );
  13098. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  13099. else if ( end && end.isNode ) end = end.build( builder, type );
  13100. if ( start !== undefined && end === undefined ) {
  13101. start = start + ' - 1';
  13102. end = '0';
  13103. condition = '>=';
  13104. } else if ( end !== undefined && start === undefined ) {
  13105. start = '0';
  13106. condition = '<';
  13107. }
  13108. if ( condition === undefined ) {
  13109. if ( Number( start ) > Number( end ) ) {
  13110. condition = '>=';
  13111. } else {
  13112. condition = '<';
  13113. }
  13114. }
  13115. }
  13116. let loopSnippet;
  13117. if ( isWhile ) {
  13118. loopSnippet = `while ( ${ end } )`;
  13119. } else {
  13120. const internalParam = { start, end};
  13121. //
  13122. const startSnippet = internalParam.start;
  13123. const endSnippet = internalParam.end;
  13124. let updateSnippet;
  13125. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  13126. if ( update !== undefined && update !== null ) {
  13127. switch ( typeof update ) {
  13128. case 'function':
  13129. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  13130. const snippet = flow.code.replace( /\t|;/g, '' );
  13131. updateSnippet = snippet;
  13132. break;
  13133. case 'number':
  13134. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  13135. break;
  13136. case 'string':
  13137. updateSnippet = name + ' ' + update;
  13138. break;
  13139. default:
  13140. if ( update.isNode ) {
  13141. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  13142. } else {
  13143. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.', this.stackTrace );
  13144. updateSnippet = 'break /* invalid update */';
  13145. }
  13146. }
  13147. } else {
  13148. if ( type === 'int' || type === 'uint' ) {
  13149. update = condition.includes( '<' ) ? '++' : '--';
  13150. } else {
  13151. update = deltaOperator() + ' 1.';
  13152. }
  13153. updateSnippet = name + ' ' + update;
  13154. }
  13155. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  13156. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  13157. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  13158. }
  13159. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  13160. }
  13161. const stackSnippet = stackNode.build( builder, 'void' );
  13162. properties.returnsNode.build( builder, 'void' );
  13163. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  13164. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  13165. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  13166. }
  13167. builder.addFlowTab();
  13168. }
  13169. }
  13170. /**
  13171. * TSL function for creating a loop node.
  13172. *
  13173. * @tsl
  13174. * @function
  13175. * @param {...any} params - A list of parameters.
  13176. * @returns {LoopNode}
  13177. */
  13178. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  13179. /**
  13180. * TSL function for creating a `Continue()` expression.
  13181. *
  13182. * @tsl
  13183. * @function
  13184. * @returns {ExpressionNode}
  13185. */
  13186. const Continue = () => expression( 'continue' ).toStack();
  13187. /**
  13188. * TSL function for creating a `Break()` expression.
  13189. *
  13190. * @tsl
  13191. * @function
  13192. * @returns {ExpressionNode}
  13193. */
  13194. const Break = () => expression( 'break' ).toStack();
  13195. const _morphTextures = /*@__PURE__*/ new WeakMap();
  13196. const _morphVec4 = /*@__PURE__*/ new Vector4();
  13197. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  13198. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  13199. const y = texelIndex.div( width );
  13200. const x = texelIndex.sub( y.mul( width ) );
  13201. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  13202. return bufferAttrib.mul( influence );
  13203. } );
  13204. function getEntry( geometry ) {
  13205. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13206. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  13207. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  13208. // instead of using attributes, the WebGL 2 code path encodes morph targets
  13209. // into an array of data textures. Each layer represents a single morph target.
  13210. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13211. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13212. let entry = _morphTextures.get( geometry );
  13213. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  13214. if ( entry !== undefined ) entry.texture.dispose();
  13215. const morphTargets = geometry.morphAttributes.position || [];
  13216. const morphNormals = geometry.morphAttributes.normal || [];
  13217. const morphColors = geometry.morphAttributes.color || [];
  13218. let vertexDataCount = 0;
  13219. if ( hasMorphPosition === true ) vertexDataCount = 1;
  13220. if ( hasMorphNormals === true ) vertexDataCount = 2;
  13221. if ( hasMorphColors === true ) vertexDataCount = 3;
  13222. let width = geometry.attributes.position.count * vertexDataCount;
  13223. let height = 1;
  13224. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  13225. if ( width > maxTextureSize ) {
  13226. height = Math.ceil( width / maxTextureSize );
  13227. width = maxTextureSize;
  13228. }
  13229. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  13230. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  13231. bufferTexture.type = FloatType;
  13232. bufferTexture.needsUpdate = true;
  13233. // fill buffer
  13234. const vertexDataStride = vertexDataCount * 4;
  13235. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  13236. const morphTarget = morphTargets[ i ];
  13237. const morphNormal = morphNormals[ i ];
  13238. const morphColor = morphColors[ i ];
  13239. const offset = width * height * 4 * i;
  13240. for ( let j = 0; j < morphTarget.count; j ++ ) {
  13241. const stride = j * vertexDataStride;
  13242. if ( hasMorphPosition === true ) {
  13243. _morphVec4.fromBufferAttribute( morphTarget, j );
  13244. buffer[ offset + stride + 0 ] = _morphVec4.x;
  13245. buffer[ offset + stride + 1 ] = _morphVec4.y;
  13246. buffer[ offset + stride + 2 ] = _morphVec4.z;
  13247. buffer[ offset + stride + 3 ] = 0;
  13248. }
  13249. if ( hasMorphNormals === true ) {
  13250. _morphVec4.fromBufferAttribute( morphNormal, j );
  13251. buffer[ offset + stride + 4 ] = _morphVec4.x;
  13252. buffer[ offset + stride + 5 ] = _morphVec4.y;
  13253. buffer[ offset + stride + 6 ] = _morphVec4.z;
  13254. buffer[ offset + stride + 7 ] = 0;
  13255. }
  13256. if ( hasMorphColors === true ) {
  13257. _morphVec4.fromBufferAttribute( morphColor, j );
  13258. buffer[ offset + stride + 8 ] = _morphVec4.x;
  13259. buffer[ offset + stride + 9 ] = _morphVec4.y;
  13260. buffer[ offset + stride + 10 ] = _morphVec4.z;
  13261. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  13262. }
  13263. }
  13264. }
  13265. entry = {
  13266. count: morphTargetsCount,
  13267. texture: bufferTexture,
  13268. stride: vertexDataCount,
  13269. size: new Vector2( width, height )
  13270. };
  13271. _morphTextures.set( geometry, entry );
  13272. function disposeTexture() {
  13273. bufferTexture.dispose();
  13274. _morphTextures.delete( geometry );
  13275. geometry.removeEventListener( 'dispose', disposeTexture );
  13276. }
  13277. geometry.addEventListener( 'dispose', disposeTexture );
  13278. }
  13279. return entry;
  13280. }
  13281. /**
  13282. * This node implements the vertex transformation shader logic which is required
  13283. * for morph target animation.
  13284. *
  13285. * @augments Node
  13286. */
  13287. class MorphNode extends Node {
  13288. static get type() {
  13289. return 'MorphNode';
  13290. }
  13291. /**
  13292. * Constructs a new morph node.
  13293. *
  13294. * @param {Mesh} mesh - The mesh holding the morph targets.
  13295. */
  13296. constructor( mesh ) {
  13297. super( 'void' );
  13298. /**
  13299. * The mesh holding the morph targets.
  13300. *
  13301. * @type {Mesh}
  13302. */
  13303. this.mesh = mesh;
  13304. /**
  13305. * A uniform node which represents the morph base influence value.
  13306. *
  13307. * @type {UniformNode<float>}
  13308. */
  13309. this.morphBaseInfluence = uniform( 1 );
  13310. /**
  13311. * The update type overwritten since morph nodes are updated per object.
  13312. *
  13313. * @type {string}
  13314. */
  13315. this.updateType = NodeUpdateType.OBJECT;
  13316. }
  13317. /**
  13318. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  13319. *
  13320. * @param {NodeBuilder} builder - The current node builder.
  13321. */
  13322. setup( builder ) {
  13323. const { geometry } = builder;
  13324. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13325. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  13326. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13327. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13328. // nodes
  13329. const { texture: bufferMap, stride, size } = getEntry( geometry );
  13330. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  13331. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  13332. const width = int( size.width );
  13333. Loop( morphTargetsCount, ( { i } ) => {
  13334. const influence = float( 0 ).toVar();
  13335. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  13336. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  13337. } else {
  13338. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  13339. }
  13340. If( influence.notEqual( 0 ), () => {
  13341. if ( hasMorphPosition === true ) {
  13342. positionLocal.addAssign( getMorph( {
  13343. bufferMap,
  13344. influence,
  13345. stride,
  13346. width,
  13347. depth: i,
  13348. offset: int( 0 )
  13349. } ) );
  13350. }
  13351. if ( hasMorphNormals === true ) {
  13352. normalLocal.addAssign( getMorph( {
  13353. bufferMap,
  13354. influence,
  13355. stride,
  13356. width,
  13357. depth: i,
  13358. offset: int( 1 )
  13359. } ) );
  13360. }
  13361. } );
  13362. } );
  13363. }
  13364. /**
  13365. * Updates the state of the morphed mesh by updating the base influence.
  13366. *
  13367. * @param {NodeFrame} frame - The current node frame.
  13368. */
  13369. update( /*frame*/ ) {
  13370. const morphBaseInfluence = this.morphBaseInfluence;
  13371. if ( this.mesh.geometry.morphTargetsRelative ) {
  13372. morphBaseInfluence.value = 1;
  13373. } else {
  13374. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  13375. }
  13376. }
  13377. }
  13378. /**
  13379. * TSL function for creating a morph node.
  13380. *
  13381. * @tsl
  13382. * @function
  13383. * @param {Mesh} mesh - The mesh holding the morph targets.
  13384. * @returns {MorphNode}
  13385. */
  13386. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  13387. /**
  13388. * Base class for lighting nodes.
  13389. *
  13390. * @augments Node
  13391. */
  13392. class LightingNode extends Node {
  13393. static get type() {
  13394. return 'LightingNode';
  13395. }
  13396. /**
  13397. * Constructs a new lighting node.
  13398. */
  13399. constructor() {
  13400. super( 'vec3' );
  13401. /**
  13402. * This flag can be used for type testing.
  13403. *
  13404. * @type {boolean}
  13405. * @readonly
  13406. * @default true
  13407. */
  13408. this.isLightingNode = true;
  13409. }
  13410. }
  13411. /**
  13412. * A generic class that can be used by nodes which contribute
  13413. * ambient occlusion to the scene. E.g. an ambient occlusion map
  13414. * node can be used as input for this module. Used in {@link NodeMaterial}.
  13415. *
  13416. * @augments LightingNode
  13417. */
  13418. class AONode extends LightingNode {
  13419. static get type() {
  13420. return 'AONode';
  13421. }
  13422. /**
  13423. * Constructs a new AO node.
  13424. *
  13425. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  13426. */
  13427. constructor( aoNode = null ) {
  13428. super();
  13429. /**
  13430. * The ambient occlusion node.
  13431. *
  13432. * @type {?Node<float>}
  13433. * @default null
  13434. */
  13435. this.aoNode = aoNode;
  13436. }
  13437. setup( builder ) {
  13438. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  13439. }
  13440. }
  13441. /**
  13442. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  13443. * by adding lighting specific context data. It represents the runtime context of
  13444. * {@link LightsNode}.
  13445. *
  13446. * @augments ContextNode
  13447. */
  13448. class LightingContextNode extends ContextNode {
  13449. static get type() {
  13450. return 'LightingContextNode';
  13451. }
  13452. /**
  13453. * Constructs a new lighting context node.
  13454. *
  13455. * @param {LightsNode} lightsNode - The lights node.
  13456. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  13457. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  13458. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  13459. */
  13460. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  13461. super( lightsNode );
  13462. /**
  13463. * The current lighting model.
  13464. *
  13465. * @type {?LightingModel}
  13466. * @default null
  13467. */
  13468. this.lightingModel = lightingModel;
  13469. /**
  13470. * A backdrop node.
  13471. *
  13472. * @type {?Node<vec3>}
  13473. * @default null
  13474. */
  13475. this.backdropNode = backdropNode;
  13476. /**
  13477. * A backdrop alpha node.
  13478. *
  13479. * @type {?Node<float>}
  13480. * @default null
  13481. */
  13482. this.backdropAlphaNode = backdropAlphaNode;
  13483. this._value = null;
  13484. }
  13485. /**
  13486. * Returns a lighting context object.
  13487. *
  13488. * @return {{
  13489. * radiance: Node<vec3>,
  13490. * irradiance: Node<vec3>,
  13491. * iblIrradiance: Node<vec3>,
  13492. * ambientOcclusion: Node<float>,
  13493. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  13494. * backdrop: Node<vec3>,
  13495. * backdropAlpha: Node<float>
  13496. * }} The lighting context object.
  13497. */
  13498. getContext() {
  13499. const { backdropNode, backdropAlphaNode } = this;
  13500. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  13501. directSpecular = vec3().toVar( 'directSpecular' ),
  13502. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  13503. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  13504. const reflectedLight = {
  13505. directDiffuse,
  13506. directSpecular,
  13507. indirectDiffuse,
  13508. indirectSpecular
  13509. };
  13510. const context = {
  13511. radiance: vec3().toVar( 'radiance' ),
  13512. irradiance: vec3().toVar( 'irradiance' ),
  13513. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  13514. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  13515. reflectedLight,
  13516. backdrop: backdropNode,
  13517. backdropAlpha: backdropAlphaNode
  13518. };
  13519. return context;
  13520. }
  13521. setup( builder ) {
  13522. this.value = this._value || ( this._value = this.getContext() );
  13523. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13524. return super.setup( builder );
  13525. }
  13526. }
  13527. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13528. /**
  13529. * A generic class that can be used by nodes which contribute
  13530. * irradiance to the scene. E.g. a light map node can be used
  13531. * as input for this module. Used in {@link NodeMaterial}.
  13532. *
  13533. * @augments LightingNode
  13534. */
  13535. class IrradianceNode extends LightingNode {
  13536. static get type() {
  13537. return 'IrradianceNode';
  13538. }
  13539. /**
  13540. * Constructs a new irradiance node.
  13541. *
  13542. * @param {Node<vec3>} node - A node contributing irradiance.
  13543. */
  13544. constructor( node ) {
  13545. super();
  13546. /**
  13547. * A node contributing irradiance.
  13548. *
  13549. * @type {Node<vec3>}
  13550. */
  13551. this.node = node;
  13552. }
  13553. setup( builder ) {
  13554. builder.context.irradiance.addAssign( this.node );
  13555. }
  13556. }
  13557. const _size$5 = /*@__PURE__*/ new Vector2();
  13558. /**
  13559. * A special type of texture node which represents the data of the current viewport
  13560. * as a texture. The module extracts data from the current bound framebuffer with
  13561. * a copy operation so no extra render pass is required to produce the texture data
  13562. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13563. * variety of effects like refractive or transmissive materials.
  13564. *
  13565. * @augments TextureNode
  13566. */
  13567. class ViewportTextureNode extends TextureNode {
  13568. static get type() {
  13569. return 'ViewportTextureNode';
  13570. }
  13571. /**
  13572. * Constructs a new viewport texture node.
  13573. *
  13574. * @param {Node} [uvNode=screenUV] - The uv node.
  13575. * @param {?Node} [levelNode=null] - The level node.
  13576. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13577. */
  13578. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13579. let defaultFramebuffer = null;
  13580. if ( framebufferTexture === null ) {
  13581. defaultFramebuffer = new FramebufferTexture();
  13582. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13583. framebufferTexture = defaultFramebuffer;
  13584. } else {
  13585. defaultFramebuffer = framebufferTexture;
  13586. }
  13587. super( framebufferTexture, uvNode, levelNode );
  13588. /**
  13589. * Whether to generate mipmaps or not.
  13590. *
  13591. * @type {boolean}
  13592. * @default false
  13593. */
  13594. this.generateMipmaps = false;
  13595. /**
  13596. * The reference framebuffer texture. This is used to store the framebuffer texture
  13597. * for the current render target. If the render target changes, a new framebuffer texture
  13598. * is created automatically.
  13599. *
  13600. * @type {FramebufferTexture}
  13601. * @default null
  13602. */
  13603. this.defaultFramebuffer = defaultFramebuffer;
  13604. /**
  13605. * This flag can be used for type testing.
  13606. *
  13607. * @type {boolean}
  13608. * @readonly
  13609. * @default true
  13610. */
  13611. this.isOutputTextureNode = true;
  13612. /**
  13613. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node should extract
  13614. * the current contents of the bound framebuffer for each render call.
  13615. *
  13616. * @type {string}
  13617. * @default 'render'
  13618. */
  13619. this.updateBeforeType = NodeUpdateType.RENDER;
  13620. /**
  13621. * The framebuffer texture for the current renderer context.
  13622. *
  13623. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13624. * @private
  13625. */
  13626. this._cacheTextures = new WeakMap();
  13627. }
  13628. /**
  13629. * This methods returns a texture for the given render target reference.
  13630. *
  13631. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13632. * for different render contexts.
  13633. *
  13634. * @param {?RenderTarget} [reference=null] - The render target reference.
  13635. * @return {Texture} The framebuffer texture.
  13636. */
  13637. getTextureForReference( reference = null ) {
  13638. let defaultFramebuffer;
  13639. let cacheTextures;
  13640. if ( this.referenceNode ) {
  13641. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13642. cacheTextures = this.referenceNode._cacheTextures;
  13643. } else {
  13644. defaultFramebuffer = this.defaultFramebuffer;
  13645. cacheTextures = this._cacheTextures;
  13646. }
  13647. if ( reference === null ) {
  13648. return defaultFramebuffer;
  13649. }
  13650. if ( cacheTextures.has( reference ) === false ) {
  13651. const framebufferTexture = defaultFramebuffer.clone();
  13652. cacheTextures.set( reference, framebufferTexture );
  13653. }
  13654. return cacheTextures.get( reference );
  13655. }
  13656. updateReference( frame ) {
  13657. const renderTarget = frame.renderer.getRenderTarget();
  13658. this.value = this.getTextureForReference( renderTarget );
  13659. return this.value;
  13660. }
  13661. updateBefore( frame ) {
  13662. const renderer = frame.renderer;
  13663. const renderTarget = renderer.getRenderTarget();
  13664. if ( renderTarget === null ) {
  13665. renderer.getDrawingBufferSize( _size$5 );
  13666. } else {
  13667. _size$5.set( renderTarget.width, renderTarget.height );
  13668. }
  13669. //
  13670. const framebufferTexture = this.getTextureForReference( renderTarget );
  13671. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13672. framebufferTexture.image.width = _size$5.width;
  13673. framebufferTexture.image.height = _size$5.height;
  13674. framebufferTexture.needsUpdate = true;
  13675. }
  13676. //
  13677. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13678. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13679. renderer.copyFramebufferToTexture( framebufferTexture );
  13680. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13681. }
  13682. clone() {
  13683. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13684. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13685. return viewportTextureNode;
  13686. }
  13687. }
  13688. /**
  13689. * TSL function for creating a viewport texture node.
  13690. *
  13691. * @tsl
  13692. * @function
  13693. * @param {?Node} [uvNode=screenUV] - The uv node.
  13694. * @param {?Node} [levelNode=null] - The level node.
  13695. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13696. * @returns {ViewportTextureNode}
  13697. */
  13698. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13699. /**
  13700. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13701. *
  13702. * @tsl
  13703. * @function
  13704. * @param {?Node} [uvNode=screenUV] - The uv node.
  13705. * @param {?Node} [levelNode=null] - The level node.
  13706. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13707. * @returns {ViewportTextureNode}
  13708. */
  13709. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13710. // Singleton instances for common usage
  13711. const _singletonOpaqueViewportTextureNode = /*@__PURE__*/ viewportMipTexture();
  13712. /**
  13713. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13714. * The texture should only contain the opaque rendering objects.
  13715. *
  13716. * This should be used just in transparent or transmissive materials.
  13717. *
  13718. * @tsl
  13719. * @function
  13720. * @param {?Node} [uv=screenUV] - The uv node.
  13721. * @param {?Node} [level=null] - The level node.
  13722. * @returns {ViewportTextureNode}
  13723. */
  13724. const viewportOpaqueMipTexture = ( uv = screenUV, level = null ) => _singletonOpaqueViewportTextureNode.sample( uv, level ); // TODO: Use once() when sample() supports it
  13725. let _sharedDepthbuffer = null;
  13726. /**
  13727. * Represents the depth of the current viewport as a texture. This module
  13728. * can be used in combination with viewport texture to achieve effects
  13729. * that require depth evaluation.
  13730. *
  13731. * @augments ViewportTextureNode
  13732. */
  13733. class ViewportDepthTextureNode extends ViewportTextureNode {
  13734. static get type() {
  13735. return 'ViewportDepthTextureNode';
  13736. }
  13737. /**
  13738. * Constructs a new viewport depth texture node.
  13739. *
  13740. * @param {Node} [uvNode=screenUV] - The uv node.
  13741. * @param {?Node} [levelNode=null] - The level node.
  13742. */
  13743. constructor( uvNode = screenUV, levelNode = null ) {
  13744. if ( _sharedDepthbuffer === null ) {
  13745. _sharedDepthbuffer = new DepthTexture();
  13746. }
  13747. super( uvNode, levelNode, _sharedDepthbuffer );
  13748. }
  13749. /**
  13750. * Overwritten so the method always returns the unique shared
  13751. * depth texture.
  13752. *
  13753. * @return {DepthTexture} The shared depth texture.
  13754. */
  13755. getTextureForReference() {
  13756. return _sharedDepthbuffer;
  13757. }
  13758. }
  13759. /**
  13760. * TSL function for a viewport depth texture node.
  13761. *
  13762. * @tsl
  13763. * @function
  13764. * @param {?Node} [uvNode=screenUV] - The uv node.
  13765. * @param {?Node} [levelNode=null] - The level node.
  13766. * @returns {ViewportDepthTextureNode}
  13767. */
  13768. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  13769. /**
  13770. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13771. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13772. * fragment or for depth evaluation purposes.
  13773. *
  13774. * @augments Node
  13775. */
  13776. class ViewportDepthNode extends Node {
  13777. static get type() {
  13778. return 'ViewportDepthNode';
  13779. }
  13780. /**
  13781. * Constructs a new viewport depth node.
  13782. *
  13783. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13784. * @param {?Node} [valueNode=null] - The value node.
  13785. */
  13786. constructor( scope, valueNode = null ) {
  13787. super( 'float' );
  13788. /**
  13789. * The node behaves differently depending on which scope is selected.
  13790. *
  13791. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13792. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13793. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13794. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13795. *
  13796. * @type {('depth'|'depthBase'|'linearDepth')}
  13797. */
  13798. this.scope = scope;
  13799. /**
  13800. * Can be used to define a custom depth value.
  13801. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13802. *
  13803. * @type {?Node}
  13804. * @default null
  13805. */
  13806. this.valueNode = valueNode;
  13807. /**
  13808. * This flag can be used for type testing.
  13809. *
  13810. * @type {boolean}
  13811. * @readonly
  13812. * @default true
  13813. */
  13814. this.isViewportDepthNode = true;
  13815. }
  13816. generate( builder ) {
  13817. const { scope } = this;
  13818. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13819. return builder.getFragDepth();
  13820. }
  13821. return super.generate( builder );
  13822. }
  13823. setup( { camera } ) {
  13824. const { scope } = this;
  13825. const value = this.valueNode;
  13826. let node = null;
  13827. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13828. if ( value !== null ) {
  13829. node = depthBase().assign( value );
  13830. }
  13831. } else if ( scope === ViewportDepthNode.DEPTH ) {
  13832. if ( camera.isPerspectiveCamera ) {
  13833. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  13834. } else {
  13835. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13836. }
  13837. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  13838. if ( value !== null ) {
  13839. if ( camera.isPerspectiveCamera ) {
  13840. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  13841. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  13842. } else {
  13843. node = value;
  13844. }
  13845. } else {
  13846. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13847. }
  13848. }
  13849. return node;
  13850. }
  13851. }
  13852. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  13853. ViewportDepthNode.DEPTH = 'depth';
  13854. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  13855. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  13856. /**
  13857. * TSL function for converting a viewZ value to an orthographic depth value.
  13858. *
  13859. * @tsl
  13860. * @function
  13861. * @param {Node<float>} viewZ - The viewZ node.
  13862. * @param {Node<float>} near - The camera's near value.
  13863. * @param {Node<float>} far - The camera's far value.
  13864. * @returns {Node<float>}
  13865. */
  13866. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  13867. /**
  13868. * TSL function for converting an orthographic depth value to a viewZ value.
  13869. *
  13870. * @tsl
  13871. * @function
  13872. * @param {Node<float>} depth - The orthographic depth.
  13873. * @param {Node<float>} near - The camera's near value.
  13874. * @param {Node<float>} far - The camera's far value.
  13875. * @returns {Node<float>}
  13876. */
  13877. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  13878. /**
  13879. * TSL function for converting a viewZ value to a perspective depth value.
  13880. *
  13881. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  13882. *
  13883. * @tsl
  13884. * @function
  13885. * @param {Node<float>} viewZ - The viewZ node.
  13886. * @param {Node<float>} near - The camera's near value.
  13887. * @param {Node<float>} far - The camera's far value.
  13888. * @returns {Node<float>}
  13889. */
  13890. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  13891. /**
  13892. * TSL function for converting a viewZ value to a reversed perspective depth value.
  13893. *
  13894. * @tsl
  13895. * @function
  13896. * @param {Node<float>} viewZ - The viewZ node.
  13897. * @param {Node<float>} near - The camera's near value.
  13898. * @param {Node<float>} far - The camera's far value.
  13899. * @returns {Node<float>}
  13900. */
  13901. const viewZToReversedPerspectiveDepth = ( viewZ, near, far ) => near.mul( viewZ.add( far ) ).div( viewZ.mul( near.sub( far ) ) );
  13902. /**
  13903. * TSL function for converting a perspective depth value to a viewZ value.
  13904. *
  13905. * @tsl
  13906. * @function
  13907. * @param {Node<float>} depth - The perspective depth.
  13908. * @param {Node<float>} near - The camera's near value.
  13909. * @param {Node<float>} far - The camera's far value.
  13910. * @returns {Node<float>}
  13911. */
  13912. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13913. /**
  13914. * TSL function for converting a viewZ value to a logarithmic depth value.
  13915. *
  13916. * @tsl
  13917. * @function
  13918. * @param {Node<float>} viewZ - The viewZ node.
  13919. * @param {Node<float>} near - The camera's near value.
  13920. * @param {Node<float>} far - The camera's far value.
  13921. * @returns {Node<float>}
  13922. */
  13923. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13924. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13925. // The final logarithmic depth formula used here is adapted from one described in an
  13926. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13927. // which was an improvement upon an earlier formula one described in an
  13928. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13929. // Ulrich's formula is the following:
  13930. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13931. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13932. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13933. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13934. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13935. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13936. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13937. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13938. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13939. // Outerra eventually made another improvement to their original "C-constant" variant,
  13940. // but it still does not incorporate the camera near plane (for this version,
  13941. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13942. // Here we make 4 changes to Ulrich's formula:
  13943. // 1. Clamp the camera near plane so we don't divide by 0.
  13944. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13945. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13946. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13947. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13948. // so we do the same here, hence the 'viewZ.negate()' call.
  13949. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13950. near = near.max( 1e-6 ).toVar();
  13951. const numerator = log2( viewZ.negate().div( near ) );
  13952. const denominator = log2( far.div( near ) );
  13953. return numerator.div( denominator );
  13954. };
  13955. /**
  13956. * TSL function for converting a logarithmic depth value to a viewZ value.
  13957. *
  13958. * @tsl
  13959. * @function
  13960. * @param {Node<float>} depth - The logarithmic depth.
  13961. * @param {Node<float>} near - The camera's near value.
  13962. * @param {Node<float>} far - The camera's far value.
  13963. * @returns {Node<float>}
  13964. */
  13965. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13966. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13967. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13968. // a negative viewZ).
  13969. const exponent = depth.mul( log( far.div( near ) ) );
  13970. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13971. };
  13972. /**
  13973. * TSL function for defining a value for the current fragment's depth.
  13974. *
  13975. * @tsl
  13976. * @function
  13977. * @param {Node<float>} value - The depth value to set.
  13978. * @returns {ViewportDepthNode<float>}
  13979. */
  13980. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13981. /**
  13982. * TSL object that represents the depth value for the current fragment.
  13983. *
  13984. * @tsl
  13985. * @type {ViewportDepthNode}
  13986. */
  13987. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13988. /**
  13989. * TSL function for converting a perspective depth value to linear depth.
  13990. *
  13991. * @tsl
  13992. * @function
  13993. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13994. * @returns {ViewportDepthNode<float>}
  13995. */
  13996. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13997. /**
  13998. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13999. *
  14000. * @tsl
  14001. * @type {ViewportDepthNode}
  14002. */
  14003. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  14004. depth.assign = ( value ) => depthBase( value );
  14005. /**
  14006. * This node is used in {@link NodeMaterial} to setup the clipping
  14007. * which can happen hardware-accelerated (if supported) and optionally
  14008. * use alpha-to-coverage for anti-aliasing clipped edges.
  14009. *
  14010. * @augments Node
  14011. */
  14012. class ClippingNode extends Node {
  14013. static get type() {
  14014. return 'ClippingNode';
  14015. }
  14016. /**
  14017. * Constructs a new clipping node.
  14018. *
  14019. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  14020. * the selected scope influences the behavior of the node and what type of code is generated.
  14021. */
  14022. constructor( scope = ClippingNode.DEFAULT ) {
  14023. super();
  14024. /**
  14025. * The node's scope. Similar to other nodes, the selected scope influences
  14026. * the behavior of the node and what type of code is generated.
  14027. *
  14028. * @type {('default'|'hardware'|'alphaToCoverage')}
  14029. */
  14030. this.scope = scope;
  14031. }
  14032. /**
  14033. * Setups the node depending on the selected scope.
  14034. *
  14035. * @param {NodeBuilder} builder - The current node builder.
  14036. * @return {Node} The result node.
  14037. */
  14038. setup( builder ) {
  14039. super.setup( builder );
  14040. const clippingContext = builder.clippingContext;
  14041. const { intersectionPlanes, unionPlanes } = clippingContext;
  14042. this.hardwareClipping = builder.material.hardwareClipping;
  14043. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  14044. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  14045. } else if ( this.scope === ClippingNode.HARDWARE ) {
  14046. return this.setupHardwareClipping( unionPlanes, builder );
  14047. } else {
  14048. return this.setupDefault( intersectionPlanes, unionPlanes );
  14049. }
  14050. }
  14051. /**
  14052. * Setups alpha to coverage.
  14053. *
  14054. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  14055. * @param {Array<Vector4>} unionPlanes - The union planes.
  14056. * @return {Node} The result node.
  14057. */
  14058. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  14059. return Fn( () => {
  14060. const distanceToPlane = float().toVar( 'distanceToPlane' );
  14061. const distanceGradient = float().toVar( 'distanceToGradient' );
  14062. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  14063. const numUnionPlanes = unionPlanes.length;
  14064. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  14065. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14066. Loop( numUnionPlanes, ( { i } ) => {
  14067. const plane = clippingPlanes.element( i );
  14068. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  14069. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  14070. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  14071. } );
  14072. }
  14073. const numIntersectionPlanes = intersectionPlanes.length;
  14074. if ( numIntersectionPlanes > 0 ) {
  14075. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  14076. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  14077. Loop( numIntersectionPlanes, ( { i } ) => {
  14078. const plane = clippingPlanes.element( i );
  14079. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  14080. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  14081. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  14082. } );
  14083. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  14084. }
  14085. diffuseColor.a.mulAssign( clipOpacity );
  14086. diffuseColor.a.equal( 0.0 ).discard();
  14087. } )();
  14088. }
  14089. /**
  14090. * Setups the default clipping.
  14091. *
  14092. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  14093. * @param {Array<Vector4>} unionPlanes - The union planes.
  14094. * @return {Node} The result node.
  14095. */
  14096. setupDefault( intersectionPlanes, unionPlanes ) {
  14097. return Fn( () => {
  14098. const numUnionPlanes = unionPlanes.length;
  14099. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  14100. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14101. Loop( numUnionPlanes, ( { i } ) => {
  14102. const plane = clippingPlanes.element( i );
  14103. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  14104. } );
  14105. }
  14106. const numIntersectionPlanes = intersectionPlanes.length;
  14107. if ( numIntersectionPlanes > 0 ) {
  14108. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  14109. const clipped = bool( true ).toVar( 'clipped' );
  14110. Loop( numIntersectionPlanes, ( { i } ) => {
  14111. const plane = clippingPlanes.element( i );
  14112. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  14113. } );
  14114. clipped.discard();
  14115. }
  14116. } )();
  14117. }
  14118. /**
  14119. * Setups hardware clipping.
  14120. *
  14121. * @param {Array<Vector4>} unionPlanes - The union planes.
  14122. * @param {NodeBuilder} builder - The current node builder.
  14123. * @return {Node} The result node.
  14124. */
  14125. setupHardwareClipping( unionPlanes, builder ) {
  14126. const numUnionPlanes = unionPlanes.length;
  14127. builder.enableHardwareClipping( numUnionPlanes );
  14128. return Fn( () => {
  14129. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  14130. const hw_clip_distances = builtin( builder.getClipDistance() );
  14131. Loop( numUnionPlanes, ( { i } ) => {
  14132. const plane = clippingPlanes.element( i );
  14133. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  14134. hw_clip_distances.element( i ).assign( distance );
  14135. } );
  14136. } )();
  14137. }
  14138. }
  14139. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  14140. ClippingNode.DEFAULT = 'default';
  14141. ClippingNode.HARDWARE = 'hardware';
  14142. /**
  14143. * TSL function for setting up the default clipping logic.
  14144. *
  14145. * @tsl
  14146. * @function
  14147. * @returns {ClippingNode}
  14148. */
  14149. const clipping = () => new ClippingNode();
  14150. /**
  14151. * TSL function for setting up alpha to coverage.
  14152. *
  14153. * @tsl
  14154. * @function
  14155. * @returns {ClippingNode}
  14156. */
  14157. const clippingAlpha = () => new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE );
  14158. /**
  14159. * TSL function for setting up hardware-based clipping.
  14160. *
  14161. * @tsl
  14162. * @function
  14163. * @returns {ClippingNode}
  14164. */
  14165. const hardwareClipping = () => new ClippingNode( ClippingNode.HARDWARE );
  14166. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  14167. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  14168. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  14169. 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 ) ) ) ) ) );
  14170. } );
  14171. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  14172. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  14173. } );
  14174. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  14175. // Find the discretized derivatives of our coordinates
  14176. const maxDeriv = max$1(
  14177. length( dFdx( position.xyz ) ),
  14178. length( dFdy( position.xyz ) )
  14179. );
  14180. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  14181. // Find two nearest log-discretized noise scales
  14182. const pixScales = vec2(
  14183. exp2( floor( log2( pixScale ) ) ),
  14184. exp2( ceil( log2( pixScale ) ) )
  14185. );
  14186. // Compute alpha thresholds at our two noise scales
  14187. const alpha = vec2(
  14188. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  14189. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  14190. );
  14191. // Factor to interpolate lerp with
  14192. const lerpFactor = fract( log2( pixScale ) );
  14193. // Interpolate alpha threshold from noise at two scales
  14194. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  14195. // Pass into CDF to compute uniformly distrib threshold
  14196. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  14197. const cases = vec3(
  14198. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  14199. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  14200. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  14201. // Find our final, uniformly distributed alpha threshold (ατ)
  14202. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  14203. // Avoids ατ == 0. Could also do ατ =1-ατ
  14204. return clamp( threshold, 1.0e-6, 1.0 );
  14205. } ).setLayout( {
  14206. name: 'getAlphaHashThreshold',
  14207. type: 'float',
  14208. inputs: [
  14209. { name: 'position', type: 'vec3' }
  14210. ]
  14211. } );
  14212. /**
  14213. * An attribute node for representing vertex colors.
  14214. *
  14215. * @augments AttributeNode
  14216. */
  14217. class VertexColorNode extends AttributeNode {
  14218. static get type() {
  14219. return 'VertexColorNode';
  14220. }
  14221. /**
  14222. * Constructs a new vertex color node.
  14223. *
  14224. * @param {number} index - The attribute index.
  14225. */
  14226. constructor( index ) {
  14227. super( null, 'vec4' );
  14228. /**
  14229. * This flag can be used for type testing.
  14230. *
  14231. * @type {boolean}
  14232. * @readonly
  14233. * @default true
  14234. */
  14235. this.isVertexColorNode = true;
  14236. /**
  14237. * The attribute index to enable more than one sets of vertex colors.
  14238. *
  14239. * @type {number}
  14240. * @default 0
  14241. */
  14242. this.index = index;
  14243. }
  14244. /**
  14245. * Overwrites the default implementation by honoring the attribute index.
  14246. *
  14247. * @param {NodeBuilder} builder - The current node builder.
  14248. * @return {string} The attribute name.
  14249. */
  14250. getAttributeName( /*builder*/ ) {
  14251. const index = this.index;
  14252. return 'color' + ( index > 0 ? index : '' );
  14253. }
  14254. generate( builder ) {
  14255. const attributeName = this.getAttributeName( builder );
  14256. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  14257. let result;
  14258. if ( geometryAttribute === true ) {
  14259. result = super.generate( builder );
  14260. } else {
  14261. // Vertex color fallback should be white
  14262. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  14263. }
  14264. return result;
  14265. }
  14266. serialize( data ) {
  14267. super.serialize( data );
  14268. data.index = this.index;
  14269. }
  14270. deserialize( data ) {
  14271. super.deserialize( data );
  14272. this.index = data.index;
  14273. }
  14274. }
  14275. /**
  14276. * TSL function for creating a reference node.
  14277. *
  14278. * @tsl
  14279. * @function
  14280. * @param {number} [index=0] - The attribute index.
  14281. * @returns {VertexColorNode}
  14282. */
  14283. const vertexColor = ( index = 0 ) => new VertexColorNode( index );
  14284. /**
  14285. * Represents a "Color Burn" blend mode.
  14286. *
  14287. * It's designed to darken the base layer's colors based on the color of the blend layer.
  14288. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  14289. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  14290. *
  14291. * @tsl
  14292. * @function
  14293. * @param {Node<vec3>} base - The base color.
  14294. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  14295. * @return {Node<vec3>} The result.
  14296. */
  14297. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14298. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  14299. } ).setLayout( {
  14300. name: 'blendBurn',
  14301. type: 'vec3',
  14302. inputs: [
  14303. { name: 'base', type: 'vec3' },
  14304. { name: 'blend', type: 'vec3' }
  14305. ]
  14306. } );
  14307. /**
  14308. * Represents a "Color Dodge" blend mode.
  14309. *
  14310. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  14311. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  14312. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  14313. *
  14314. * @tsl
  14315. * @function
  14316. * @param {Node<vec3>} base - The base color.
  14317. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14318. * @return {Node<vec3>} The result.
  14319. */
  14320. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14321. return min$1( base.div( blend.oneMinus() ), 1.0 );
  14322. } ).setLayout( {
  14323. name: 'blendDodge',
  14324. type: 'vec3',
  14325. inputs: [
  14326. { name: 'base', type: 'vec3' },
  14327. { name: 'blend', type: 'vec3' }
  14328. ]
  14329. } );
  14330. /**
  14331. * Represents a "Screen" blend mode.
  14332. *
  14333. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  14334. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  14335. * effects.
  14336. *
  14337. * @tsl
  14338. * @function
  14339. * @param {Node<vec3>} base - The base color.
  14340. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14341. * @return {Node<vec3>} The result.
  14342. */
  14343. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14344. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  14345. } ).setLayout( {
  14346. name: 'blendScreen',
  14347. type: 'vec3',
  14348. inputs: [
  14349. { name: 'base', type: 'vec3' },
  14350. { name: 'blend', type: 'vec3' }
  14351. ]
  14352. } );
  14353. /**
  14354. * Represents a "Overlay" blend mode.
  14355. *
  14356. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  14357. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  14358. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  14359. *
  14360. * @tsl
  14361. * @function
  14362. * @param {Node<vec3>} base - The base color.
  14363. * @param {Node<vec3>} blend - The blend color
  14364. * @return {Node<vec3>} The result.
  14365. */
  14366. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14367. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  14368. } ).setLayout( {
  14369. name: 'blendOverlay',
  14370. type: 'vec3',
  14371. inputs: [
  14372. { name: 'base', type: 'vec3' },
  14373. { name: 'blend', type: 'vec3' }
  14374. ]
  14375. } );
  14376. /**
  14377. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  14378. * It assumes both input colors have non-premultiplied alpha.
  14379. *
  14380. * @tsl
  14381. * @function
  14382. * @param {Node<vec4>} base - The base color.
  14383. * @param {Node<vec4>} blend - The blend color
  14384. * @return {Node<vec4>} The result.
  14385. */
  14386. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14387. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  14388. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  14389. } ).setLayout( {
  14390. name: 'blendColor',
  14391. type: 'vec4',
  14392. inputs: [
  14393. { name: 'base', type: 'vec4' },
  14394. { name: 'blend', type: 'vec4' }
  14395. ]
  14396. } );
  14397. /**
  14398. * Premultiplies the RGB channels of a color by its alpha channel.
  14399. *
  14400. * This function is useful for converting a non-premultiplied alpha color
  14401. * into a premultiplied alpha format, where the RGB values are scaled
  14402. * by the alpha value. Premultiplied alpha is often used in graphics
  14403. * rendering for certain operations, such as compositing and image processing.
  14404. *
  14405. * @tsl
  14406. * @function
  14407. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  14408. * @return {Node<vec4>} The color with premultiplied alpha.
  14409. */
  14410. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14411. return vec4( color.rgb.mul( color.a ), color.a );
  14412. }, { color: 'vec4', return: 'vec4' } );
  14413. /**
  14414. * Unpremultiplies the RGB channels of a color by its alpha channel.
  14415. *
  14416. * This function is useful for converting a premultiplied alpha color
  14417. * back into a non-premultiplied alpha format, where the RGB values are
  14418. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  14419. * rendering for certain operations, such as compositing and image processing.
  14420. *
  14421. * @tsl
  14422. * @function
  14423. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  14424. * @return {Node<vec4>} The color with non-premultiplied alpha.
  14425. */
  14426. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14427. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  14428. return vec4( color.rgb.div( color.a ), color.a );
  14429. }, { color: 'vec4', return: 'vec4' } );
  14430. /**
  14431. * Base class for all node materials.
  14432. *
  14433. * @augments Material
  14434. */
  14435. class NodeMaterial extends Material {
  14436. static get type() {
  14437. return 'NodeMaterial';
  14438. }
  14439. /**
  14440. * Represents the type of the node material.
  14441. *
  14442. * @type {string}
  14443. */
  14444. get type() {
  14445. return this.constructor.type;
  14446. }
  14447. set type( _value ) { /* */ }
  14448. /**
  14449. * Constructs a new node material.
  14450. */
  14451. constructor() {
  14452. super();
  14453. /**
  14454. * This flag can be used for type testing.
  14455. *
  14456. * @type {boolean}
  14457. * @readonly
  14458. * @default true
  14459. */
  14460. this.isNodeMaterial = true;
  14461. /**
  14462. * Whether this material is affected by fog or not.
  14463. *
  14464. * @type {boolean}
  14465. * @default true
  14466. */
  14467. this.fog = true;
  14468. /**
  14469. * Whether this material is affected by lights or not.
  14470. *
  14471. * @type {boolean}
  14472. * @default false
  14473. */
  14474. this.lights = false;
  14475. /**
  14476. * Whether this material uses hardware clipping or not.
  14477. * This property is managed by the engine and should not be
  14478. * modified by apps.
  14479. *
  14480. * @type {boolean}
  14481. * @default false
  14482. */
  14483. this.hardwareClipping = false;
  14484. /**
  14485. * Node materials which set their `lights` property to `true`
  14486. * are affected by all lights of the scene. Sometimes selective
  14487. * lighting is wanted which means only _some_ lights in the scene
  14488. * affect a material. This can be achieved by creating an instance
  14489. * of {@link LightsNode} with a list of selective
  14490. * lights and assign the node to this property.
  14491. *
  14492. * ```js
  14493. * const customLightsNode = lights( [ light1, light2 ] );
  14494. * material.lightsNode = customLightsNode;
  14495. * ```
  14496. *
  14497. * @type {?LightsNode}
  14498. * @default null
  14499. */
  14500. this.lightsNode = null;
  14501. /**
  14502. * The environment of node materials can be defined by an environment
  14503. * map assigned to the `envMap` property or by `Scene.environment`
  14504. * if the node material is a PBR material. This node property allows to overwrite
  14505. * the default behavior and define the environment with a custom node.
  14506. *
  14507. * ```js
  14508. * material.envNode = pmremTexture( renderTarget.texture );
  14509. * ```
  14510. *
  14511. * @type {?Node<vec3>}
  14512. * @default null
  14513. */
  14514. this.envNode = null;
  14515. /**
  14516. * The lighting of node materials might be influenced by ambient occlusion.
  14517. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14518. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14519. * the default and define the ambient occlusion with a custom node instead.
  14520. *
  14521. * If you don't want to overwrite the diffuse color but modify the existing
  14522. * values instead, use {@link materialAO}.
  14523. *
  14524. * @type {?Node<float>}
  14525. * @default null
  14526. */
  14527. this.aoNode = null;
  14528. /**
  14529. * The diffuse color of node materials is by default inferred from the
  14530. * `color` and `map` properties. This node property allows to overwrite the default
  14531. * and define the diffuse color with a node instead.
  14532. *
  14533. * ```js
  14534. * material.colorNode = color( 0xff0000 ); // define red color
  14535. * ```
  14536. *
  14537. * If you don't want to overwrite the diffuse color but modify the existing
  14538. * values instead, use {@link materialColor}.
  14539. *
  14540. * ```js
  14541. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14542. * ```
  14543. *
  14544. * @type {?Node<vec3>}
  14545. * @default null
  14546. */
  14547. this.colorNode = null;
  14548. /**
  14549. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14550. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14551. * and define the normals with a node instead.
  14552. *
  14553. * If you don't want to overwrite the normals but modify the existing values instead,
  14554. * use {@link materialNormal}.
  14555. *
  14556. * @type {?Node<vec3>}
  14557. * @default null
  14558. */
  14559. this.normalNode = null;
  14560. /**
  14561. * The opacity of node materials is by default inferred from the `opacity`
  14562. * and `alphaMap` properties. This node property allows to overwrite the default
  14563. * and define the opacity with a node instead.
  14564. *
  14565. * If you don't want to overwrite the opacity but modify the existing
  14566. * value instead, use {@link materialOpacity}.
  14567. *
  14568. * @type {?Node<float>}
  14569. * @default null
  14570. */
  14571. this.opacityNode = null;
  14572. /**
  14573. * This node can be used to implement a variety of filter-like effects. The idea is
  14574. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14575. * to create an arbitrary effect and then assign the node composition to this property.
  14576. * Everything behind the object using this material will now be affected by a filter.
  14577. *
  14578. * ```js
  14579. * const material = new NodeMaterial()
  14580. * material.transparent = true;
  14581. *
  14582. * // everything behind the object will be monochromatic
  14583. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14584. * ```
  14585. *
  14586. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14587. *
  14588. * @type {?Node<vec3>}
  14589. * @default null
  14590. */
  14591. this.backdropNode = null;
  14592. /**
  14593. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14594. *
  14595. * @type {?Node<float>}
  14596. * @default null
  14597. */
  14598. this.backdropAlphaNode = null;
  14599. /**
  14600. * The alpha test of node materials is by default inferred from the `alphaTest`
  14601. * property. This node property allows to overwrite the default and define the
  14602. * alpha test with a node instead.
  14603. *
  14604. * If you don't want to overwrite the alpha test but modify the existing
  14605. * value instead, use {@link materialAlphaTest}.
  14606. *
  14607. * @type {?Node<float>}
  14608. * @default null
  14609. */
  14610. this.alphaTestNode = null;
  14611. /**
  14612. * Discards the fragment if the mask value is `false`.
  14613. *
  14614. * @type {?Node<bool>}
  14615. * @default null
  14616. */
  14617. this.maskNode = null;
  14618. /**
  14619. * This node can be used to implement a shadow mask for the material.
  14620. *
  14621. * @type {?Node<bool>}
  14622. * @default null
  14623. */
  14624. this.maskShadowNode = null;
  14625. /**
  14626. * The local vertex positions are computed based on multiple factors like the
  14627. * attribute data, morphing or skinning. This node property allows to overwrite
  14628. * the default and define local vertex positions with nodes instead.
  14629. *
  14630. * If you don't want to overwrite the vertex positions but modify the existing
  14631. * values instead, use {@link positionLocal}.
  14632. *
  14633. *```js
  14634. * material.positionNode = positionLocal.add( displace );
  14635. * ```
  14636. *
  14637. * @type {?Node<vec3>}
  14638. * @default null
  14639. */
  14640. this.positionNode = null;
  14641. /**
  14642. * This node property is intended for logic which modifies geometry data once or per animation step.
  14643. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14644. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14645. * can be implemented.
  14646. *
  14647. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14648. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14649. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14650. * eventually assigned to `geometryNode`.
  14651. *
  14652. * @type {?Function}
  14653. * @default null
  14654. */
  14655. this.geometryNode = null;
  14656. /**
  14657. * Allows to overwrite depth values in the fragment shader.
  14658. *
  14659. * @type {?Node<float>}
  14660. * @default null
  14661. */
  14662. this.depthNode = null;
  14663. /**
  14664. * Allows to overwrite the position used for shadow map rendering which
  14665. * is by default {@link positionWorld}, the vertex position
  14666. * in world space.
  14667. *
  14668. * @type {?Node<float>}
  14669. * @default null
  14670. */
  14671. this.receivedShadowPositionNode = null;
  14672. /**
  14673. * Allows to overwrite the geometry position used for shadow map projection which
  14674. * is by default {@link positionLocal}, the vertex position in local space.
  14675. *
  14676. * @type {?Node<float>}
  14677. * @default null
  14678. */
  14679. this.castShadowPositionNode = null;
  14680. /**
  14681. * This node can be used to influence how an object using this node material
  14682. * receive shadows.
  14683. *
  14684. * ```js
  14685. * const totalShadows = float( 1 ).toVar();
  14686. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14687. * totalShadows.mulAssign( shadow );
  14688. * //return float( 1 ); // bypass received shadows
  14689. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14690. * } );
  14691. *
  14692. * @type {?(Function|FunctionNode<vec4>)}
  14693. * @default null
  14694. */
  14695. this.receivedShadowNode = null;
  14696. /**
  14697. * This node can be used to influence how an object using this node material
  14698. * casts shadows. To apply a color to shadows, you can simply do:
  14699. *
  14700. * ```js
  14701. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14702. * ```
  14703. *
  14704. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14705. * is also common to use the property with `Fn` function so checks are performed
  14706. * per fragment.
  14707. *
  14708. * ```js
  14709. * materialCustomShadow.castShadowNode = Fn( () => {
  14710. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14711. * return materialColor;
  14712. * } )();
  14713. * ```
  14714. *
  14715. * @type {?Node<vec4>}
  14716. * @default null
  14717. */
  14718. this.castShadowNode = null;
  14719. /**
  14720. * This node can be used to define the final output of the material.
  14721. *
  14722. * TODO: Explain the differences to `fragmentNode`.
  14723. *
  14724. * @type {?Node<vec4>}
  14725. * @default null
  14726. */
  14727. this.outputNode = null;
  14728. /**
  14729. * MRT configuration is done on renderer or pass level. This node allows to
  14730. * overwrite what values are written into MRT targets on material level. This
  14731. * can be useful for implementing selective FX features that should only affect
  14732. * specific objects.
  14733. *
  14734. * @type {?MRTNode}
  14735. * @default null
  14736. */
  14737. this.mrtNode = null;
  14738. /**
  14739. * This node property can be used if you need complete freedom in implementing
  14740. * the fragment shader. Assigning a node will replace the built-in material
  14741. * logic used in the fragment stage.
  14742. *
  14743. * @type {?Node<vec4>}
  14744. * @default null
  14745. */
  14746. this.fragmentNode = null;
  14747. /**
  14748. * This node property can be used if you need complete freedom in implementing
  14749. * the vertex shader. Assigning a node will replace the built-in material logic
  14750. * used in the vertex stage.
  14751. *
  14752. * @type {?Node<vec4>}
  14753. * @default null
  14754. */
  14755. this.vertexNode = null;
  14756. /**
  14757. * This node can be used as a global context management component for this material.
  14758. *
  14759. * @type {?ContextNode}
  14760. * @default null
  14761. */
  14762. this.contextNode = null;
  14763. }
  14764. /**
  14765. * Returns an array of child nodes for this material.
  14766. *
  14767. * @private
  14768. * @returns {Array<{property: string, childNode: Node}>}
  14769. */
  14770. _getNodeChildren() {
  14771. const children = [];
  14772. for ( const property of Object.getOwnPropertyNames( this ) ) {
  14773. if ( property.startsWith( '_' ) === true ) continue;
  14774. const object = this[ property ];
  14775. if ( object && object.isNode === true ) {
  14776. children.push( { property, childNode: object } );
  14777. }
  14778. }
  14779. return children;
  14780. }
  14781. /**
  14782. * Allows to define a custom cache key that influence the material key computation
  14783. * for render objects.
  14784. *
  14785. * @return {string} The custom cache key.
  14786. */
  14787. customProgramCacheKey() {
  14788. const values = [];
  14789. for ( const { property, childNode } of this._getNodeChildren() ) {
  14790. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey() );
  14791. }
  14792. return this.type + hashArray( values );
  14793. }
  14794. /**
  14795. * Builds this material with the given node builder.
  14796. *
  14797. * @param {NodeBuilder} builder - The current node builder.
  14798. */
  14799. build( builder ) {
  14800. this.setup( builder );
  14801. }
  14802. /**
  14803. * Setups a node material observer with the given builder.
  14804. *
  14805. * @param {NodeBuilder} builder - The current node builder.
  14806. * @return {NodeMaterialObserver} The node material observer.
  14807. */
  14808. setupObserver( builder ) {
  14809. return new NodeMaterialObserver( builder );
  14810. }
  14811. /**
  14812. * Setups the vertex and fragment stage of this node material.
  14813. *
  14814. * @param {NodeBuilder} builder - The current node builder.
  14815. */
  14816. setup( builder ) {
  14817. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14818. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14819. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14820. const renderer = builder.renderer;
  14821. const renderTarget = renderer.getRenderTarget();
  14822. // < CONTEXT >
  14823. if ( renderer.contextNode.isContextNode === true ) {
  14824. builder.context = { ...builder.context, ...renderer.contextNode.getFlowContextData() };
  14825. } else {
  14826. error( 'NodeMaterial: "renderer.contextNode" must be an instance of `context()`.' );
  14827. }
  14828. if ( this.contextNode !== null ) {
  14829. if ( this.contextNode.isContextNode === true ) {
  14830. builder.context = { ...builder.context, ...this.contextNode.getFlowContextData() };
  14831. } else {
  14832. error( 'NodeMaterial: "material.contextNode" must be an instance of `context()`.' );
  14833. }
  14834. }
  14835. // < VERTEX STAGE >
  14836. builder.addStack();
  14837. const mvp = this.setupVertex( builder );
  14838. const vertexNode = subBuild( this.vertexNode || mvp, 'VERTEX' );
  14839. builder.context.clipSpace = vertexNode;
  14840. builder.stack.outputNode = vertexNode;
  14841. this.setupHardwareClipping( builder );
  14842. if ( this.geometryNode !== null ) {
  14843. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14844. }
  14845. builder.addFlow( 'vertex', builder.removeStack() );
  14846. // < FRAGMENT STAGE >
  14847. builder.addStack();
  14848. let resultNode;
  14849. const clippingNode = this.setupClipping( builder );
  14850. if ( this.depthWrite === true || this.depthTest === true ) {
  14851. // only write depth if depth buffer is configured
  14852. if ( renderTarget !== null ) {
  14853. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14854. } else {
  14855. if ( renderer.depth === true ) this.setupDepth( builder );
  14856. }
  14857. }
  14858. if ( this.fragmentNode === null ) {
  14859. this.setupDiffuseColor( builder );
  14860. this.setupVariants( builder );
  14861. const outgoingLightNode = this.setupLighting( builder );
  14862. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  14863. // force unsigned floats - useful for RenderTargets
  14864. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  14865. resultNode = this.setupOutput( builder, basicOutput );
  14866. // OUTPUT NODE
  14867. output.assign( resultNode );
  14868. //
  14869. const isCustomOutput = this.outputNode !== null;
  14870. if ( isCustomOutput ) resultNode = this.outputNode;
  14871. //
  14872. if ( builder.context.getOutput ) {
  14873. resultNode = builder.context.getOutput( resultNode, builder );
  14874. }
  14875. // MRT
  14876. if ( renderTarget !== null ) {
  14877. const mrt = renderer.getMRT();
  14878. const materialMRT = this.mrtNode;
  14879. if ( mrt !== null ) {
  14880. if ( isCustomOutput ) output.assign( resultNode );
  14881. resultNode = mrt;
  14882. if ( materialMRT !== null ) {
  14883. resultNode = mrt.merge( materialMRT );
  14884. }
  14885. } else if ( materialMRT !== null ) {
  14886. resultNode = materialMRT;
  14887. }
  14888. }
  14889. } else {
  14890. let fragmentNode = this.fragmentNode;
  14891. if ( fragmentNode.isOutputStructNode !== true ) {
  14892. fragmentNode = vec4( fragmentNode );
  14893. }
  14894. resultNode = this.setupOutput( builder, fragmentNode );
  14895. }
  14896. builder.stack.outputNode = resultNode;
  14897. builder.addFlow( 'fragment', builder.removeStack() );
  14898. // < OBSERVER >
  14899. builder.observer = this.setupObserver( builder );
  14900. }
  14901. /**
  14902. * Setups the clipping node.
  14903. *
  14904. * @param {NodeBuilder} builder - The current node builder.
  14905. * @return {ClippingNode} The clipping node.
  14906. */
  14907. setupClipping( builder ) {
  14908. if ( builder.clippingContext === null ) return null;
  14909. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14910. let result = null;
  14911. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14912. const samples = builder.renderer.currentSamples;
  14913. if ( this.alphaToCoverage && samples > 1 ) {
  14914. // to be added to flow when the color/alpha value has been determined
  14915. result = clippingAlpha();
  14916. } else {
  14917. builder.stack.addToStack( clipping() );
  14918. }
  14919. }
  14920. return result;
  14921. }
  14922. /**
  14923. * Setups the hardware clipping if available on the current device.
  14924. *
  14925. * @param {NodeBuilder} builder - The current node builder.
  14926. */
  14927. setupHardwareClipping( builder ) {
  14928. this.hardwareClipping = false;
  14929. if ( builder.clippingContext === null ) return;
  14930. const candidateCount = builder.clippingContext.unionPlanes.length;
  14931. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14932. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14933. builder.stack.addToStack( hardwareClipping() );
  14934. this.hardwareClipping = true;
  14935. }
  14936. return;
  14937. }
  14938. /**
  14939. * Setups the depth of this material.
  14940. *
  14941. * @param {NodeBuilder} builder - The current node builder.
  14942. */
  14943. setupDepth( builder ) {
  14944. const { renderer, camera } = builder;
  14945. // Depth
  14946. let depthNode = this.depthNode;
  14947. if ( depthNode === null ) {
  14948. const mrt = renderer.getMRT();
  14949. if ( mrt && mrt.has( 'depth' ) ) {
  14950. depthNode = mrt.get( 'depth' );
  14951. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14952. if ( camera.isPerspectiveCamera ) {
  14953. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14954. } else {
  14955. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14956. }
  14957. }
  14958. }
  14959. if ( depthNode !== null ) {
  14960. depth.assign( depthNode ).toStack();
  14961. }
  14962. }
  14963. /**
  14964. * Setups the position node in view space. This method exists
  14965. * so derived node materials can modify the implementation e.g. sprite materials.
  14966. *
  14967. * @param {NodeBuilder} builder - The current node builder.
  14968. * @return {Node<vec3>} The position in view space.
  14969. */
  14970. setupPositionView( /*builder*/ ) {
  14971. return modelViewMatrix.mul( positionLocal ).xyz;
  14972. }
  14973. /**
  14974. * Setups the position in clip space.
  14975. *
  14976. * @param {NodeBuilder} builder - The current node builder.
  14977. * @return {Node<vec4>} The position in view space.
  14978. */
  14979. setupModelViewProjection( /*builder*/ ) {
  14980. return cameraProjectionMatrix.mul( positionView );
  14981. }
  14982. /**
  14983. * Setups the logic for the vertex stage.
  14984. *
  14985. * @param {NodeBuilder} builder - The current node builder.
  14986. * @return {Node<vec4>} The position in clip space.
  14987. */
  14988. setupVertex( builder ) {
  14989. builder.addStack();
  14990. this.setupPosition( builder );
  14991. builder.context.position = builder.removeStack();
  14992. return modelViewProjection;
  14993. }
  14994. /**
  14995. * Setups the computation of the position in local space.
  14996. *
  14997. * @param {NodeBuilder} builder - The current node builder.
  14998. * @return {Node<vec3>} The position in local space.
  14999. */
  15000. setupPosition( builder ) {
  15001. const { object, geometry } = builder;
  15002. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  15003. morphReference( object ).toStack();
  15004. }
  15005. if ( object.isSkinnedMesh === true ) {
  15006. skinning( object ).toStack();
  15007. }
  15008. if ( this.displacementMap ) {
  15009. const displacementMap = materialReference( 'displacementMap', 'texture' );
  15010. const displacementScale = materialReference( 'displacementScale', 'float' );
  15011. const displacementBias = materialReference( 'displacementBias', 'float' );
  15012. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  15013. }
  15014. if ( object.isBatchedMesh ) {
  15015. batch( object ).toStack();
  15016. }
  15017. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  15018. instancedMesh( object ).toStack();
  15019. }
  15020. if ( this.positionNode !== null ) {
  15021. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  15022. }
  15023. return positionLocal;
  15024. }
  15025. /**
  15026. * Setups the computation of the material's diffuse color.
  15027. *
  15028. * @param {NodeBuilder} builder - The current node builder.
  15029. * @param {BufferGeometry} geometry - The geometry.
  15030. */
  15031. setupDiffuseColor( builder ) {
  15032. const { object, geometry } = builder;
  15033. // MASK
  15034. if ( this.maskNode !== null ) {
  15035. // Discard if the mask is `false`
  15036. bool( this.maskNode ).not().discard();
  15037. }
  15038. // COLOR
  15039. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  15040. // VERTEX COLORS
  15041. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  15042. colorNode = colorNode.mul( vertexColor() );
  15043. }
  15044. // INSTANCED COLORS
  15045. if ( object.instanceColor ) {
  15046. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  15047. colorNode = instanceColor.mul( colorNode );
  15048. }
  15049. if ( object.isBatchedMesh && object._colorsTexture ) {
  15050. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  15051. colorNode = batchColor.mul( colorNode );
  15052. }
  15053. // DIFFUSE COLOR
  15054. diffuseColor.assign( colorNode );
  15055. // OPACITY
  15056. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15057. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  15058. // ALPHA TEST
  15059. let alphaTestNode = null;
  15060. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  15061. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  15062. if ( this.alphaToCoverage === true ) {
  15063. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  15064. diffuseColor.a.lessThanEqual( 0 ).discard();
  15065. } else {
  15066. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  15067. }
  15068. }
  15069. // ALPHA HASH
  15070. if ( this.alphaHash === true ) {
  15071. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  15072. }
  15073. // OPAQUE
  15074. if ( builder.isOpaque() ) {
  15075. diffuseColor.a.assign( 1.0 );
  15076. }
  15077. }
  15078. /**
  15079. * Abstract interface method that can be implemented by derived materials
  15080. * to setup material-specific node variables.
  15081. *
  15082. * @abstract
  15083. * @param {NodeBuilder} builder - The current node builder.
  15084. */
  15085. setupVariants( /*builder*/ ) {
  15086. // Interface function.
  15087. }
  15088. /**
  15089. * Setups the outgoing light node variable
  15090. *
  15091. * @return {Node<vec3>} The outgoing light node.
  15092. */
  15093. setupOutgoingLight() {
  15094. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  15095. }
  15096. /**
  15097. * Setups the normal node from the material.
  15098. *
  15099. * @return {Node<vec3>} The normal node.
  15100. */
  15101. setupNormal() {
  15102. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  15103. }
  15104. /**
  15105. * Setups the environment node from the material.
  15106. *
  15107. * @param {NodeBuilder} builder - The current node builder.
  15108. * @return {Node<vec4>} The environment node.
  15109. */
  15110. setupEnvironment( /*builder*/ ) {
  15111. let node = null;
  15112. if ( this.envNode ) {
  15113. node = this.envNode;
  15114. } else if ( this.envMap ) {
  15115. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  15116. }
  15117. return node;
  15118. }
  15119. /**
  15120. * Setups the light map node from the material.
  15121. *
  15122. * @param {NodeBuilder} builder - The current node builder.
  15123. * @return {Node<vec3>} The light map node.
  15124. */
  15125. setupLightMap( builder ) {
  15126. let node = null;
  15127. if ( builder.material.lightMap ) {
  15128. node = new IrradianceNode( materialLightMap );
  15129. }
  15130. return node;
  15131. }
  15132. /**
  15133. * Setups the lights node based on the scene, environment and material.
  15134. *
  15135. * @param {NodeBuilder} builder - The current node builder.
  15136. * @return {LightsNode} The lights node.
  15137. */
  15138. setupLights( builder ) {
  15139. const materialLightsNode = [];
  15140. //
  15141. const envNode = this.setupEnvironment( builder );
  15142. if ( envNode && envNode.isLightingNode ) {
  15143. materialLightsNode.push( envNode );
  15144. }
  15145. const lightMapNode = this.setupLightMap( builder );
  15146. if ( lightMapNode && lightMapNode.isLightingNode ) {
  15147. materialLightsNode.push( lightMapNode );
  15148. }
  15149. let aoNode = this.aoNode;
  15150. if ( aoNode === null && builder.material.aoMap ) {
  15151. aoNode = materialAO;
  15152. }
  15153. if ( builder.context.getAO ) {
  15154. aoNode = builder.context.getAO( aoNode, builder );
  15155. }
  15156. if ( aoNode ) {
  15157. materialLightsNode.push( new AONode( aoNode ) );
  15158. }
  15159. let lightsN = this.lightsNode || builder.lightsNode;
  15160. if ( materialLightsNode.length > 0 ) {
  15161. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  15162. }
  15163. return lightsN;
  15164. }
  15165. /**
  15166. * This method should be implemented by most derived materials
  15167. * since it defines the material's lighting model.
  15168. *
  15169. * @abstract
  15170. * @param {NodeBuilder} builder - The current node builder.
  15171. * @return {LightingModel} The lighting model.
  15172. */
  15173. setupLightingModel( /*builder*/ ) {
  15174. // Interface function.
  15175. }
  15176. /**
  15177. * Setups the outgoing light node.
  15178. *
  15179. * @param {NodeBuilder} builder - The current node builder.
  15180. * @return {Node<vec3>} The outgoing light node.
  15181. */
  15182. setupLighting( builder ) {
  15183. const { material } = builder;
  15184. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  15185. // OUTGOING LIGHT
  15186. const lights = this.lights === true || this.lightsNode !== null;
  15187. const lightsNode = lights ? this.setupLights( builder ) : null;
  15188. let outgoingLightNode = this.setupOutgoingLight( builder );
  15189. if ( lightsNode && lightsNode.getScope().hasLights ) {
  15190. const lightingModel = this.setupLightingModel( builder ) || null;
  15191. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  15192. } else if ( backdropNode !== null ) {
  15193. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  15194. }
  15195. // EMISSIVE
  15196. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  15197. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  15198. outgoingLightNode = outgoingLightNode.add( emissive );
  15199. }
  15200. return outgoingLightNode;
  15201. }
  15202. /**
  15203. * Setup the fog.
  15204. *
  15205. * @param {NodeBuilder} builder - The current node builder.
  15206. * @param {Node<vec4>} outputNode - The existing output node.
  15207. * @return {Node<vec4>} The output node.
  15208. */
  15209. setupFog( builder, outputNode ) {
  15210. const fogNode = builder.fogNode;
  15211. if ( fogNode ) {
  15212. output.assign( outputNode );
  15213. outputNode = vec4( fogNode.toVar() );
  15214. }
  15215. return outputNode;
  15216. }
  15217. /**
  15218. * Setups premultiplied alpha.
  15219. *
  15220. * @param {NodeBuilder} builder - The current node builder.
  15221. * @param {Node<vec4>} outputNode - The existing output node.
  15222. * @return {Node<vec4>} The output node.
  15223. */
  15224. setupPremultipliedAlpha( builder, outputNode ) {
  15225. return premultiplyAlpha( outputNode );
  15226. }
  15227. /**
  15228. * Setups the output node.
  15229. *
  15230. * @param {NodeBuilder} builder - The current node builder.
  15231. * @param {Node<vec4>} outputNode - The existing output node.
  15232. * @return {Node<vec4>} The output node.
  15233. */
  15234. setupOutput( builder, outputNode ) {
  15235. // FOG
  15236. if ( this.fog === true ) {
  15237. outputNode = this.setupFog( builder, outputNode );
  15238. }
  15239. // PREMULTIPLIED ALPHA
  15240. if ( this.premultipliedAlpha === true ) {
  15241. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  15242. }
  15243. return outputNode;
  15244. }
  15245. /**
  15246. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  15247. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  15248. * defining all material properties of the classic type in the node type.
  15249. *
  15250. * @param {Material} material - The material to copy properties with their values to this node material.
  15251. */
  15252. setDefaultValues( material ) {
  15253. // This approach is to reuse the native refreshUniforms*
  15254. // and turn available the use of features like transmission and environment in core
  15255. for ( const property in material ) {
  15256. const value = material[ property ];
  15257. if ( this[ property ] === undefined ) {
  15258. this[ property ] = value;
  15259. if ( value && value.clone ) this[ property ] = value.clone();
  15260. }
  15261. }
  15262. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  15263. for ( const key in descriptors ) {
  15264. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  15265. descriptors[ key ].get !== undefined ) {
  15266. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  15267. }
  15268. }
  15269. }
  15270. /**
  15271. * Serializes this material to JSON.
  15272. *
  15273. * @param {?(Object|string)} meta - The meta information for serialization.
  15274. * @return {Object} The serialized node.
  15275. */
  15276. toJSON( meta ) {
  15277. const isRoot = ( meta === undefined || typeof meta === 'string' );
  15278. if ( isRoot ) {
  15279. meta = {
  15280. textures: {},
  15281. images: {},
  15282. nodes: {}
  15283. };
  15284. }
  15285. const data = Material.prototype.toJSON.call( this, meta );
  15286. data.inputNodes = {};
  15287. for ( const { property, childNode } of this._getNodeChildren() ) {
  15288. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  15289. }
  15290. // TODO: Copied from Object3D.toJSON
  15291. function extractFromCache( cache ) {
  15292. const values = [];
  15293. for ( const key in cache ) {
  15294. const data = cache[ key ];
  15295. delete data.metadata;
  15296. values.push( data );
  15297. }
  15298. return values;
  15299. }
  15300. if ( isRoot ) {
  15301. const textures = extractFromCache( meta.textures );
  15302. const images = extractFromCache( meta.images );
  15303. const nodes = extractFromCache( meta.nodes );
  15304. if ( textures.length > 0 ) data.textures = textures;
  15305. if ( images.length > 0 ) data.images = images;
  15306. if ( nodes.length > 0 ) data.nodes = nodes;
  15307. }
  15308. return data;
  15309. }
  15310. /**
  15311. * Copies the properties of the given node material to this instance.
  15312. *
  15313. * @param {NodeMaterial} source - The material to copy.
  15314. * @return {NodeMaterial} A reference to this node material.
  15315. */
  15316. copy( source ) {
  15317. this.lightsNode = source.lightsNode;
  15318. this.envNode = source.envNode;
  15319. this.aoNode = source.aoNode;
  15320. this.colorNode = source.colorNode;
  15321. this.normalNode = source.normalNode;
  15322. this.opacityNode = source.opacityNode;
  15323. this.backdropNode = source.backdropNode;
  15324. this.backdropAlphaNode = source.backdropAlphaNode;
  15325. this.alphaTestNode = source.alphaTestNode;
  15326. this.maskNode = source.maskNode;
  15327. this.maskShadowNode = source.maskShadowNode;
  15328. this.positionNode = source.positionNode;
  15329. this.geometryNode = source.geometryNode;
  15330. this.depthNode = source.depthNode;
  15331. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  15332. this.castShadowPositionNode = source.castShadowPositionNode;
  15333. this.receivedShadowNode = source.receivedShadowNode;
  15334. this.castShadowNode = source.castShadowNode;
  15335. this.outputNode = source.outputNode;
  15336. this.mrtNode = source.mrtNode;
  15337. this.fragmentNode = source.fragmentNode;
  15338. this.vertexNode = source.vertexNode;
  15339. this.contextNode = source.contextNode;
  15340. return super.copy( source );
  15341. }
  15342. }
  15343. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  15344. /**
  15345. * Node material version of {@link LineBasicMaterial}.
  15346. *
  15347. * @augments NodeMaterial
  15348. */
  15349. class LineBasicNodeMaterial extends NodeMaterial {
  15350. static get type() {
  15351. return 'LineBasicNodeMaterial';
  15352. }
  15353. /**
  15354. * Constructs a new line basic node material.
  15355. *
  15356. * @param {Object} [parameters] - The configuration parameter.
  15357. */
  15358. constructor( parameters ) {
  15359. super();
  15360. /**
  15361. * This flag can be used for type testing.
  15362. *
  15363. * @type {boolean}
  15364. * @readonly
  15365. * @default true
  15366. */
  15367. this.isLineBasicNodeMaterial = true;
  15368. this.setDefaultValues( _defaultValues$d );
  15369. this.setValues( parameters );
  15370. }
  15371. }
  15372. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  15373. /**
  15374. * Node material version of {@link LineDashedMaterial}.
  15375. *
  15376. * @augments NodeMaterial
  15377. */
  15378. class LineDashedNodeMaterial extends NodeMaterial {
  15379. static get type() {
  15380. return 'LineDashedNodeMaterial';
  15381. }
  15382. /**
  15383. * Constructs a new line dashed node material.
  15384. *
  15385. * @param {Object} [parameters] - The configuration parameter.
  15386. */
  15387. constructor( parameters ) {
  15388. super();
  15389. /**
  15390. * This flag can be used for type testing.
  15391. *
  15392. * @type {boolean}
  15393. * @readonly
  15394. * @default true
  15395. */
  15396. this.isLineDashedNodeMaterial = true;
  15397. this.setDefaultValues( _defaultValues$c );
  15398. /**
  15399. * The dash offset.
  15400. *
  15401. * @type {number}
  15402. * @default 0
  15403. */
  15404. this.dashOffset = 0;
  15405. /**
  15406. * The offset of dash materials is by default inferred from the `dashOffset`
  15407. * property. This node property allows to overwrite the default
  15408. * and define the offset with a node instead.
  15409. *
  15410. * If you don't want to overwrite the offset but modify the existing
  15411. * value instead, use {@link materialLineDashOffset}.
  15412. *
  15413. * @type {?Node<float>}
  15414. * @default null
  15415. */
  15416. this.offsetNode = null;
  15417. /**
  15418. * The scale of dash materials is by default inferred from the `scale`
  15419. * property. This node property allows to overwrite the default
  15420. * and define the scale with a node instead.
  15421. *
  15422. * If you don't want to overwrite the scale but modify the existing
  15423. * value instead, use {@link materialLineScale}.
  15424. *
  15425. * @type {?Node<float>}
  15426. * @default null
  15427. */
  15428. this.dashScaleNode = null;
  15429. /**
  15430. * The dash size of dash materials is by default inferred from the `dashSize`
  15431. * property. This node property allows to overwrite the default
  15432. * and define the dash size with a node instead.
  15433. *
  15434. * If you don't want to overwrite the dash size but modify the existing
  15435. * value instead, use {@link materialLineDashSize}.
  15436. *
  15437. * @type {?Node<float>}
  15438. * @default null
  15439. */
  15440. this.dashSizeNode = null;
  15441. /**
  15442. * The gap size of dash materials is by default inferred from the `gapSize`
  15443. * property. This node property allows to overwrite the default
  15444. * and define the gap size with a node instead.
  15445. *
  15446. * If you don't want to overwrite the gap size but modify the existing
  15447. * value instead, use {@link materialLineGapSize}.
  15448. *
  15449. * @type {?Node<float>}
  15450. * @default null
  15451. */
  15452. this.gapSizeNode = null;
  15453. this.setValues( parameters );
  15454. }
  15455. /**
  15456. * Setups the dash specific node variables.
  15457. *
  15458. * @param {NodeBuilder} builder - The current node builder.
  15459. */
  15460. setupVariants( /* builder */ ) {
  15461. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15462. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15463. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15464. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15465. dashSize.assign( dashSizeNode );
  15466. gapSize.assign( gapSizeNode );
  15467. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  15468. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  15469. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  15470. }
  15471. }
  15472. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  15473. /**
  15474. * This node material can be used to render lines with a size larger than one
  15475. * by representing them as instanced meshes.
  15476. *
  15477. * @augments NodeMaterial
  15478. */
  15479. class Line2NodeMaterial extends NodeMaterial {
  15480. static get type() {
  15481. return 'Line2NodeMaterial';
  15482. }
  15483. /**
  15484. * Constructs a new node material for wide line rendering.
  15485. *
  15486. * @param {Object} [parameters={}] - The configuration parameter.
  15487. */
  15488. constructor( parameters = {} ) {
  15489. super();
  15490. /**
  15491. * This flag can be used for type testing.
  15492. *
  15493. * @type {boolean}
  15494. * @readonly
  15495. * @default true
  15496. */
  15497. this.isLine2NodeMaterial = true;
  15498. this.setDefaultValues( _defaultValues$b );
  15499. /**
  15500. * Whether vertex colors should be used or not.
  15501. *
  15502. * @type {boolean}
  15503. * @default false
  15504. */
  15505. this.vertexColors = parameters.vertexColors;
  15506. /**
  15507. * The dash offset.
  15508. *
  15509. * @type {number}
  15510. * @default 0
  15511. */
  15512. this.dashOffset = 0;
  15513. /**
  15514. * Defines the lines color.
  15515. *
  15516. * @type {?Node<vec3>}
  15517. * @default null
  15518. */
  15519. this.lineColorNode = null;
  15520. /**
  15521. * Defines the offset.
  15522. *
  15523. * @type {?Node<float>}
  15524. * @default null
  15525. */
  15526. this.offsetNode = null;
  15527. /**
  15528. * Defines the dash scale.
  15529. *
  15530. * @type {?Node<float>}
  15531. * @default null
  15532. */
  15533. this.dashScaleNode = null;
  15534. /**
  15535. * Defines the dash size.
  15536. *
  15537. * @type {?Node<float>}
  15538. * @default null
  15539. */
  15540. this.dashSizeNode = null;
  15541. /**
  15542. * Defines the gap size.
  15543. *
  15544. * @type {?Node<float>}
  15545. * @default null
  15546. */
  15547. this.gapSizeNode = null;
  15548. /**
  15549. * Blending is set to `NoBlending` since transparency
  15550. * is not supported, yet.
  15551. *
  15552. * @type {number}
  15553. * @default 0
  15554. */
  15555. this.blending = NoBlending;
  15556. this._useDash = parameters.dashed;
  15557. this._useAlphaToCoverage = true;
  15558. this._useWorldUnits = false;
  15559. this.setValues( parameters );
  15560. }
  15561. /**
  15562. * Setups the vertex and fragment stage of this node material.
  15563. *
  15564. * @param {NodeBuilder} builder - The current node builder.
  15565. */
  15566. setup( builder ) {
  15567. const { renderer } = builder;
  15568. const useAlphaToCoverage = this._useAlphaToCoverage;
  15569. const vertexColors = this.vertexColors;
  15570. const useDash = this._useDash;
  15571. const useWorldUnits = this._useWorldUnits;
  15572. const trimSegment = Fn( ( { start, end } ) => {
  15573. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15574. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15575. const nearEstimate = b.mul( -0.5 ).div( a );
  15576. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15577. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15578. } ).setLayout( {
  15579. name: 'trimSegment',
  15580. type: 'vec4',
  15581. inputs: [
  15582. { name: 'start', type: 'vec4' },
  15583. { name: 'end', type: 'vec4' }
  15584. ]
  15585. } );
  15586. this.vertexNode = Fn( () => {
  15587. const instanceStart = attribute( 'instanceStart' );
  15588. const instanceEnd = attribute( 'instanceEnd' );
  15589. // camera space
  15590. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15591. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15592. if ( useDash ) {
  15593. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15594. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15595. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15596. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15597. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15598. lineDistance = lineDistance.add( offsetNode );
  15599. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15600. }
  15601. if ( useWorldUnits ) {
  15602. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15603. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15604. }
  15605. const aspect = viewport.z.div( viewport.w );
  15606. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15607. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15608. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15609. // perhaps there is a more elegant solution -- WestLangley
  15610. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15611. If( perspective, () => {
  15612. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15613. end.assign( trimSegment( { start: start, end: end } ) );
  15614. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15615. start.assign( trimSegment( { start: end, end: start } ) );
  15616. } );
  15617. } );
  15618. // clip space
  15619. const clipStart = cameraProjectionMatrix.mul( start );
  15620. const clipEnd = cameraProjectionMatrix.mul( end );
  15621. // ndc space
  15622. const ndcStart = clipStart.xyz.div( clipStart.w );
  15623. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15624. // direction
  15625. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15626. // account for clip-space aspect ratio
  15627. dir.x.assign( dir.x.mul( aspect ) );
  15628. dir.assign( dir.normalize() );
  15629. const clip = vec4().toVar();
  15630. if ( useWorldUnits ) {
  15631. // get the offset direction as perpendicular to the view vector
  15632. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15633. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15634. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15635. const worldFwd = worldDir.cross( worldUp );
  15636. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15637. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15638. // height offset
  15639. const hw = materialLineWidth.mul( 0.5 );
  15640. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15641. // don't extend the line if we're rendering dashes because we
  15642. // won't be rendering the endcaps
  15643. if ( ! useDash ) {
  15644. // cap extension
  15645. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15646. // add width to the box
  15647. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15648. // endcaps
  15649. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15650. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15651. } );
  15652. }
  15653. // project the worldpos
  15654. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15655. // shift the depth of the projected points so the line
  15656. // segments overlap neatly
  15657. const clipPose = vec3().toVar();
  15658. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15659. clip.z.assign( clipPose.z.mul( clip.w ) );
  15660. } else {
  15661. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15662. // undo aspect ratio adjustment
  15663. dir.x.assign( dir.x.div( aspect ) );
  15664. offset.x.assign( offset.x.div( aspect ) );
  15665. // sign flip
  15666. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15667. // endcaps
  15668. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15669. offset.assign( offset.sub( dir ) );
  15670. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15671. offset.assign( offset.add( dir ) );
  15672. } );
  15673. // adjust for linewidth
  15674. offset.assign( offset.mul( materialLineWidth ) );
  15675. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15676. offset.assign( offset.div( viewport.w.div( screenDPR ) ) );
  15677. // select end
  15678. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15679. // back to clip space
  15680. offset.assign( offset.mul( clip.w ) );
  15681. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15682. }
  15683. return clip;
  15684. } )();
  15685. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15686. const p13 = p1.sub( p3 );
  15687. const p43 = p4.sub( p3 );
  15688. const p21 = p2.sub( p1 );
  15689. const d1343 = p13.dot( p43 );
  15690. const d4321 = p43.dot( p21 );
  15691. const d1321 = p13.dot( p21 );
  15692. const d4343 = p43.dot( p43 );
  15693. const d2121 = p21.dot( p21 );
  15694. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15695. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15696. const mua = numer.div( denom ).clamp();
  15697. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15698. return vec2( mua, mub );
  15699. } );
  15700. this.colorNode = Fn( () => {
  15701. const vUv = uv$1();
  15702. if ( useDash ) {
  15703. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15704. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15705. dashSize.assign( dashSizeNode );
  15706. gapSize.assign( gapSizeNode );
  15707. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15708. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15709. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15710. }
  15711. const alpha = float( 1 ).toVar( 'alpha' );
  15712. if ( useWorldUnits ) {
  15713. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15714. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15715. // Find the closest points on the view ray and the line segment
  15716. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15717. const lineDir = worldEnd.sub( worldStart );
  15718. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15719. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15720. const p2 = rayEnd.mul( params.y );
  15721. const delta = p1.sub( p2 );
  15722. const len = delta.length();
  15723. const norm = len.div( materialLineWidth );
  15724. if ( ! useDash ) {
  15725. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15726. const dnorm = norm.fwidth();
  15727. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15728. } else {
  15729. norm.greaterThan( 0.5 ).discard();
  15730. }
  15731. }
  15732. } else {
  15733. // round endcaps
  15734. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15735. const a = vUv.x;
  15736. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15737. const len2 = a.mul( a ).add( b.mul( b ) );
  15738. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15739. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15740. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15741. } );
  15742. } else {
  15743. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15744. const a = vUv.x;
  15745. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15746. const len2 = a.mul( a ).add( b.mul( b ) );
  15747. len2.greaterThan( 1.0 ).discard();
  15748. } );
  15749. }
  15750. }
  15751. let lineColorNode;
  15752. if ( this.lineColorNode ) {
  15753. lineColorNode = this.lineColorNode;
  15754. } else {
  15755. if ( vertexColors ) {
  15756. const instanceColorStart = attribute( 'instanceColorStart' );
  15757. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15758. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15759. lineColorNode = instanceColor.mul( materialColor );
  15760. } else {
  15761. lineColorNode = materialColor;
  15762. }
  15763. }
  15764. return vec4( lineColorNode, alpha );
  15765. } )();
  15766. if ( this.transparent ) {
  15767. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15768. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportOpaqueMipTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15769. }
  15770. super.setup( builder );
  15771. }
  15772. /**
  15773. * Whether the lines should sized in world units or not.
  15774. * When set to `false` the unit is pixel.
  15775. *
  15776. * @type {boolean}
  15777. * @default false
  15778. */
  15779. get worldUnits() {
  15780. return this._useWorldUnits;
  15781. }
  15782. set worldUnits( value ) {
  15783. if ( this._useWorldUnits !== value ) {
  15784. this._useWorldUnits = value;
  15785. this.needsUpdate = true;
  15786. }
  15787. }
  15788. /**
  15789. * Whether the lines should be dashed or not.
  15790. *
  15791. * @type {boolean}
  15792. * @default false
  15793. */
  15794. get dashed() {
  15795. return this._useDash;
  15796. }
  15797. set dashed( value ) {
  15798. if ( this._useDash !== value ) {
  15799. this._useDash = value;
  15800. this.needsUpdate = true;
  15801. }
  15802. }
  15803. /**
  15804. * Whether alpha to coverage should be used or not.
  15805. *
  15806. * @type {boolean}
  15807. * @default true
  15808. */
  15809. get alphaToCoverage() {
  15810. return this._useAlphaToCoverage;
  15811. }
  15812. set alphaToCoverage( value ) {
  15813. if ( this._useAlphaToCoverage !== value ) {
  15814. this._useAlphaToCoverage = value;
  15815. this.needsUpdate = true;
  15816. }
  15817. }
  15818. }
  15819. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15820. /**
  15821. * Node material version of {@link MeshNormalMaterial}.
  15822. *
  15823. * @augments NodeMaterial
  15824. */
  15825. class MeshNormalNodeMaterial extends NodeMaterial {
  15826. static get type() {
  15827. return 'MeshNormalNodeMaterial';
  15828. }
  15829. /**
  15830. * Constructs a new mesh normal node material.
  15831. *
  15832. * @param {Object} [parameters] - The configuration parameter.
  15833. */
  15834. constructor( parameters ) {
  15835. super();
  15836. /**
  15837. * This flag can be used for type testing.
  15838. *
  15839. * @type {boolean}
  15840. * @readonly
  15841. * @default true
  15842. */
  15843. this.isMeshNormalNodeMaterial = true;
  15844. this.setDefaultValues( _defaultValues$a );
  15845. this.setValues( parameters );
  15846. }
  15847. /**
  15848. * Overwrites the default implementation by computing the diffuse color
  15849. * based on the normal data.
  15850. */
  15851. setupDiffuseColor() {
  15852. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15853. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15854. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15855. }
  15856. }
  15857. /**
  15858. * TSL function for creating an equirect uv node.
  15859. *
  15860. * Can be used to compute texture coordinates for projecting an
  15861. * equirectangular texture onto a mesh for using it as the scene's
  15862. * background.
  15863. *
  15864. * ```js
  15865. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15866. * ```
  15867. *
  15868. * @tsl
  15869. * @function
  15870. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15871. * @returns {Node<vec2>}
  15872. */
  15873. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15874. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15875. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15876. return vec2( u, v );
  15877. } );
  15878. /**
  15879. * This class represents a cube render target. It is a special version
  15880. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15881. *
  15882. * @augments RenderTarget
  15883. */
  15884. class CubeRenderTarget extends RenderTarget {
  15885. /**
  15886. * Constructs a new cube render target.
  15887. *
  15888. * @param {number} [size=1] - The size of the render target.
  15889. * @param {RenderTarget~Options} [options] - The configuration object.
  15890. */
  15891. constructor( size = 1, options = {} ) {
  15892. super( size, size, options );
  15893. /**
  15894. * This flag can be used for type testing.
  15895. *
  15896. * @type {boolean}
  15897. * @readonly
  15898. * @default true
  15899. */
  15900. this.isCubeRenderTarget = true;
  15901. const image = { width: size, height: size, depth: 1 };
  15902. const images = [ image, image, image, image, image, image ];
  15903. /**
  15904. * Overwritten with a different texture type.
  15905. *
  15906. * @type {DataArrayTexture}
  15907. */
  15908. this.texture = new CubeTexture( images );
  15909. this._setTextureOptions( options );
  15910. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  15911. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  15912. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  15913. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  15914. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  15915. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  15916. this.texture.isRenderTargetTexture = true;
  15917. }
  15918. /**
  15919. * Converts the given equirectangular texture to a cube map.
  15920. *
  15921. * @param {Renderer} renderer - The renderer.
  15922. * @param {Texture} texture - The equirectangular texture.
  15923. * @return {CubeRenderTarget} A reference to this cube render target.
  15924. */
  15925. fromEquirectangularTexture( renderer, texture$1 ) {
  15926. const currentMinFilter = texture$1.minFilter;
  15927. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15928. texture$1.generateMipmaps = true;
  15929. this.texture.type = texture$1.type;
  15930. this.texture.colorSpace = texture$1.colorSpace;
  15931. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15932. this.texture.minFilter = texture$1.minFilter;
  15933. this.texture.magFilter = texture$1.magFilter;
  15934. const geometry = new BoxGeometry( 5, 5, 5 );
  15935. const uvNode = equirectUV( positionWorldDirection );
  15936. const material = new NodeMaterial();
  15937. material.colorNode = texture( texture$1, uvNode, 0 );
  15938. material.side = BackSide;
  15939. material.blending = NoBlending;
  15940. const mesh = new Mesh( geometry, material );
  15941. const scene = new Scene();
  15942. scene.add( mesh );
  15943. // Avoid blurred poles
  15944. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15945. const camera = new CubeCamera( 1, 10, this );
  15946. const currentMRT = renderer.getMRT();
  15947. renderer.setMRT( null );
  15948. camera.update( renderer, scene );
  15949. renderer.setMRT( currentMRT );
  15950. texture$1.minFilter = currentMinFilter;
  15951. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15952. mesh.geometry.dispose();
  15953. mesh.material.dispose();
  15954. return this;
  15955. }
  15956. /**
  15957. * Clears this cube render target.
  15958. *
  15959. * @param {Renderer} renderer - The renderer.
  15960. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  15961. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  15962. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  15963. */
  15964. clear( renderer, color = true, depth = true, stencil = true ) {
  15965. const currentRenderTarget = renderer.getRenderTarget();
  15966. for ( let i = 0; i < 6; i ++ ) {
  15967. renderer.setRenderTarget( this, i );
  15968. renderer.clear( color, depth, stencil );
  15969. }
  15970. renderer.setRenderTarget( currentRenderTarget );
  15971. }
  15972. }
  15973. const _cache$1 = new WeakMap();
  15974. /**
  15975. * This node can be used to automatically convert environment maps in the
  15976. * equirectangular format into the cube map format.
  15977. *
  15978. * @augments TempNode
  15979. */
  15980. class CubeMapNode extends TempNode {
  15981. static get type() {
  15982. return 'CubeMapNode';
  15983. }
  15984. /**
  15985. * Constructs a new cube map node.
  15986. *
  15987. * @param {Node} envNode - The node representing the environment map.
  15988. */
  15989. constructor( envNode ) {
  15990. super( 'vec3' );
  15991. /**
  15992. * The node representing the environment map.
  15993. *
  15994. * @type {Node}
  15995. */
  15996. this.envNode = envNode;
  15997. /**
  15998. * A reference to the internal cube texture.
  15999. *
  16000. * @private
  16001. * @type {?CubeTexture}
  16002. * @default null
  16003. */
  16004. this._cubeTexture = null;
  16005. /**
  16006. * A reference to the internal cube texture node.
  16007. *
  16008. * @private
  16009. * @type {CubeTextureNode}
  16010. */
  16011. this._cubeTextureNode = cubeTexture( null );
  16012. const defaultTexture = new CubeTexture();
  16013. defaultTexture.isRenderTargetTexture = true;
  16014. /**
  16015. * A default cube texture that acts as a placeholder.
  16016. * It is used when the conversion from equirectangular to cube
  16017. * map has not finished yet for a given texture.
  16018. *
  16019. * @private
  16020. * @type {CubeTexture}
  16021. */
  16022. this._defaultTexture = defaultTexture;
  16023. /**
  16024. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  16025. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  16026. *
  16027. * @type {string}
  16028. * @default 'render'
  16029. */
  16030. this.updateBeforeType = NodeUpdateType.RENDER;
  16031. }
  16032. updateBefore( frame ) {
  16033. const { renderer, material } = frame;
  16034. const envNode = this.envNode;
  16035. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  16036. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  16037. if ( texture && texture.isTexture ) {
  16038. const mapping = texture.mapping;
  16039. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  16040. // check for converted cubemap map
  16041. if ( _cache$1.has( texture ) ) {
  16042. const cubeMap = _cache$1.get( texture );
  16043. mapTextureMapping( cubeMap, texture.mapping );
  16044. this._cubeTexture = cubeMap;
  16045. } else {
  16046. // create cube map from equirectangular map
  16047. const image = texture.image;
  16048. if ( isEquirectangularMapReady$1( image ) ) {
  16049. const renderTarget = new CubeRenderTarget( image.height );
  16050. renderTarget.fromEquirectangularTexture( renderer, texture );
  16051. mapTextureMapping( renderTarget.texture, texture.mapping );
  16052. this._cubeTexture = renderTarget.texture;
  16053. _cache$1.set( texture, renderTarget.texture );
  16054. texture.addEventListener( 'dispose', onTextureDispose );
  16055. } else {
  16056. // default cube texture as fallback when equirectangular texture is not yet loaded
  16057. this._cubeTexture = this._defaultTexture;
  16058. }
  16059. }
  16060. //
  16061. this._cubeTextureNode.value = this._cubeTexture;
  16062. } else {
  16063. // envNode already refers to a cube map
  16064. this._cubeTextureNode = this.envNode;
  16065. }
  16066. }
  16067. }
  16068. }
  16069. setup( builder ) {
  16070. this.updateBefore( builder );
  16071. return this._cubeTextureNode;
  16072. }
  16073. }
  16074. /**
  16075. * Returns true if the given equirectangular image has been fully loaded
  16076. * and is ready for further processing.
  16077. *
  16078. * @private
  16079. * @param {Image} image - The equirectangular image to check.
  16080. * @return {boolean} Whether the image is ready or not.
  16081. */
  16082. function isEquirectangularMapReady$1( image ) {
  16083. if ( image === null || image === undefined ) return false;
  16084. return image.height > 0;
  16085. }
  16086. /**
  16087. * This function is executed when `dispose()` is called on the equirectangular
  16088. * texture. In this case, the generated cube map with its render target
  16089. * is deleted as well.
  16090. *
  16091. * @private
  16092. * @param {Object} event - The event object.
  16093. */
  16094. function onTextureDispose( event ) {
  16095. const texture = event.target;
  16096. texture.removeEventListener( 'dispose', onTextureDispose );
  16097. const renderTarget = _cache$1.get( texture );
  16098. if ( renderTarget !== undefined ) {
  16099. _cache$1.delete( texture );
  16100. renderTarget.dispose();
  16101. }
  16102. }
  16103. /**
  16104. * This function makes sure the generated cube map uses the correct
  16105. * texture mapping that corresponds to the equirectangular original.
  16106. *
  16107. * @private
  16108. * @param {Texture} texture - The cube texture.
  16109. * @param {number} mapping - The original texture mapping.
  16110. */
  16111. function mapTextureMapping( texture, mapping ) {
  16112. if ( mapping === EquirectangularReflectionMapping ) {
  16113. texture.mapping = CubeReflectionMapping;
  16114. } else if ( mapping === EquirectangularRefractionMapping ) {
  16115. texture.mapping = CubeRefractionMapping;
  16116. }
  16117. }
  16118. /**
  16119. * TSL function for creating a cube map node.
  16120. *
  16121. * @tsl
  16122. * @function
  16123. * @param {Node} envNode - The node representing the environment map.
  16124. * @returns {CubeMapNode}
  16125. */
  16126. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  16127. /**
  16128. * Represents a basic model for Image-based lighting (IBL). The environment
  16129. * is defined via environment maps in the equirectangular or cube map format.
  16130. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  16131. * or {@link MeshPhongNodeMaterial}.
  16132. *
  16133. * @augments LightingNode
  16134. */
  16135. class BasicEnvironmentNode extends LightingNode {
  16136. static get type() {
  16137. return 'BasicEnvironmentNode';
  16138. }
  16139. /**
  16140. * Constructs a new basic environment node.
  16141. *
  16142. * @param {Node} [envNode=null] - A node representing the environment.
  16143. */
  16144. constructor( envNode = null ) {
  16145. super();
  16146. /**
  16147. * A node representing the environment.
  16148. *
  16149. * @type {Node}
  16150. * @default null
  16151. */
  16152. this.envNode = envNode;
  16153. }
  16154. setup( builder ) {
  16155. // environment property is used in the finish() method of BasicLightingModel
  16156. builder.context.environment = cubeMapNode( this.envNode );
  16157. }
  16158. }
  16159. /**
  16160. * A specific version of {@link IrradianceNode} that is only relevant
  16161. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  16162. * requires a special scaling factor for the light map.
  16163. *
  16164. * @augments LightingNode
  16165. */
  16166. class BasicLightMapNode extends LightingNode {
  16167. static get type() {
  16168. return 'BasicLightMapNode';
  16169. }
  16170. /**
  16171. * Constructs a new basic light map node.
  16172. *
  16173. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  16174. */
  16175. constructor( lightMapNode = null ) {
  16176. super();
  16177. /**
  16178. * The light map node.
  16179. *
  16180. * @type {?Node<vec3>}
  16181. */
  16182. this.lightMapNode = lightMapNode;
  16183. }
  16184. setup( builder ) {
  16185. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  16186. const RECIPROCAL_PI = float( 1 / Math.PI );
  16187. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  16188. }
  16189. }
  16190. /**
  16191. * Abstract class for implementing lighting models. The module defines
  16192. * multiple methods that concrete lighting models can implement. These
  16193. * methods are executed at different points during the light evaluation
  16194. * process.
  16195. */
  16196. class LightingModel {
  16197. /**
  16198. * This method is intended for setting up lighting model and context data
  16199. * which are later used in the evaluation process.
  16200. *
  16201. * @abstract
  16202. * @param {NodeBuilder} builder - The current node builder.
  16203. */
  16204. start( builder ) {
  16205. // lights ( direct )
  16206. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  16207. // indirect
  16208. this.indirect( builder );
  16209. }
  16210. /**
  16211. * This method is intended for executing final tasks like final updates
  16212. * to the outgoing light.
  16213. *
  16214. * @abstract
  16215. * @param {NodeBuilder} builder - The current node builder.
  16216. */
  16217. finish( /*builder*/ ) { }
  16218. /**
  16219. * This method is intended for implementing the direct light term and
  16220. * executed during the build process of directional, point and spot light nodes.
  16221. *
  16222. * @abstract
  16223. * @param {Object} lightData - The light data.
  16224. * @param {NodeBuilder} builder - The current node builder.
  16225. */
  16226. direct( /*lightData, builder*/ ) { }
  16227. /**
  16228. * This method is intended for implementing the direct light term for
  16229. * rect area light nodes.
  16230. *
  16231. * @abstract
  16232. * @param {Object} lightData - The light data.
  16233. * @param {NodeBuilder} builder - The current node builder.
  16234. */
  16235. directRectArea( /*lightData, builder*/ ) {}
  16236. /**
  16237. * This method is intended for implementing the indirect light term.
  16238. *
  16239. * @abstract
  16240. * @param {NodeBuilder} builder - The current node builder.
  16241. */
  16242. indirect( /*builder*/ ) { }
  16243. /**
  16244. * This method is intended for implementing the ambient occlusion term.
  16245. * Unlike other methods, this method must be called manually by the lighting
  16246. * model in its indirect term.
  16247. *
  16248. * @abstract
  16249. * @param {NodeBuilder} builder - The current node builder.
  16250. */
  16251. ambientOcclusion( /*input, stack, builder*/ ) { }
  16252. }
  16253. /**
  16254. * Represents the lighting model for unlit materials. The only light contribution
  16255. * is baked indirect lighting modulated with ambient occlusion and the material's
  16256. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  16257. *
  16258. * @augments LightingModel
  16259. */
  16260. class BasicLightingModel extends LightingModel {
  16261. /**
  16262. * Constructs a new basic lighting model.
  16263. */
  16264. constructor() {
  16265. super();
  16266. }
  16267. /**
  16268. * Implements the baked indirect lighting with its modulation.
  16269. *
  16270. * @param {NodeBuilder} builder - The current node builder.
  16271. */
  16272. indirect( { context } ) {
  16273. const ambientOcclusion = context.ambientOcclusion;
  16274. const reflectedLight = context.reflectedLight;
  16275. const irradianceLightMap = context.irradianceLightMap;
  16276. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  16277. // accumulation (baked indirect lighting only)
  16278. if ( irradianceLightMap ) {
  16279. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  16280. } else {
  16281. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  16282. }
  16283. // modulation
  16284. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16285. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  16286. }
  16287. /**
  16288. * Implements the environment mapping.
  16289. *
  16290. * @param {NodeBuilder} builder - The current node builder.
  16291. */
  16292. finish( builder ) {
  16293. const { material, context } = builder;
  16294. const outgoingLight = context.outgoingLight;
  16295. const envNode = builder.context.environment;
  16296. if ( envNode ) {
  16297. switch ( material.combine ) {
  16298. case MultiplyOperation:
  16299. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  16300. break;
  16301. case MixOperation:
  16302. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  16303. break;
  16304. case AddOperation:
  16305. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  16306. break;
  16307. default:
  16308. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  16309. break;
  16310. }
  16311. }
  16312. }
  16313. }
  16314. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  16315. /**
  16316. * Node material version of {@link MeshBasicMaterial}.
  16317. *
  16318. * @augments NodeMaterial
  16319. */
  16320. class MeshBasicNodeMaterial extends NodeMaterial {
  16321. static get type() {
  16322. return 'MeshBasicNodeMaterial';
  16323. }
  16324. /**
  16325. * Constructs a new mesh basic node material.
  16326. *
  16327. * @param {Object} [parameters] - The configuration parameter.
  16328. */
  16329. constructor( parameters ) {
  16330. super();
  16331. /**
  16332. * This flag can be used for type testing.
  16333. *
  16334. * @type {boolean}
  16335. * @readonly
  16336. * @default true
  16337. */
  16338. this.isMeshBasicNodeMaterial = true;
  16339. /**
  16340. * Although the basic material is by definition unlit, we set
  16341. * this property to `true` since we use a lighting model to compute
  16342. * the outgoing light of the fragment shader.
  16343. *
  16344. * @type {boolean}
  16345. * @default true
  16346. */
  16347. this.lights = true;
  16348. this.setDefaultValues( _defaultValues$9 );
  16349. this.setValues( parameters );
  16350. }
  16351. /**
  16352. * Basic materials are not affected by normal and bump maps so we
  16353. * return by default {@link normalViewGeometry}.
  16354. *
  16355. * @return {Node<vec3>} The normal node.
  16356. */
  16357. setupNormal() {
  16358. return directionToFaceDirection( normalViewGeometry ); // see #28839
  16359. }
  16360. /**
  16361. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16362. * to implement the default environment mapping.
  16363. *
  16364. * @param {NodeBuilder} builder - The current node builder.
  16365. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16366. */
  16367. setupEnvironment( builder ) {
  16368. const envNode = super.setupEnvironment( builder );
  16369. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16370. }
  16371. /**
  16372. * This method must be overwritten since light maps are evaluated
  16373. * with a special scaling factor for basic materials.
  16374. *
  16375. * @param {NodeBuilder} builder - The current node builder.
  16376. * @return {?BasicLightMapNode<vec3>} The light map node.
  16377. */
  16378. setupLightMap( builder ) {
  16379. let node = null;
  16380. if ( builder.material.lightMap ) {
  16381. node = new BasicLightMapNode( materialLightMap );
  16382. }
  16383. return node;
  16384. }
  16385. /**
  16386. * The material overwrites this method because `lights` is set to `true` but
  16387. * we still want to return the diffuse color as the outgoing light.
  16388. *
  16389. * @return {Node<vec3>} The outgoing light node.
  16390. */
  16391. setupOutgoingLight() {
  16392. return diffuseColor.rgb;
  16393. }
  16394. /**
  16395. * Setups the lighting model.
  16396. *
  16397. * @return {BasicLightingModel} The lighting model.
  16398. */
  16399. setupLightingModel() {
  16400. return new BasicLightingModel();
  16401. }
  16402. }
  16403. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  16404. // Original approximation by Christophe Schlick '94
  16405. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  16406. // Optimized variant (presented by Epic at SIGGRAPH '13)
  16407. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  16408. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  16409. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  16410. } ); // validated
  16411. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  16412. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  16413. } ); // validated
  16414. const G_BlinnPhong_Implicit = () => float( 0.25 );
  16415. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  16416. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  16417. } );
  16418. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16419. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16420. const dotNH = normalView.dot( halfDir ).clamp();
  16421. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16422. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  16423. const G = G_BlinnPhong_Implicit();
  16424. const D = D_BlinnPhong( { dotNH } );
  16425. return F.mul( G ).mul( D );
  16426. } );
  16427. /**
  16428. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  16429. *
  16430. * @augments BasicLightingModel
  16431. */
  16432. class PhongLightingModel extends BasicLightingModel {
  16433. /**
  16434. * Constructs a new phong lighting model.
  16435. *
  16436. * @param {boolean} [specular=true] - Whether specular is supported or not.
  16437. */
  16438. constructor( specular = true ) {
  16439. super();
  16440. /**
  16441. * Whether specular is supported or not. Set this to `false` if you are
  16442. * looking for a Lambert-like material meaning a material for non-shiny
  16443. * surfaces, without specular highlights.
  16444. *
  16445. * @type {boolean}
  16446. * @default true
  16447. */
  16448. this.specular = specular;
  16449. }
  16450. /**
  16451. * Implements the direct lighting. The specular portion is optional an can be controlled
  16452. * with the {@link PhongLightingModel#specular} flag.
  16453. *
  16454. * @param {Object} lightData - The light data.
  16455. */
  16456. direct( { lightDirection, lightColor, reflectedLight } ) {
  16457. const dotNL = normalView.dot( lightDirection ).clamp();
  16458. const irradiance = dotNL.mul( lightColor );
  16459. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16460. if ( this.specular === true ) {
  16461. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  16462. }
  16463. }
  16464. /**
  16465. * Implements the indirect lighting.
  16466. *
  16467. * @param {NodeBuilder} builder - The current node builder.
  16468. */
  16469. indirect( builder ) {
  16470. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16471. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16472. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16473. }
  16474. }
  16475. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  16476. /**
  16477. * Node material version of {@link MeshLambertMaterial}.
  16478. *
  16479. * @augments NodeMaterial
  16480. */
  16481. class MeshLambertNodeMaterial extends NodeMaterial {
  16482. static get type() {
  16483. return 'MeshLambertNodeMaterial';
  16484. }
  16485. /**
  16486. * Constructs a new mesh lambert node material.
  16487. *
  16488. * @param {Object} [parameters] - The configuration parameter.
  16489. */
  16490. constructor( parameters ) {
  16491. super();
  16492. /**
  16493. * This flag can be used for type testing.
  16494. *
  16495. * @type {boolean}
  16496. * @readonly
  16497. * @default true
  16498. */
  16499. this.isMeshLambertNodeMaterial = true;
  16500. /**
  16501. * Set to `true` because lambert materials react on lights.
  16502. *
  16503. * @type {boolean}
  16504. * @default true
  16505. */
  16506. this.lights = true;
  16507. this.setDefaultValues( _defaultValues$8 );
  16508. this.setValues( parameters );
  16509. }
  16510. /**
  16511. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16512. * to implement the default environment mapping.
  16513. *
  16514. * @param {NodeBuilder} builder - The current node builder.
  16515. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16516. */
  16517. setupEnvironment( builder ) {
  16518. const envNode = super.setupEnvironment( builder );
  16519. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16520. }
  16521. /**
  16522. * Setups the lighting model.
  16523. *
  16524. * @return {PhongLightingModel} The lighting model.
  16525. */
  16526. setupLightingModel( /*builder*/ ) {
  16527. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16528. }
  16529. }
  16530. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16531. /**
  16532. * Node material version of {@link MeshPhongMaterial}.
  16533. *
  16534. * @augments NodeMaterial
  16535. */
  16536. class MeshPhongNodeMaterial extends NodeMaterial {
  16537. static get type() {
  16538. return 'MeshPhongNodeMaterial';
  16539. }
  16540. /**
  16541. * Constructs a new mesh lambert node material.
  16542. *
  16543. * @param {Object} [parameters] - The configuration parameter.
  16544. */
  16545. constructor( parameters ) {
  16546. super();
  16547. /**
  16548. * This flag can be used for type testing.
  16549. *
  16550. * @type {boolean}
  16551. * @readonly
  16552. * @default true
  16553. */
  16554. this.isMeshPhongNodeMaterial = true;
  16555. /**
  16556. * Set to `true` because phong materials react on lights.
  16557. *
  16558. * @type {boolean}
  16559. * @default true
  16560. */
  16561. this.lights = true;
  16562. /**
  16563. * The shininess of phong materials is by default inferred from the `shininess`
  16564. * property. This node property allows to overwrite the default
  16565. * and define the shininess with a node instead.
  16566. *
  16567. * If you don't want to overwrite the shininess but modify the existing
  16568. * value instead, use {@link materialShininess}.
  16569. *
  16570. * @type {?Node<float>}
  16571. * @default null
  16572. */
  16573. this.shininessNode = null;
  16574. /**
  16575. * The specular color of phong materials is by default inferred from the
  16576. * `specular` property. This node property allows to overwrite the default
  16577. * and define the specular color with a node instead.
  16578. *
  16579. * If you don't want to overwrite the specular color but modify the existing
  16580. * value instead, use {@link materialSpecular}.
  16581. *
  16582. * @type {?Node<vec3>}
  16583. * @default null
  16584. */
  16585. this.specularNode = null;
  16586. this.setDefaultValues( _defaultValues$7 );
  16587. this.setValues( parameters );
  16588. }
  16589. /**
  16590. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16591. * to implement the default environment mapping.
  16592. *
  16593. * @param {NodeBuilder} builder - The current node builder.
  16594. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16595. */
  16596. setupEnvironment( builder ) {
  16597. const envNode = super.setupEnvironment( builder );
  16598. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16599. }
  16600. /**
  16601. * Setups the lighting model.
  16602. *
  16603. * @return {PhongLightingModel} The lighting model.
  16604. */
  16605. setupLightingModel( /*builder*/ ) {
  16606. return new PhongLightingModel();
  16607. }
  16608. /**
  16609. * Setups the phong specific node variables.
  16610. *
  16611. * @param {NodeBuilder} builder - The current node builder.
  16612. */
  16613. setupVariants( /*builder*/ ) {
  16614. // SHININESS
  16615. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16616. shininess.assign( shininessNode );
  16617. // SPECULAR COLOR
  16618. const specularNode = this.specularNode || materialSpecular;
  16619. specularColor.assign( specularNode );
  16620. }
  16621. copy( source ) {
  16622. this.shininessNode = source.shininessNode;
  16623. this.specularNode = source.specularNode;
  16624. return super.copy( source );
  16625. }
  16626. }
  16627. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16628. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16629. return float( 0 );
  16630. }
  16631. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16632. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16633. return geometryRoughness;
  16634. } );
  16635. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16636. const { roughness } = inputs;
  16637. const geometryRoughness = getGeometryRoughness();
  16638. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16639. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16640. roughnessFactor = roughnessFactor.min( 1.0 );
  16641. return roughnessFactor;
  16642. } );
  16643. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16644. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16645. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16646. const a2 = alpha.pow2();
  16647. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16648. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16649. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16650. } ).setLayout( {
  16651. name: 'V_GGX_SmithCorrelated',
  16652. type: 'float',
  16653. inputs: [
  16654. { name: 'alpha', type: 'float' },
  16655. { name: 'dotNL', type: 'float' },
  16656. { name: 'dotNV', type: 'float' }
  16657. ]
  16658. } ); // validated
  16659. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16660. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16661. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16662. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16663. const v = div( 0.5, gv.add( gl ) );
  16664. return v;
  16665. } ).setLayout( {
  16666. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16667. type: 'float',
  16668. inputs: [
  16669. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16670. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16671. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16672. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16673. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16674. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16675. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16676. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16677. ]
  16678. } );
  16679. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16680. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16681. // alpha is "roughness squared" in Disney’s reparameterization
  16682. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16683. const a2 = alpha.pow2();
  16684. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16685. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16686. } ).setLayout( {
  16687. name: 'D_GGX',
  16688. type: 'float',
  16689. inputs: [
  16690. { name: 'alpha', type: 'float' },
  16691. { name: 'dotNH', type: 'float' }
  16692. ]
  16693. } ); // validated
  16694. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16695. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16696. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16697. const a2 = alphaT.mul( alphaB );
  16698. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16699. const v2 = v.dot( v );
  16700. const w2 = a2.div( v2 );
  16701. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16702. } ).setLayout( {
  16703. name: 'D_GGX_Anisotropic',
  16704. type: 'float',
  16705. inputs: [
  16706. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16707. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16708. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16709. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16710. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16711. ]
  16712. } );
  16713. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16714. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16715. const alpha = roughness.pow2(); // UE4's roughness
  16716. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16717. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16718. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16719. const dotNH = normalView$1.dot( halfDir ).clamp();
  16720. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16721. let F = F_Schlick( { f0, f90, dotVH } );
  16722. let V, D;
  16723. if ( defined( USE_IRIDESCENCE ) ) {
  16724. F = iridescence.mix( F, f );
  16725. }
  16726. if ( defined( USE_ANISOTROPY ) ) {
  16727. const dotTL = anisotropyT.dot( lightDirection );
  16728. const dotTV = anisotropyT.dot( positionViewDirection );
  16729. const dotTH = anisotropyT.dot( halfDir );
  16730. const dotBL = anisotropyB.dot( lightDirection );
  16731. const dotBV = anisotropyB.dot( positionViewDirection );
  16732. const dotBH = anisotropyB.dot( halfDir );
  16733. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16734. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16735. } else {
  16736. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16737. D = D_GGX( { alpha, dotNH } );
  16738. }
  16739. return F.mul( V ).mul( D );
  16740. } ); // validated
  16741. /**
  16742. * Precomputed DFG LUT for Image-Based Lighting
  16743. * Resolution: 16x16
  16744. * Samples: 4096 per texel
  16745. * Format: RG16F (2 half floats per texel: scale, bias)
  16746. */
  16747. const DATA = new Uint16Array( [
  16748. 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,
  16749. 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,
  16750. 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,
  16751. 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,
  16752. 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,
  16753. 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,
  16754. 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,
  16755. 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,
  16756. 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,
  16757. 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,
  16758. 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,
  16759. 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,
  16760. 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,
  16761. 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,
  16762. 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,
  16763. 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
  16764. ] );
  16765. let lut = null;
  16766. const DFGLUT = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16767. if ( lut === null ) {
  16768. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  16769. lut.name = 'DFG_LUT';
  16770. lut.minFilter = LinearFilter;
  16771. lut.magFilter = LinearFilter;
  16772. lut.wrapS = ClampToEdgeWrapping;
  16773. lut.wrapT = ClampToEdgeWrapping;
  16774. lut.generateMipmaps = false;
  16775. lut.needsUpdate = true;
  16776. }
  16777. const uv = vec2( roughness, dotNV );
  16778. return texture( lut, uv ).rg;
  16779. } );
  16780. // GGX BRDF with multi-scattering energy compensation for direct lighting
  16781. // This provides more accurate energy conservation, especially for rough materials
  16782. // Based on "Practical Multiple Scattering Compensation for Microfacet Models"
  16783. // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf
  16784. const BRDF_GGX_Multiscatter = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16785. // Single-scattering BRDF (standard GGX)
  16786. const singleScatter = BRDF_GGX( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } );
  16787. // Multi-scattering compensation
  16788. const dotNL = normalView.dot( lightDirection ).clamp();
  16789. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16790. // Precomputed DFG values for view and light directions
  16791. const dfgV = DFGLUT( { roughness: _roughness, dotNV } );
  16792. const dfgL = DFGLUT( { roughness: _roughness, dotNV: dotNL } );
  16793. // Single-scattering energy for view and light
  16794. const FssEss_V = f0.mul( dfgV.x ).add( f90.mul( dfgV.y ) );
  16795. const FssEss_L = f0.mul( dfgL.x ).add( f90.mul( dfgL.y ) );
  16796. const Ess_V = dfgV.x.add( dfgV.y );
  16797. const Ess_L = dfgL.x.add( dfgL.y );
  16798. // Energy lost to multiple scattering
  16799. const Ems_V = float( 1.0 ).sub( Ess_V );
  16800. const Ems_L = float( 1.0 ).sub( Ess_L );
  16801. // Average Fresnel reflectance
  16802. const Favg = f0.add( f0.oneMinus().mul( 0.047619 ) ); // 1/21
  16803. // Multiple scattering contribution
  16804. // Uses geometric mean of view and light contributions for better energy distribution
  16805. 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 ) );
  16806. // Energy compensation factor
  16807. const compensationFactor = Ems_V.mul( Ems_L );
  16808. const multiScatter = Fms.mul( compensationFactor );
  16809. return singleScatter.add( multiScatter );
  16810. } );
  16811. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16812. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16813. const fab = DFGLUT( { dotNV, roughness } );
  16814. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16815. } );
  16816. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16817. const x = dotVH.oneMinus().saturate();
  16818. const x2 = x.mul( x );
  16819. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16820. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16821. } ).setLayout( {
  16822. name: 'Schlick_to_F0',
  16823. type: 'vec3',
  16824. inputs: [
  16825. { name: 'f', type: 'vec3' },
  16826. { name: 'f90', type: 'float' },
  16827. { name: 'dotVH', type: 'float' }
  16828. ]
  16829. } );
  16830. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16831. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16832. const alpha = roughness.pow2();
  16833. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16834. const invAlpha = float( 1.0 ).div( alpha );
  16835. const cos2h = dotNH.pow2();
  16836. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16837. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16838. } ).setLayout( {
  16839. name: 'D_Charlie',
  16840. type: 'float',
  16841. inputs: [
  16842. { name: 'roughness', type: 'float' },
  16843. { name: 'dotNH', type: 'float' }
  16844. ]
  16845. } );
  16846. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16847. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  16848. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  16849. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  16850. } ).setLayout( {
  16851. name: 'V_Neubelt',
  16852. type: 'float',
  16853. inputs: [
  16854. { name: 'dotNV', type: 'float' },
  16855. { name: 'dotNL', type: 'float' }
  16856. ]
  16857. } );
  16858. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16859. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16860. const dotNL = normalView.dot( lightDirection ).clamp();
  16861. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16862. const dotNH = normalView.dot( halfDir ).clamp();
  16863. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  16864. const V = V_Neubelt( { dotNV, dotNL } );
  16865. return sheen.mul( D ).mul( V );
  16866. } );
  16867. // Rect Area Light
  16868. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  16869. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  16870. // code: https://github.com/selfshadow/ltc_code/
  16871. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  16872. const LUT_SIZE = 64.0;
  16873. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  16874. const LUT_BIAS = 0.5 / LUT_SIZE;
  16875. const dotNV = N.dot( V ).saturate();
  16876. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  16877. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  16878. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  16879. return uv;
  16880. } ).setLayout( {
  16881. name: 'LTC_Uv',
  16882. type: 'vec2',
  16883. inputs: [
  16884. { name: 'N', type: 'vec3' },
  16885. { name: 'V', type: 'vec3' },
  16886. { name: 'roughness', type: 'float' }
  16887. ]
  16888. } );
  16889. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  16890. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  16891. // An approximation of the form factor of a horizon-clipped rectangle.
  16892. const l = f.length();
  16893. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  16894. } ).setLayout( {
  16895. name: 'LTC_ClippedSphereFormFactor',
  16896. type: 'float',
  16897. inputs: [
  16898. { name: 'f', type: 'vec3' }
  16899. ]
  16900. } );
  16901. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  16902. const x = v1.dot( v2 );
  16903. const y = x.abs().toVar();
  16904. // rational polynomial approximation to theta / sin( theta ) / 2PI
  16905. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  16906. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  16907. const v = a.div( b );
  16908. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  16909. return v1.cross( v2 ).mul( theta_sintheta );
  16910. } ).setLayout( {
  16911. name: 'LTC_EdgeVectorFormFactor',
  16912. type: 'vec3',
  16913. inputs: [
  16914. { name: 'v1', type: 'vec3' },
  16915. { name: 'v2', type: 'vec3' }
  16916. ]
  16917. } );
  16918. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  16919. // bail if point is on back side of plane of light
  16920. // assumes ccw winding order of light vertices
  16921. const v1 = p1.sub( p0 ).toVar();
  16922. const v2 = p3.sub( p0 ).toVar();
  16923. const lightNormal = v1.cross( v2 );
  16924. const result = vec3().toVar();
  16925. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16926. // construct orthonormal basis around N
  16927. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16928. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16929. // compute transform
  16930. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16931. // transform rect
  16932. // & project rect onto sphere
  16933. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16934. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16935. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16936. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16937. // calculate vector form factor
  16938. const vectorFormFactor = vec3( 0 ).toVar();
  16939. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16940. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16941. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16942. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16943. // adjust for horizon clipping
  16944. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16945. } );
  16946. return result;
  16947. } ).setLayout( {
  16948. name: 'LTC_Evaluate',
  16949. type: 'vec3',
  16950. inputs: [
  16951. { name: 'N', type: 'vec3' },
  16952. { name: 'V', type: 'vec3' },
  16953. { name: 'P', type: 'vec3' },
  16954. { name: 'mInv', type: 'mat3' },
  16955. { name: 'p0', type: 'vec3' },
  16956. { name: 'p1', type: 'vec3' },
  16957. { name: 'p2', type: 'vec3' },
  16958. { name: 'p3', type: 'vec3' }
  16959. ]
  16960. } );
  16961. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16962. // bail if point is on back side of plane of light
  16963. // assumes ccw winding order of light vertices
  16964. const v1 = p1.sub( p0 ).toVar();
  16965. const v2 = p3.sub( p0 ).toVar();
  16966. const lightNormal = v1.cross( v2 );
  16967. const result = vec3().toVar();
  16968. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16969. // transform rect
  16970. // & project rect onto sphere
  16971. const coords0 = p0.sub( P ).normalize().toVar();
  16972. const coords1 = p1.sub( P ).normalize().toVar();
  16973. const coords2 = p2.sub( P ).normalize().toVar();
  16974. const coords3 = p3.sub( P ).normalize().toVar();
  16975. // calculate vector form factor
  16976. const vectorFormFactor = vec3( 0 ).toVar();
  16977. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16978. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16979. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16980. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16981. // adjust for horizon clipping
  16982. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16983. } );
  16984. return result;
  16985. } ).setLayout( {
  16986. name: 'LTC_Evaluate',
  16987. type: 'vec3',
  16988. inputs: [
  16989. { name: 'P', type: 'vec3' },
  16990. { name: 'p0', type: 'vec3' },
  16991. { name: 'p1', type: 'vec3' },
  16992. { name: 'p2', type: 'vec3' },
  16993. { name: 'p3', type: 'vec3' }
  16994. ]
  16995. } );
  16996. // Mipped Bicubic Texture Filtering by N8
  16997. // https://www.shadertoy.com/view/Dl2SDW
  16998. const bC = 1.0 / 6.0;
  16999. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  17000. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  17001. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  17002. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  17003. const g0 = ( a ) => w0( a ).add( w1( a ) );
  17004. const g1 = ( a ) => w2( a ).add( w3( a ) );
  17005. // h0 and h1 are the two offset functions
  17006. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  17007. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  17008. const bicubic = ( textureNode, texelSize, lod ) => {
  17009. const uv = textureNode.uvNode;
  17010. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  17011. const iuv = floor( uvScaled );
  17012. const fuv = fract( uvScaled );
  17013. const g0x = g0( fuv.x );
  17014. const g1x = g1( fuv.x );
  17015. const h0x = h0( fuv.x );
  17016. const h1x = h1( fuv.x );
  17017. const h0y = h0( fuv.y );
  17018. const h1y = h1( fuv.y );
  17019. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  17020. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  17021. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  17022. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  17023. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  17024. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  17025. return a.add( b );
  17026. };
  17027. /**
  17028. * Applies mipped bicubic texture filtering to the given texture node.
  17029. *
  17030. * @tsl
  17031. * @function
  17032. * @param {TextureNode} textureNode - The texture node that should be filtered.
  17033. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  17034. * @return {Node} The filtered texture sample.
  17035. */
  17036. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  17037. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  17038. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  17039. const fLodSizeInv = div( 1.0, fLodSize );
  17040. const cLodSizeInv = div( 1.0, cLodSize );
  17041. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  17042. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  17043. return fract( lodNode ).mix( fSample, cSample );
  17044. } );
  17045. /**
  17046. * Applies mipped bicubic texture filtering to the given texture node.
  17047. *
  17048. * @tsl
  17049. * @function
  17050. * @param {TextureNode} textureNode - The texture node that should be filtered.
  17051. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  17052. * @return {Node} The filtered texture sample.
  17053. */
  17054. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  17055. const lod = strength.mul( maxMipLevel( textureNode ) );
  17056. return textureBicubicLevel( textureNode, lod );
  17057. } );
  17058. //
  17059. // Transmission
  17060. //
  17061. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  17062. // Direction of refracted light.
  17063. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  17064. // Compute rotation-independent scaling of the model matrix.
  17065. const modelScale = vec3(
  17066. length( modelMatrix[ 0 ].xyz ),
  17067. length( modelMatrix[ 1 ].xyz ),
  17068. length( modelMatrix[ 2 ].xyz )
  17069. );
  17070. // The thickness is specified in local space.
  17071. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  17072. } ).setLayout( {
  17073. name: 'getVolumeTransmissionRay',
  17074. type: 'vec3',
  17075. inputs: [
  17076. { name: 'n', type: 'vec3' },
  17077. { name: 'v', type: 'vec3' },
  17078. { name: 'thickness', type: 'float' },
  17079. { name: 'ior', type: 'float' },
  17080. { name: 'modelMatrix', type: 'mat4' }
  17081. ]
  17082. } );
  17083. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  17084. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  17085. // an IOR of 1.5 results in the default amount of microfacet refraction.
  17086. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  17087. } ).setLayout( {
  17088. name: 'applyIorToRoughness',
  17089. type: 'float',
  17090. inputs: [
  17091. { name: 'roughness', type: 'float' },
  17092. { name: 'ior', type: 'float' }
  17093. ]
  17094. } );
  17095. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  17096. const viewportFrontSideTexture = /*@__PURE__*/ viewportOpaqueMipTexture();
  17097. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  17098. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  17099. const transmissionSample = vTexture.sample( fragCoord );
  17100. //const transmissionSample = viewportMipTexture( fragCoord );
  17101. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  17102. return textureBicubicLevel( transmissionSample, lod );
  17103. } );
  17104. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  17105. If( attenuationDistance.notEqual( 0 ), () => {
  17106. // Compute light attenuation using Beer's law.
  17107. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  17108. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  17109. return transmittance;
  17110. } );
  17111. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  17112. return vec3( 1.0 );
  17113. } ).setLayout( {
  17114. name: 'volumeAttenuation',
  17115. type: 'vec3',
  17116. inputs: [
  17117. { name: 'transmissionDistance', type: 'float' },
  17118. { name: 'attenuationColor', type: 'vec3' },
  17119. { name: 'attenuationDistance', type: 'float' }
  17120. ]
  17121. } );
  17122. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  17123. let transmittedLight, transmittance;
  17124. if ( dispersion ) {
  17125. transmittedLight = vec4().toVar();
  17126. transmittance = vec3().toVar();
  17127. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  17128. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  17129. Loop( { start: 0, end: 3 }, ( { i } ) => {
  17130. const ior = iors.element( i );
  17131. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  17132. const refractedRayExit = position.add( transmissionRay );
  17133. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  17134. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  17135. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  17136. refractionCoords.addAssign( 1.0 );
  17137. refractionCoords.divAssign( 2.0 );
  17138. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  17139. // Sample framebuffer to get pixel the refracted ray hits.
  17140. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  17141. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  17142. transmittedLight.a.addAssign( transmissionSample.a );
  17143. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  17144. } );
  17145. transmittedLight.a.divAssign( 3.0 );
  17146. } else {
  17147. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  17148. const refractedRayExit = position.add( transmissionRay );
  17149. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  17150. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  17151. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  17152. refractionCoords.addAssign( 1.0 );
  17153. refractionCoords.divAssign( 2.0 );
  17154. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  17155. // Sample framebuffer to get pixel the refracted ray hits.
  17156. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  17157. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  17158. }
  17159. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  17160. const dotNV = n.dot( v ).clamp();
  17161. // Get the specular component.
  17162. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  17163. dotNV,
  17164. specularColor,
  17165. specularF90,
  17166. roughness
  17167. } ) );
  17168. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  17169. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  17170. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  17171. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  17172. } );
  17173. //
  17174. // Iridescence
  17175. //
  17176. // XYZ to linear-sRGB color space
  17177. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  17178. 3.2404542, -0.969266, 0.0556434,
  17179. -1.5371385, 1.8760108, -0.2040259,
  17180. -0.4985314, 0.0415560, 1.0572252
  17181. );
  17182. // Assume air interface for top
  17183. // Note: We don't handle the case fresnel0 == 1
  17184. const Fresnel0ToIor = ( fresnel0 ) => {
  17185. const sqrtF0 = fresnel0.sqrt();
  17186. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  17187. };
  17188. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  17189. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  17190. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  17191. };
  17192. // Fresnel equations for dielectric/dielectric interfaces.
  17193. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  17194. // Evaluation XYZ sensitivity curves in Fourier space
  17195. const evalSensitivity = ( OPD, shift ) => {
  17196. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  17197. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  17198. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  17199. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  17200. 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() );
  17201. 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() );
  17202. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  17203. const rgb = XYZ_TO_REC709.mul( xyz );
  17204. return rgb;
  17205. };
  17206. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  17207. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  17208. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  17209. // Evaluate the cosTheta on the base layer (Snell law)
  17210. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  17211. // Handle TIR:
  17212. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  17213. If( cosTheta2Sq.lessThan( 0 ), () => {
  17214. return vec3( 1.0 );
  17215. } );
  17216. const cosTheta2 = cosTheta2Sq.sqrt();
  17217. // First interface
  17218. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  17219. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  17220. //const R21 = R12;
  17221. const T121 = R12.oneMinus();
  17222. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  17223. const phi21 = float( Math.PI ).sub( phi12 );
  17224. // Second interface
  17225. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  17226. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  17227. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  17228. const phi23 = vec3(
  17229. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17230. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17231. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  17232. );
  17233. // Phase shift
  17234. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  17235. const phi = vec3( phi21 ).add( phi23 );
  17236. // Compound terms
  17237. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  17238. const r123 = R123.sqrt();
  17239. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  17240. // Reflectance term for m = 0 (DC term amplitude)
  17241. const C0 = R12.add( Rs );
  17242. const I = C0.toVar();
  17243. // Reflectance term for m > 0 (pairs of diracs)
  17244. const Cm = Rs.sub( T121 ).toVar();
  17245. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  17246. Cm.mulAssign( r123 );
  17247. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  17248. I.addAssign( Cm.mul( Sm ) );
  17249. } );
  17250. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  17251. return I.max( vec3( 0.0 ) );
  17252. } ).setLayout( {
  17253. name: 'evalIridescence',
  17254. type: 'vec3',
  17255. inputs: [
  17256. { name: 'outsideIOR', type: 'float' },
  17257. { name: 'eta2', type: 'float' },
  17258. { name: 'cosTheta1', type: 'float' },
  17259. { name: 'thinFilmThickness', type: 'float' },
  17260. { name: 'baseF0', type: 'vec3' }
  17261. ]
  17262. } );
  17263. //
  17264. // Sheen
  17265. //
  17266. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  17267. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF".
  17268. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  17269. const dotNV = normal.dot( viewDir ).saturate();
  17270. const r2 = roughness.mul( roughness );
  17271. const rInv = roughness.add( 0.1 ).reciprocal();
  17272. const a = float( -1.9362 ).add( roughness.mul( 1.0678 ) ).add( r2.mul( 0.4573 ) ).sub( rInv.mul( 0.8469 ) );
  17273. const b = float( -0.6014 ).add( roughness.mul( 0.5538 ) ).sub( r2.mul( 0.4670 ) ).sub( rInv.mul( 0.1255 ) );
  17274. const DG = a.mul( dotNV ).add( b ).exp();
  17275. return DG.saturate();
  17276. } );
  17277. const clearcoatF0 = vec3( 0.04 );
  17278. const clearcoatF90 = float( 1 );
  17279. /**
  17280. * Represents the lighting model for a PBR material.
  17281. *
  17282. * @augments LightingModel
  17283. */
  17284. class PhysicalLightingModel extends LightingModel {
  17285. /**
  17286. * Constructs a new physical lighting model.
  17287. *
  17288. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17289. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17290. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17291. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17292. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17293. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17294. */
  17295. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  17296. super();
  17297. /**
  17298. * Whether clearcoat is supported or not.
  17299. *
  17300. * @type {boolean}
  17301. * @default false
  17302. */
  17303. this.clearcoat = clearcoat;
  17304. /**
  17305. * Whether sheen is supported or not.
  17306. *
  17307. * @type {boolean}
  17308. * @default false
  17309. */
  17310. this.sheen = sheen;
  17311. /**
  17312. * Whether iridescence is supported or not.
  17313. *
  17314. * @type {boolean}
  17315. * @default false
  17316. */
  17317. this.iridescence = iridescence;
  17318. /**
  17319. * Whether anisotropy is supported or not.
  17320. *
  17321. * @type {boolean}
  17322. * @default false
  17323. */
  17324. this.anisotropy = anisotropy;
  17325. /**
  17326. * Whether transmission is supported or not.
  17327. *
  17328. * @type {boolean}
  17329. * @default false
  17330. */
  17331. this.transmission = transmission;
  17332. /**
  17333. * Whether dispersion is supported or not.
  17334. *
  17335. * @type {boolean}
  17336. * @default false
  17337. */
  17338. this.dispersion = dispersion;
  17339. /**
  17340. * The clear coat radiance.
  17341. *
  17342. * @type {?Node}
  17343. * @default null
  17344. */
  17345. this.clearcoatRadiance = null;
  17346. /**
  17347. * The clear coat specular direct.
  17348. *
  17349. * @type {?Node}
  17350. * @default null
  17351. */
  17352. this.clearcoatSpecularDirect = null;
  17353. /**
  17354. * The clear coat specular indirect.
  17355. *
  17356. * @type {?Node}
  17357. * @default null
  17358. */
  17359. this.clearcoatSpecularIndirect = null;
  17360. /**
  17361. * The sheen specular direct.
  17362. *
  17363. * @type {?Node}
  17364. * @default null
  17365. */
  17366. this.sheenSpecularDirect = null;
  17367. /**
  17368. * The sheen specular indirect.
  17369. *
  17370. * @type {?Node}
  17371. * @default null
  17372. */
  17373. this.sheenSpecularIndirect = null;
  17374. /**
  17375. * The iridescence Fresnel.
  17376. *
  17377. * @type {?Node}
  17378. * @default null
  17379. */
  17380. this.iridescenceFresnel = null;
  17381. /**
  17382. * The iridescence F0.
  17383. *
  17384. * @type {?Node}
  17385. * @default null
  17386. */
  17387. this.iridescenceF0 = null;
  17388. /**
  17389. * The iridescence F0 dielectric.
  17390. *
  17391. * @type {?Node}
  17392. * @default null
  17393. */
  17394. this.iridescenceF0Dielectric = null;
  17395. /**
  17396. * The iridescence F0 metallic.
  17397. *
  17398. * @type {?Node}
  17399. * @default null
  17400. */
  17401. this.iridescenceF0Metallic = null;
  17402. }
  17403. /**
  17404. * Depending on what features are requested, the method prepares certain node variables
  17405. * which are later used for lighting computations.
  17406. *
  17407. * @param {NodeBuilder} builder - The current node builder.
  17408. */
  17409. start( builder ) {
  17410. if ( this.clearcoat === true ) {
  17411. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  17412. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  17413. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  17414. }
  17415. if ( this.sheen === true ) {
  17416. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  17417. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  17418. }
  17419. if ( this.iridescence === true ) {
  17420. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  17421. const iridescenceFresnelDielectric = evalIridescence( {
  17422. outsideIOR: float( 1.0 ),
  17423. eta2: iridescenceIOR,
  17424. cosTheta1: dotNVi,
  17425. thinFilmThickness: iridescenceThickness,
  17426. baseF0: specularColor
  17427. } );
  17428. const iridescenceFresnelMetallic = evalIridescence( {
  17429. outsideIOR: float( 1.0 ),
  17430. eta2: iridescenceIOR,
  17431. cosTheta1: dotNVi,
  17432. thinFilmThickness: iridescenceThickness,
  17433. baseF0: diffuseColor.rgb
  17434. } );
  17435. this.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, metalness );
  17436. this.iridescenceF0Dielectric = Schlick_to_F0( { f: iridescenceFresnelDielectric, f90: 1.0, dotVH: dotNVi } );
  17437. this.iridescenceF0Metallic = Schlick_to_F0( { f: iridescenceFresnelMetallic, f90: 1.0, dotVH: dotNVi } );
  17438. this.iridescenceF0 = mix( this.iridescenceF0Dielectric, this.iridescenceF0Metallic, metalness );
  17439. }
  17440. if ( this.transmission === true ) {
  17441. const position = positionWorld;
  17442. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  17443. const n = normalWorld;
  17444. const context = builder.context;
  17445. context.backdrop = getIBLVolumeRefraction(
  17446. n,
  17447. v,
  17448. roughness,
  17449. diffuseContribution,
  17450. specularColorBlended,
  17451. specularF90, // specularF90
  17452. position, // positionWorld
  17453. modelWorldMatrix, // modelMatrix
  17454. cameraViewMatrix, // viewMatrix
  17455. cameraProjectionMatrix, // projMatrix
  17456. ior,
  17457. thickness,
  17458. attenuationColor,
  17459. attenuationDistance,
  17460. this.dispersion ? dispersion : null
  17461. );
  17462. context.backdropAlpha = transmission;
  17463. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  17464. }
  17465. super.start( builder );
  17466. }
  17467. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  17468. // Approximates multi-scattering in order to preserve energy.
  17469. // http://www.jcgt.org/published/0008/01/03/
  17470. computeMultiscattering( singleScatter, multiScatter, specularF90, f0, iridescenceF0 = null ) {
  17471. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17472. const fab = DFGLUT( { roughness, dotNV } );
  17473. const Fr = iridescenceF0 ? iridescence.mix( f0, iridescenceF0 ) : f0;
  17474. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17475. const Ess = fab.x.add( fab.y );
  17476. const Ems = Ess.oneMinus();
  17477. const Favg = Fr.add( Fr.oneMinus().mul( 0.047619 ) ); // 1/21
  17478. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  17479. singleScatter.addAssign( FssEss );
  17480. multiScatter.addAssign( Fms.mul( Ems ) );
  17481. }
  17482. /**
  17483. * Implements the direct light.
  17484. *
  17485. * @param {Object} lightData - The light data.
  17486. * @param {NodeBuilder} builder - The current node builder.
  17487. */
  17488. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  17489. const dotNL = normalView.dot( lightDirection ).clamp();
  17490. const irradiance = dotNL.mul( lightColor ).toVar();
  17491. if ( this.sheen === true ) {
  17492. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  17493. const sheenAlbedoV = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17494. const sheenAlbedoL = IBLSheenBRDF( { normal: normalView, viewDir: lightDirection, roughness: sheenRoughness } );
  17495. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedoV.max( sheenAlbedoL ) ).oneMinus();
  17496. irradiance.mulAssign( sheenEnergyComp );
  17497. }
  17498. if ( this.clearcoat === true ) {
  17499. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  17500. const ccIrradiance = dotNLcc.mul( lightColor );
  17501. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  17502. }
  17503. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ) );
  17504. 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 } ) ) );
  17505. }
  17506. /**
  17507. * This method is intended for implementing the direct light term for
  17508. * rect area light nodes.
  17509. *
  17510. * @param {Object} input - The input data.
  17511. * @param {NodeBuilder} builder - The current node builder.
  17512. */
  17513. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  17514. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17515. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17516. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17517. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17518. const N = normalView;
  17519. const V = positionViewDirection;
  17520. const P = positionView.toVar();
  17521. const uv = LTC_Uv( { N, V, roughness } );
  17522. const t1 = ltc_1.sample( uv ).toVar();
  17523. const t2 = ltc_2.sample( uv ).toVar();
  17524. const mInv = mat3(
  17525. vec3( t1.x, 0, t1.y ),
  17526. vec3( 0, 1, 0 ),
  17527. vec3( t1.z, 0, t1.w )
  17528. ).toVar();
  17529. // LTC Fresnel Approximation by Stephen Hill
  17530. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  17531. const fresnel = specularColorBlended.mul( t2.x ).add( specularF90.sub( specularColorBlended ).mul( t2.y ) ).toVar();
  17532. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  17533. 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 } ) ) );
  17534. if ( this.clearcoat === true ) {
  17535. const Ncc = clearcoatNormalView;
  17536. const uvClearcoat = LTC_Uv( { N: Ncc, V, roughness: clearcoatRoughness } );
  17537. const t1Clearcoat = ltc_1.sample( uvClearcoat );
  17538. const t2Clearcoat = ltc_2.sample( uvClearcoat );
  17539. const mInvClearcoat = mat3(
  17540. vec3( t1Clearcoat.x, 0, t1Clearcoat.y ),
  17541. vec3( 0, 1, 0 ),
  17542. vec3( t1Clearcoat.z, 0, t1Clearcoat.w )
  17543. );
  17544. // LTC Fresnel Approximation for clearcoat
  17545. const fresnelClearcoat = clearcoatF0.mul( t2Clearcoat.x ).add( clearcoatF90.sub( clearcoatF0 ).mul( t2Clearcoat.y ) );
  17546. this.clearcoatSpecularDirect.addAssign( lightColor.mul( fresnelClearcoat ).mul( LTC_Evaluate( { N: Ncc, V, P, mInv: mInvClearcoat, p0, p1, p2, p3 } ) ) );
  17547. }
  17548. }
  17549. /**
  17550. * Implements the indirect lighting.
  17551. *
  17552. * @param {NodeBuilder} builder - The current node builder.
  17553. */
  17554. indirect( builder ) {
  17555. this.indirectDiffuse( builder );
  17556. this.indirectSpecular( builder );
  17557. this.ambientOcclusion( builder );
  17558. }
  17559. /**
  17560. * Implements the indirect diffuse term.
  17561. *
  17562. * @param {NodeBuilder} builder - The current node builder.
  17563. */
  17564. indirectDiffuse( builder ) {
  17565. const { irradiance, reflectedLight } = builder.context;
  17566. const diffuse = irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ).toVar();
  17567. if ( this.sheen === true ) {
  17568. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17569. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17570. diffuse.mulAssign( sheenEnergyComp );
  17571. }
  17572. reflectedLight.indirectDiffuse.addAssign( diffuse );
  17573. }
  17574. /**
  17575. * Implements the indirect specular term.
  17576. *
  17577. * @param {NodeBuilder} builder - The current node builder.
  17578. */
  17579. indirectSpecular( builder ) {
  17580. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  17581. if ( this.sheen === true ) {
  17582. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  17583. sheen,
  17584. IBLSheenBRDF( {
  17585. normal: normalView,
  17586. viewDir: positionViewDirection,
  17587. roughness: sheenRoughness
  17588. } )
  17589. ) );
  17590. }
  17591. if ( this.clearcoat === true ) {
  17592. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17593. const clearcoatEnv = EnvironmentBRDF( {
  17594. dotNV: dotNVcc,
  17595. specularColor: clearcoatF0,
  17596. specularF90: clearcoatF90,
  17597. roughness: clearcoatRoughness
  17598. } );
  17599. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  17600. }
  17601. // Both indirect specular and indirect diffuse light accumulate here
  17602. // Compute multiscattering separately for dielectric and metallic, then mix
  17603. const singleScatteringDielectric = vec3().toVar( 'singleScatteringDielectric' );
  17604. const multiScatteringDielectric = vec3().toVar( 'multiScatteringDielectric' );
  17605. const singleScatteringMetallic = vec3().toVar( 'singleScatteringMetallic' );
  17606. const multiScatteringMetallic = vec3().toVar( 'multiScatteringMetallic' );
  17607. this.computeMultiscattering( singleScatteringDielectric, multiScatteringDielectric, specularF90, specularColor, this.iridescenceF0Dielectric );
  17608. this.computeMultiscattering( singleScatteringMetallic, multiScatteringMetallic, specularF90, diffuseColor.rgb, this.iridescenceF0Metallic );
  17609. // Mix based on metalness
  17610. const singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, metalness );
  17611. const multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, metalness );
  17612. // Diffuse energy conservation uses dielectric path
  17613. const totalScatteringDielectric = singleScatteringDielectric.add( multiScatteringDielectric );
  17614. const diffuse = diffuseContribution.mul( totalScatteringDielectric.oneMinus() );
  17615. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  17616. const indirectSpecular = radiance.mul( singleScattering ).add( multiScattering.mul( cosineWeightedIrradiance ) ).toVar();
  17617. const indirectDiffuse = diffuse.mul( cosineWeightedIrradiance ).toVar();
  17618. if ( this.sheen === true ) {
  17619. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17620. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17621. indirectSpecular.mulAssign( sheenEnergyComp );
  17622. indirectDiffuse.mulAssign( sheenEnergyComp );
  17623. }
  17624. reflectedLight.indirectSpecular.addAssign( indirectSpecular );
  17625. reflectedLight.indirectDiffuse.addAssign( indirectDiffuse );
  17626. }
  17627. /**
  17628. * Implements the ambient occlusion term.
  17629. *
  17630. * @param {NodeBuilder} builder - The current node builder.
  17631. */
  17632. ambientOcclusion( builder ) {
  17633. const { ambientOcclusion, reflectedLight } = builder.context;
  17634. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17635. const aoNV = dotNV.add( ambientOcclusion );
  17636. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17637. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17638. if ( this.clearcoat === true ) {
  17639. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17640. }
  17641. if ( this.sheen === true ) {
  17642. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  17643. }
  17644. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17645. reflectedLight.indirectSpecular.mulAssign( aoNode );
  17646. }
  17647. /**
  17648. * Used for final lighting accumulations depending on the requested features.
  17649. *
  17650. * @param {NodeBuilder} builder - The current node builder.
  17651. */
  17652. finish( { context } ) {
  17653. const { outgoingLight } = context;
  17654. if ( this.clearcoat === true ) {
  17655. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17656. const Fcc = F_Schlick( {
  17657. dotVH: dotNVcc,
  17658. f0: clearcoatF0,
  17659. f90: clearcoatF90
  17660. } );
  17661. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17662. outgoingLight.assign( clearcoatLight );
  17663. }
  17664. if ( this.sheen === true ) {
  17665. const sheenLight = outgoingLight.add( this.sheenSpecularDirect, this.sheenSpecularIndirect.mul( 1.0 / Math.PI ) );
  17666. outgoingLight.assign( sheenLight );
  17667. }
  17668. }
  17669. }
  17670. // These defines must match with PMREMGenerator
  17671. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17672. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17673. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17674. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17675. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17676. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17677. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17678. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17679. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17680. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17681. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17682. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17683. // These shader functions convert between the UV coordinates of a single face of
  17684. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17685. // sampling a textureCube (not generally normalized ).
  17686. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17687. const absDirection = vec3( abs( direction ) ).toVar();
  17688. const face = float( -1 ).toVar();
  17689. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17690. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17691. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17692. } ).Else( () => {
  17693. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17694. } );
  17695. } ).Else( () => {
  17696. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17697. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17698. } ).Else( () => {
  17699. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17700. } );
  17701. } );
  17702. return face;
  17703. } ).setLayout( {
  17704. name: 'getFace',
  17705. type: 'float',
  17706. inputs: [
  17707. { name: 'direction', type: 'vec3' }
  17708. ]
  17709. } );
  17710. // RH coordinate system; PMREM face-indexing convention
  17711. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17712. const uv = vec2().toVar();
  17713. If( face.equal( 0.0 ), () => {
  17714. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17715. } ).ElseIf( face.equal( 1.0 ), () => {
  17716. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17717. } ).ElseIf( face.equal( 2.0 ), () => {
  17718. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17719. } ).ElseIf( face.equal( 3.0 ), () => {
  17720. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17721. } ).ElseIf( face.equal( 4.0 ), () => {
  17722. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17723. } ).Else( () => {
  17724. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17725. } );
  17726. return mul( 0.5, uv.add( 1.0 ) );
  17727. } ).setLayout( {
  17728. name: 'getUV',
  17729. type: 'vec2',
  17730. inputs: [
  17731. { name: 'direction', type: 'vec3' },
  17732. { name: 'face', type: 'float' }
  17733. ]
  17734. } );
  17735. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17736. const mip = float( 0.0 ).toVar();
  17737. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17738. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17739. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17740. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17741. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17742. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17743. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17744. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17745. } ).Else( () => {
  17746. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17747. } );
  17748. return mip;
  17749. } ).setLayout( {
  17750. name: 'roughnessToMip',
  17751. type: 'float',
  17752. inputs: [
  17753. { name: 'roughness', type: 'float' }
  17754. ]
  17755. } );
  17756. // RH coordinate system; PMREM face-indexing convention
  17757. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17758. const uv = uv_immutable.toVar();
  17759. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17760. const direction = vec3( uv, 1.0 ).toVar();
  17761. If( face.equal( 0.0 ), () => {
  17762. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17763. } ).ElseIf( face.equal( 1.0 ), () => {
  17764. direction.assign( direction.xzy );
  17765. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17766. } ).ElseIf( face.equal( 2.0 ), () => {
  17767. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17768. } ).ElseIf( face.equal( 3.0 ), () => {
  17769. direction.assign( direction.zyx );
  17770. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17771. } ).ElseIf( face.equal( 4.0 ), () => {
  17772. direction.assign( direction.xzy );
  17773. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17774. } ).ElseIf( face.equal( 5.0 ), () => {
  17775. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17776. } );
  17777. return direction;
  17778. } ).setLayout( {
  17779. name: 'getDirection',
  17780. type: 'vec3',
  17781. inputs: [
  17782. { name: 'uv', type: 'vec2' },
  17783. { name: 'face', type: 'float' }
  17784. ]
  17785. } );
  17786. //
  17787. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17788. const roughness = float( roughness_immutable );
  17789. const sampleDir = vec3( sampleDir_immutable );
  17790. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  17791. const mipF = fract( mip );
  17792. const mipInt = floor( mip );
  17793. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17794. If( mipF.notEqual( 0.0 ), () => {
  17795. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17796. color0.assign( mix( color0, color1, mipF ) );
  17797. } );
  17798. return color0;
  17799. } );
  17800. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17801. const mipInt = float( mipInt_immutable ).toVar();
  17802. const direction = vec3( direction_immutable );
  17803. const face = float( getFace( direction ) ).toVar();
  17804. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  17805. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  17806. const faceSize = float( exp2( mipInt ) ).toVar();
  17807. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  17808. If( face.greaterThan( 2.0 ), () => {
  17809. uv.y.addAssign( faceSize );
  17810. face.subAssign( 3.0 );
  17811. } );
  17812. uv.x.addAssign( face.mul( faceSize ) );
  17813. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  17814. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  17815. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  17816. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  17817. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  17818. } );
  17819. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17820. const cosTheta = cos( theta );
  17821. // Rodrigues' axis-angle rotation
  17822. const sampleDirection = outputDirection.mul( cosTheta )
  17823. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  17824. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  17825. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17826. } );
  17827. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17828. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  17829. If( axis.equal( vec3( 0.0 ) ), () => {
  17830. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  17831. } );
  17832. axis.assign( normalize( axis ) );
  17833. const gl_FragColor = vec3().toVar();
  17834. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17835. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17836. If( i.greaterThanEqual( samples ), () => {
  17837. Break();
  17838. } );
  17839. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17840. 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 } ) ) );
  17841. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17842. } );
  17843. return vec4( gl_FragColor, 1 );
  17844. } );
  17845. // GGX VNDF importance sampling functions
  17846. // Van der Corput radical inverse for generating quasi-random sequences
  17847. const radicalInverse_VdC = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  17848. const bits = uint( bits_immutable ).toVar();
  17849. bits.assign( bits.shiftLeft( uint( 16 ) ).bitOr( bits.shiftRight( uint( 16 ) ) ) );
  17850. bits.assign( bits.bitAnd( uint( 0x55555555 ) ).shiftLeft( uint( 1 ) ).bitOr( bits.bitAnd( uint( 0xAAAAAAAA ) ).shiftRight( uint( 1 ) ) ) );
  17851. bits.assign( bits.bitAnd( uint( 0x33333333 ) ).shiftLeft( uint( 2 ) ).bitOr( bits.bitAnd( uint( 0xCCCCCCCC ) ).shiftRight( uint( 2 ) ) ) );
  17852. bits.assign( bits.bitAnd( uint( 0x0F0F0F0F ) ).shiftLeft( uint( 4 ) ).bitOr( bits.bitAnd( uint( 0xF0F0F0F0 ) ).shiftRight( uint( 4 ) ) ) );
  17853. bits.assign( bits.bitAnd( uint( 0x00FF00FF ) ).shiftLeft( uint( 8 ) ).bitOr( bits.bitAnd( uint( 0xFF00FF00 ) ).shiftRight( uint( 8 ) ) ) );
  17854. return float( bits ).mul( 2.3283064365386963e-10 ); // / 0x100000000
  17855. } );
  17856. // Hammersley sequence for quasi-Monte Carlo sampling
  17857. const hammersley = /*@__PURE__*/ Fn( ( [ i, N ] ) => {
  17858. return vec2( float( i ).div( float( N ) ), radicalInverse_VdC( i ) );
  17859. } );
  17860. // GGX VNDF importance sampling (Eric Heitz 2018)
  17861. // "Sampling the GGX Distribution of Visible Normals"
  17862. // https://jcgt.org/published/0007/04/01/
  17863. const importanceSampleGGX_VNDF = /*@__PURE__*/ Fn( ( [ Xi, V, roughness ] ) => {
  17864. const alpha = roughness.mul( roughness ).toConst();
  17865. // Section 4.1: Orthonormal basis
  17866. const T1 = vec3( 1.0, 0.0, 0.0 ).toConst();
  17867. const T2 = cross( V, T1 ).toConst();
  17868. // Section 4.2: Parameterization of projected area
  17869. const r = sqrt( Xi.x ).toConst();
  17870. const phi = mul( 2.0, 3.14159265359 ).mul( Xi.y ).toConst();
  17871. const t1 = r.mul( cos( phi ) ).toConst();
  17872. const t2 = r.mul( sin( phi ) ).toVar();
  17873. const s = mul( 0.5, V.z.add( 1.0 ) ).toConst();
  17874. t2.assign( s.oneMinus().mul( sqrt( t1.mul( t1 ).oneMinus() ) ).add( s.mul( t2 ) ) );
  17875. // Section 4.3: Reprojection onto hemisphere
  17876. 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() ) ) ) );
  17877. // Section 3.4: Transform back to ellipsoid configuration
  17878. return normalize( vec3( alpha.mul( Nh.x ), alpha.mul( Nh.y ), max$1( 0.0, Nh.z ) ) );
  17879. } );
  17880. // GGX convolution using VNDF importance sampling
  17881. const ggxConvolution = /*@__PURE__*/ Fn( ( { roughness, mipInt, envMap, N_immutable, GGX_SAMPLES, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17882. const N = vec3( N_immutable ).toVar();
  17883. const prefilteredColor = vec3( 0.0 ).toVar();
  17884. const totalWeight = float( 0.0 ).toVar();
  17885. // For very low roughness, just sample the environment directly
  17886. If( roughness.lessThan( 0.001 ), () => {
  17887. prefilteredColor.assign( bilinearCubeUV( envMap, N, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) );
  17888. } ).Else( () => {
  17889. // Tangent space basis for VNDF sampling
  17890. const up = select( abs( N.z ).lessThan( 0.999 ), vec3( 0.0, 0.0, 1.0 ), vec3( 1.0, 0.0, 0.0 ) );
  17891. const tangent = normalize( cross( up, N ) ).toVar();
  17892. const bitangent = cross( N, tangent ).toVar();
  17893. Loop( { start: uint( 0 ), end: GGX_SAMPLES }, ( { i } ) => {
  17894. const Xi = hammersley( i, GGX_SAMPLES );
  17895. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  17896. const H_tangent = importanceSampleGGX_VNDF( Xi, vec3( 0.0, 0.0, 1.0 ), roughness );
  17897. // Transform H back to world space
  17898. const H = normalize( tangent.mul( H_tangent.x ).add( bitangent.mul( H_tangent.y ) ).add( N.mul( H_tangent.z ) ) );
  17899. const L = normalize( H.mul( dot( N, H ).mul( 2.0 ) ).sub( N ) );
  17900. const NdotL = max$1( dot( N, L ), 0.0 );
  17901. If( NdotL.greaterThan( 0.0 ), () => {
  17902. // Sample environment at fixed mip level
  17903. // VNDF importance sampling handles the distribution filtering
  17904. const sampleColor = bilinearCubeUV( envMap, L, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17905. // Weight by NdotL for the split-sum approximation
  17906. // VNDF PDF naturally accounts for the visible microfacet distribution
  17907. prefilteredColor.addAssign( sampleColor.mul( NdotL ) );
  17908. totalWeight.addAssign( NdotL );
  17909. } );
  17910. } );
  17911. If( totalWeight.greaterThan( 0.0 ), () => {
  17912. prefilteredColor.assign( prefilteredColor.div( totalWeight ) );
  17913. } );
  17914. } );
  17915. return vec4( prefilteredColor, 1.0 );
  17916. } );
  17917. const LOD_MIN = 4;
  17918. // The standard deviations (radians) associated with the extra mips.
  17919. // Used for scene blur in fromScene() method.
  17920. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  17921. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  17922. // samples and exit early, but not recompile the shader.
  17923. // Used for scene blur in fromScene() method.
  17924. const MAX_SAMPLES = 20;
  17925. // GGX VNDF importance sampling configuration
  17926. const GGX_SAMPLES = 512;
  17927. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  17928. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  17929. const _clearColor$2 = /*@__PURE__*/ new Color();
  17930. let _oldTarget = null;
  17931. let _oldActiveCubeFace = 0;
  17932. let _oldActiveMipmapLevel = 0;
  17933. const _origin = /*@__PURE__*/ new Vector3();
  17934. // maps blur materials to their uniforms dictionary
  17935. const _uniformsMap = new WeakMap();
  17936. // WebGPU Face indices
  17937. const _faceLib = [
  17938. 3, 1, 5,
  17939. 0, 4, 2
  17940. ];
  17941. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  17942. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  17943. /**
  17944. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  17945. * (PMREM) from a cubeMap environment texture. This allows different levels of
  17946. * blur to be quickly accessed based on material roughness. It is packed into a
  17947. * special CubeUV format that allows us to perform custom interpolation so that
  17948. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  17949. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  17950. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  17951. * higher roughness levels. In this way we maintain resolution to smoothly
  17952. * interpolate diffuse lighting while limiting sampling computation.
  17953. *
  17954. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  17955. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  17956. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  17957. * used in material rendering for physically-based image-based lighting.
  17958. */
  17959. class PMREMGenerator {
  17960. /**
  17961. * Constructs a new PMREM generator.
  17962. *
  17963. * @param {Renderer} renderer - The renderer.
  17964. */
  17965. constructor( renderer ) {
  17966. this._renderer = renderer;
  17967. this._pingPongRenderTarget = null;
  17968. this._lodMax = 0;
  17969. this._cubeSize = 0;
  17970. this._sizeLods = [];
  17971. this._sigmas = [];
  17972. this._lodMeshes = [];
  17973. this._blurMaterial = null;
  17974. this._ggxMaterial = null;
  17975. this._cubemapMaterial = null;
  17976. this._equirectMaterial = null;
  17977. this._backgroundBox = null;
  17978. }
  17979. get _hasInitialized() {
  17980. return this._renderer.hasInitialized();
  17981. }
  17982. /**
  17983. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17984. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17985. * in radians to be applied to the scene before PMREM generation. Optional near
  17986. * and far planes ensure the scene is rendered in its entirety.
  17987. *
  17988. * @param {Scene} scene - The scene to be captured.
  17989. * @param {number} [sigma=0] - The blur radius in radians.
  17990. * @param {number} [near=0.1] - The near plane distance.
  17991. * @param {number} [far=100] - The far plane distance.
  17992. * @param {Object} [options={}] - The configuration options.
  17993. * @param {number} [options.size=256] - The texture size of the PMREM.
  17994. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  17995. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17996. * @return {RenderTarget} The resulting PMREM.
  17997. * @see {@link PMREMGenerator#fromScene}
  17998. */
  17999. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  18000. const {
  18001. size = 256,
  18002. position = _origin,
  18003. renderTarget = null,
  18004. } = options;
  18005. this._setSize( size );
  18006. if ( this._hasInitialized === false ) {
  18007. warn( 'PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.' );
  18008. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18009. options.renderTarget = cubeUVRenderTarget;
  18010. this.fromSceneAsync( scene, sigma, near, far, options );
  18011. return cubeUVRenderTarget;
  18012. }
  18013. _oldTarget = this._renderer.getRenderTarget();
  18014. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18015. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18016. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18017. cubeUVRenderTarget.depthBuffer = true;
  18018. this._init( cubeUVRenderTarget );
  18019. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  18020. if ( sigma > 0 ) {
  18021. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  18022. }
  18023. this._applyPMREM( cubeUVRenderTarget );
  18024. this._cleanup( cubeUVRenderTarget );
  18025. return cubeUVRenderTarget;
  18026. }
  18027. /**
  18028. * Generates a PMREM from a supplied Scene, which can be faster than using an
  18029. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  18030. * in radians to be applied to the scene before PMREM generation. Optional near
  18031. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  18032. * is placed at the origin).
  18033. *
  18034. * @deprecated
  18035. * @param {Scene} scene - The scene to be captured.
  18036. * @param {number} [sigma=0] - The blur radius in radians.
  18037. * @param {number} [near=0.1] - The near plane distance.
  18038. * @param {number} [far=100] - The far plane distance.
  18039. * @param {Object} [options={}] - The configuration options.
  18040. * @param {number} [options.size=256] - The texture size of the PMREM.
  18041. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  18042. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  18043. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  18044. * @see {@link PMREMGenerator#fromScene}
  18045. */
  18046. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  18047. warnOnce( 'PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18048. await this._renderer.init();
  18049. return this.fromScene( scene, sigma, near, far, options );
  18050. }
  18051. /**
  18052. * Generates a PMREM from an equirectangular texture, which can be either LDR
  18053. * or HDR. The ideal input image size is 1k (1024 x 512),
  18054. * as this matches best with the 256 x 256 cubemap output.
  18055. *
  18056. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  18057. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18058. * @return {RenderTarget} The resulting PMREM.
  18059. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  18060. */
  18061. fromEquirectangular( equirectangular, renderTarget = null ) {
  18062. if ( this._hasInitialized === false ) {
  18063. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.' );
  18064. this._setSizeFromTexture( equirectangular );
  18065. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18066. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  18067. return cubeUVRenderTarget;
  18068. }
  18069. return this._fromTexture( equirectangular, renderTarget );
  18070. }
  18071. /**
  18072. * Generates a PMREM from an equirectangular texture, which can be either LDR
  18073. * or HDR. The ideal input image size is 1k (1024 x 512),
  18074. * as this matches best with the 256 x 256 cubemap output.
  18075. *
  18076. * @deprecated
  18077. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  18078. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18079. * @return {Promise<RenderTarget>} The resulting PMREM.
  18080. * @see {@link PMREMGenerator#fromEquirectangular}
  18081. */
  18082. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  18083. warnOnce( 'PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18084. await this._renderer.init();
  18085. return this._fromTexture( equirectangular, renderTarget );
  18086. }
  18087. /**
  18088. * Generates a PMREM from an cubemap texture, which can be either LDR
  18089. * or HDR. The ideal input cube size is 256 x 256,
  18090. * as this matches best with the 256 x 256 cubemap output.
  18091. *
  18092. * @param {Texture} cubemap - The cubemap texture to be converted.
  18093. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18094. * @return {RenderTarget} The resulting PMREM.
  18095. * @see {@link PMREMGenerator#fromCubemapAsync}
  18096. */
  18097. fromCubemap( cubemap, renderTarget = null ) {
  18098. if ( this._hasInitialized === false ) {
  18099. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  18100. this._setSizeFromTexture( cubemap );
  18101. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18102. this.fromCubemapAsync( cubemap, renderTarget );
  18103. return cubeUVRenderTarget;
  18104. }
  18105. return this._fromTexture( cubemap, renderTarget );
  18106. }
  18107. /**
  18108. * Generates a PMREM from an cubemap texture, which can be either LDR
  18109. * or HDR. The ideal input cube size is 256 x 256,
  18110. * with the 256 x 256 cubemap output.
  18111. *
  18112. * @deprecated
  18113. * @param {Texture} cubemap - The cubemap texture to be converted.
  18114. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  18115. * @return {Promise<RenderTarget>} The resulting PMREM.
  18116. * @see {@link PMREMGenerator#fromCubemap}
  18117. */
  18118. async fromCubemapAsync( cubemap, renderTarget = null ) {
  18119. warnOnce( 'PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  18120. await this._renderer.init();
  18121. return this._fromTexture( cubemap, renderTarget );
  18122. }
  18123. /**
  18124. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  18125. * your texture's network fetch for increased concurrency.
  18126. *
  18127. * @returns {Promise}
  18128. */
  18129. async compileCubemapShader() {
  18130. if ( this._cubemapMaterial === null ) {
  18131. this._cubemapMaterial = _getCubemapMaterial();
  18132. await this._compileMaterial( this._cubemapMaterial );
  18133. }
  18134. }
  18135. /**
  18136. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  18137. * your texture's network fetch for increased concurrency.
  18138. *
  18139. * @returns {Promise}
  18140. */
  18141. async compileEquirectangularShader() {
  18142. if ( this._equirectMaterial === null ) {
  18143. this._equirectMaterial = _getEquirectMaterial();
  18144. await this._compileMaterial( this._equirectMaterial );
  18145. }
  18146. }
  18147. /**
  18148. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  18149. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  18150. * one of them will cause any others to also become unusable.
  18151. */
  18152. dispose() {
  18153. this._dispose();
  18154. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  18155. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  18156. if ( this._backgroundBox !== null ) {
  18157. this._backgroundBox.geometry.dispose();
  18158. this._backgroundBox.material.dispose();
  18159. }
  18160. }
  18161. // private interface
  18162. _setSizeFromTexture( texture ) {
  18163. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  18164. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  18165. } else { // Equirectangular
  18166. this._setSize( texture.image.width / 4 );
  18167. }
  18168. }
  18169. _setSize( cubeSize ) {
  18170. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  18171. this._cubeSize = Math.pow( 2, this._lodMax );
  18172. }
  18173. _dispose() {
  18174. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  18175. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  18176. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  18177. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  18178. this._lodMeshes[ i ].geometry.dispose();
  18179. }
  18180. }
  18181. _cleanup( outputTarget ) {
  18182. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  18183. outputTarget.scissorTest = false;
  18184. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  18185. }
  18186. _fromTexture( texture, renderTarget ) {
  18187. this._setSizeFromTexture( texture );
  18188. _oldTarget = this._renderer.getRenderTarget();
  18189. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18190. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18191. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  18192. this._init( cubeUVRenderTarget );
  18193. this._textureToCubeUV( texture, cubeUVRenderTarget );
  18194. this._applyPMREM( cubeUVRenderTarget );
  18195. this._cleanup( cubeUVRenderTarget );
  18196. return cubeUVRenderTarget;
  18197. }
  18198. _allocateTarget() {
  18199. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  18200. const height = 4 * this._cubeSize;
  18201. const cubeUVRenderTarget = _createRenderTarget( width, height );
  18202. return cubeUVRenderTarget;
  18203. }
  18204. _init( renderTarget ) {
  18205. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  18206. if ( this._pingPongRenderTarget !== null ) {
  18207. this._dispose();
  18208. }
  18209. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  18210. const { _lodMax } = this;
  18211. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  18212. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  18213. this._ggxMaterial = _getGGXShader( _lodMax, renderTarget.width, renderTarget.height );
  18214. }
  18215. }
  18216. async _compileMaterial( material ) {
  18217. const mesh = new Mesh( new BufferGeometry(), material );
  18218. await this._renderer.compile( mesh, _flatCamera );
  18219. }
  18220. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  18221. const cubeCamera = _cubeCamera;
  18222. cubeCamera.near = near;
  18223. cubeCamera.far = far;
  18224. // px, py, pz, nx, ny, nz
  18225. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  18226. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  18227. const renderer = this._renderer;
  18228. const originalAutoClear = renderer.autoClear;
  18229. renderer.getClearColor( _clearColor$2 );
  18230. renderer.autoClear = false;
  18231. if ( this._backgroundBox === null ) {
  18232. this._backgroundBox = new Mesh(
  18233. new BoxGeometry(),
  18234. new MeshBasicMaterial( {
  18235. name: 'PMREM.Background',
  18236. side: BackSide,
  18237. depthWrite: false,
  18238. depthTest: false,
  18239. } )
  18240. );
  18241. }
  18242. const backgroundBox = this._backgroundBox;
  18243. const backgroundMaterial = backgroundBox.material;
  18244. let useSolidColor = false;
  18245. const background = scene.background;
  18246. if ( background ) {
  18247. if ( background.isColor ) {
  18248. backgroundMaterial.color.copy( background );
  18249. scene.background = null;
  18250. useSolidColor = true;
  18251. }
  18252. } else {
  18253. backgroundMaterial.color.copy( _clearColor$2 );
  18254. useSolidColor = true;
  18255. }
  18256. renderer.setRenderTarget( cubeUVRenderTarget );
  18257. renderer.clear();
  18258. if ( useSolidColor ) {
  18259. renderer.render( backgroundBox, cubeCamera );
  18260. }
  18261. for ( let i = 0; i < 6; i ++ ) {
  18262. const col = i % 3;
  18263. if ( col === 0 ) {
  18264. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18265. cubeCamera.position.set( position.x, position.y, position.z );
  18266. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  18267. } else if ( col === 1 ) {
  18268. cubeCamera.up.set( 0, 0, upSign[ i ] );
  18269. cubeCamera.position.set( position.x, position.y, position.z );
  18270. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  18271. } else {
  18272. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18273. cubeCamera.position.set( position.x, position.y, position.z );
  18274. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  18275. }
  18276. const size = this._cubeSize;
  18277. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  18278. renderer.render( scene, cubeCamera );
  18279. }
  18280. renderer.autoClear = originalAutoClear;
  18281. scene.background = background;
  18282. }
  18283. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  18284. const renderer = this._renderer;
  18285. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  18286. if ( isCubeTexture ) {
  18287. if ( this._cubemapMaterial === null ) {
  18288. this._cubemapMaterial = _getCubemapMaterial( texture );
  18289. }
  18290. } else {
  18291. if ( this._equirectMaterial === null ) {
  18292. this._equirectMaterial = _getEquirectMaterial( texture );
  18293. }
  18294. }
  18295. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  18296. material.fragmentNode.value = texture;
  18297. const mesh = this._lodMeshes[ 0 ];
  18298. mesh.material = material;
  18299. const size = this._cubeSize;
  18300. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  18301. renderer.setRenderTarget( cubeUVRenderTarget );
  18302. renderer.render( mesh, _flatCamera );
  18303. }
  18304. _applyPMREM( cubeUVRenderTarget ) {
  18305. const renderer = this._renderer;
  18306. const autoClear = renderer.autoClear;
  18307. renderer.autoClear = false;
  18308. const n = this._lodMeshes.length;
  18309. // Use GGX VNDF importance sampling
  18310. for ( let i = 1; i < n; i ++ ) {
  18311. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  18312. }
  18313. renderer.autoClear = autoClear;
  18314. }
  18315. /**
  18316. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  18317. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  18318. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  18319. * applies incremental roughness filtering to avoid over-blurring.
  18320. *
  18321. * @private
  18322. * @param {RenderTarget} cubeUVRenderTarget
  18323. * @param {number} lodIn - Source LOD level to read from
  18324. * @param {number} lodOut - Target LOD level to write to
  18325. */
  18326. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  18327. const renderer = this._renderer;
  18328. const pingPongRenderTarget = this._pingPongRenderTarget;
  18329. const ggxMaterial = this._ggxMaterial;
  18330. const ggxMesh = this._lodMeshes[ lodOut ];
  18331. ggxMesh.material = ggxMaterial;
  18332. const ggxUniforms = _uniformsMap.get( ggxMaterial );
  18333. // Calculate incremental roughness between LOD levels
  18334. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  18335. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  18336. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  18337. // Apply blur strength mapping for better quality across the roughness range
  18338. const blurStrength = 0.0 + targetRoughness * 1.25;
  18339. const adjustedRoughness = incrementalRoughness * blurStrength;
  18340. // Calculate viewport position based on output LOD level
  18341. const { _lodMax } = this;
  18342. const outputSize = this._sizeLods[ lodOut ];
  18343. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18344. const y = 4 * ( this._cubeSize - outputSize );
  18345. // Read from previous LOD with incremental roughness
  18346. cubeUVRenderTarget.texture.frame = ( cubeUVRenderTarget.texture.frame || 0 ) + 1;
  18347. ggxUniforms.envMap.value = cubeUVRenderTarget.texture;
  18348. ggxUniforms.roughness.value = adjustedRoughness;
  18349. ggxUniforms.mipInt.value = _lodMax - lodIn; // Sample from input LOD
  18350. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18351. renderer.setRenderTarget( pingPongRenderTarget );
  18352. renderer.render( ggxMesh, _flatCamera );
  18353. // Copy from pingPong back to cubeUV (simple direct copy)
  18354. pingPongRenderTarget.texture.frame = ( pingPongRenderTarget.texture.frame || 0 ) + 1;
  18355. ggxUniforms.envMap.value = pingPongRenderTarget.texture;
  18356. ggxUniforms.roughness.value = 0.0; // Direct copy
  18357. ggxUniforms.mipInt.value = _lodMax - lodOut; // Read from the level we just wrote
  18358. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18359. renderer.setRenderTarget( cubeUVRenderTarget );
  18360. renderer.render( ggxMesh, _flatCamera );
  18361. }
  18362. /**
  18363. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  18364. * vertically and horizontally, but this breaks down on a cube. Here we apply
  18365. * the blur latitudinally (around the poles), and then longitudinally (towards
  18366. * the poles) to approximate the orthogonally-separable blur. It is least
  18367. * accurate at the poles, but still does a decent job.
  18368. *
  18369. * Used for initial scene blur in fromScene() method when sigma > 0.
  18370. *
  18371. * @private
  18372. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  18373. * @param {number} lodIn - The input level-of-detail.
  18374. * @param {number} lodOut - The output level-of-detail.
  18375. * @param {number} sigma - The blur radius in radians.
  18376. * @param {Vector3} [poleAxis] - The pole axis.
  18377. */
  18378. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  18379. const pingPongRenderTarget = this._pingPongRenderTarget;
  18380. this._halfBlur(
  18381. cubeUVRenderTarget,
  18382. pingPongRenderTarget,
  18383. lodIn,
  18384. lodOut,
  18385. sigma,
  18386. 'latitudinal',
  18387. poleAxis );
  18388. this._halfBlur(
  18389. pingPongRenderTarget,
  18390. cubeUVRenderTarget,
  18391. lodOut,
  18392. lodOut,
  18393. sigma,
  18394. 'longitudinal',
  18395. poleAxis );
  18396. }
  18397. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  18398. const renderer = this._renderer;
  18399. const blurMaterial = this._blurMaterial;
  18400. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  18401. error( 'blur direction must be either latitudinal or longitudinal!' );
  18402. }
  18403. // Number of standard deviations at which to cut off the discrete approximation.
  18404. const STANDARD_DEVIATIONS = 3;
  18405. const blurMesh = this._lodMeshes[ lodOut ];
  18406. blurMesh.material = blurMaterial;
  18407. const blurUniforms = _uniformsMap.get( blurMaterial );
  18408. const pixels = this._sizeLods[ lodIn ] - 1;
  18409. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  18410. const sigmaPixels = sigmaRadians / radiansPerPixel;
  18411. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  18412. if ( samples > MAX_SAMPLES ) {
  18413. warn( `sigmaRadians, ${
  18414. sigmaRadians}, is too large and will clip, as it requested ${
  18415. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  18416. }
  18417. const weights = [];
  18418. let sum = 0;
  18419. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  18420. const x = i / sigmaPixels;
  18421. const weight = Math.exp( - x * x / 2 );
  18422. weights.push( weight );
  18423. if ( i === 0 ) {
  18424. sum += weight;
  18425. } else if ( i < samples ) {
  18426. sum += 2 * weight;
  18427. }
  18428. }
  18429. for ( let i = 0; i < weights.length; i ++ ) {
  18430. weights[ i ] = weights[ i ] / sum;
  18431. }
  18432. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18433. blurUniforms.envMap.value = targetIn.texture;
  18434. blurUniforms.samples.value = samples;
  18435. blurUniforms.weights.array = weights;
  18436. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  18437. if ( poleAxis ) {
  18438. blurUniforms.poleAxis.value = poleAxis;
  18439. }
  18440. const { _lodMax } = this;
  18441. blurUniforms.dTheta.value = radiansPerPixel;
  18442. blurUniforms.mipInt.value = _lodMax - lodIn;
  18443. const outputSize = this._sizeLods[ lodOut ];
  18444. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18445. const y = 4 * ( this._cubeSize - outputSize );
  18446. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18447. renderer.setRenderTarget( targetOut );
  18448. renderer.render( blurMesh, _flatCamera );
  18449. }
  18450. }
  18451. function _createPlanes( lodMax ) {
  18452. const sizeLods = [];
  18453. const sigmas = [];
  18454. const lodMeshes = [];
  18455. let lod = lodMax;
  18456. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  18457. for ( let i = 0; i < totalLods; i ++ ) {
  18458. const sizeLod = Math.pow( 2, lod );
  18459. sizeLods.push( sizeLod );
  18460. let sigma = 1.0 / sizeLod;
  18461. if ( i > lodMax - LOD_MIN ) {
  18462. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  18463. } else if ( i === 0 ) {
  18464. sigma = 0;
  18465. }
  18466. sigmas.push( sigma );
  18467. const texelSize = 1.0 / ( sizeLod - 2 );
  18468. const min = - texelSize;
  18469. const max = 1 + texelSize;
  18470. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18471. const cubeFaces = 6;
  18472. const vertices = 6;
  18473. const positionSize = 3;
  18474. const uvSize = 2;
  18475. const faceIndexSize = 1;
  18476. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18477. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  18478. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  18479. for ( let face = 0; face < cubeFaces; face ++ ) {
  18480. const x = ( face % 3 ) * 2 / 3 - 1;
  18481. const y = face > 2 ? 0 : -1;
  18482. const coordinates = [
  18483. x, y, 0,
  18484. x + 2 / 3, y, 0,
  18485. x + 2 / 3, y + 1, 0,
  18486. x, y, 0,
  18487. x + 2 / 3, y + 1, 0,
  18488. x, y + 1, 0
  18489. ];
  18490. const faceIdx = _faceLib[ face ];
  18491. position.set( coordinates, positionSize * vertices * faceIdx );
  18492. uv.set( uv1, uvSize * vertices * faceIdx );
  18493. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  18494. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  18495. }
  18496. const planes = new BufferGeometry();
  18497. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18498. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  18499. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  18500. lodMeshes.push( new Mesh( planes, null ) );
  18501. if ( lod > LOD_MIN ) {
  18502. lod --;
  18503. }
  18504. }
  18505. return { lodMeshes, sizeLods, sigmas };
  18506. }
  18507. function _createRenderTarget( width, height ) {
  18508. const params = {
  18509. magFilter: LinearFilter,
  18510. minFilter: LinearFilter,
  18511. generateMipmaps: false,
  18512. type: HalfFloatType,
  18513. format: RGBAFormat,
  18514. colorSpace: LinearSRGBColorSpace,
  18515. //depthBuffer: false
  18516. };
  18517. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18518. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18519. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18520. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18521. cubeUVRenderTarget.scissorTest = true;
  18522. return cubeUVRenderTarget;
  18523. }
  18524. function _setViewport( target, x, y, width, height ) {
  18525. target.viewport.set( x, y, width, height );
  18526. target.scissor.set( x, y, width, height );
  18527. }
  18528. function _getMaterial( type ) {
  18529. const material = new NodeMaterial();
  18530. material.depthTest = false;
  18531. material.depthWrite = false;
  18532. material.blending = NoBlending;
  18533. material.name = `PMREM_${ type }`;
  18534. return material;
  18535. }
  18536. function _getBlurShader( lodMax, width, height ) {
  18537. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  18538. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  18539. const dTheta = uniform( 0 );
  18540. const n = float( MAX_SAMPLES );
  18541. const latitudinal = uniform( 0 ); // false, bool
  18542. const samples = uniform( 1 ); // int
  18543. const envMap = texture();
  18544. const mipInt = uniform( 0 ); // int
  18545. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18546. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18547. const CUBEUV_MAX_MIP = float( lodMax );
  18548. const materialUniforms = {
  18549. n,
  18550. latitudinal,
  18551. weights,
  18552. poleAxis,
  18553. outputDirection: _outputDirection,
  18554. dTheta,
  18555. samples,
  18556. envMap,
  18557. mipInt,
  18558. CUBEUV_TEXEL_WIDTH,
  18559. CUBEUV_TEXEL_HEIGHT,
  18560. CUBEUV_MAX_MIP
  18561. };
  18562. const material = _getMaterial( 'blur' );
  18563. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  18564. _uniformsMap.set( material, materialUniforms );
  18565. return material;
  18566. }
  18567. function _getGGXShader( lodMax, width, height ) {
  18568. const envMap = texture();
  18569. const roughness = uniform( 0 );
  18570. const mipInt = uniform( 0 );
  18571. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18572. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18573. const CUBEUV_MAX_MIP = float( lodMax );
  18574. const materialUniforms = {
  18575. envMap,
  18576. roughness,
  18577. mipInt,
  18578. CUBEUV_TEXEL_WIDTH,
  18579. CUBEUV_TEXEL_HEIGHT,
  18580. CUBEUV_MAX_MIP
  18581. };
  18582. const material = _getMaterial( 'ggx' );
  18583. material.fragmentNode = ggxConvolution( {
  18584. ...materialUniforms,
  18585. N_immutable: _outputDirection,
  18586. GGX_SAMPLES: uint( GGX_SAMPLES )
  18587. } );
  18588. _uniformsMap.set( material, materialUniforms );
  18589. return material;
  18590. }
  18591. function _getCubemapMaterial( envTexture ) {
  18592. const material = _getMaterial( 'cubemap' );
  18593. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  18594. return material;
  18595. }
  18596. function _getEquirectMaterial( envTexture ) {
  18597. const material = _getMaterial( 'equirect' );
  18598. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  18599. return material;
  18600. }
  18601. const _cache = new WeakMap();
  18602. /**
  18603. * Generates the cubeUV size based on the given image height.
  18604. *
  18605. * @private
  18606. * @param {number} imageHeight - The image height.
  18607. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  18608. */
  18609. function _generateCubeUVSize( imageHeight ) {
  18610. const maxMip = Math.log2( imageHeight ) - 2;
  18611. const texelHeight = 1.0 / imageHeight;
  18612. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  18613. return { texelWidth, texelHeight, maxMip };
  18614. }
  18615. /**
  18616. * Generates a PMREM from the given texture.
  18617. *
  18618. * @private
  18619. * @param {Texture} texture - The texture to create the PMREM for.
  18620. * @param {Renderer} renderer - The renderer.
  18621. * @param {PMREMGenerator} generator - The PMREM generator.
  18622. * @return {?Texture} The PMREM.
  18623. */
  18624. function _getPMREMFromTexture( texture, renderer, generator ) {
  18625. const cache = _getCache( renderer );
  18626. let cacheTexture = cache.get( texture );
  18627. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  18628. if ( pmremVersion !== texture.pmremVersion ) {
  18629. const image = texture.image;
  18630. if ( texture.isCubeTexture ) {
  18631. if ( isCubeMapReady( image ) ) {
  18632. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  18633. } else {
  18634. return null;
  18635. }
  18636. } else {
  18637. if ( isEquirectangularMapReady( image ) ) {
  18638. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  18639. } else {
  18640. return null;
  18641. }
  18642. }
  18643. cacheTexture.pmremVersion = texture.pmremVersion;
  18644. cache.set( texture, cacheTexture );
  18645. }
  18646. return cacheTexture.texture;
  18647. }
  18648. /**
  18649. * Returns a cache that stores generated PMREMs for the respective textures.
  18650. * A cache must be maintained per renderer since PMREMs are render target textures
  18651. * which can't be shared across render contexts.
  18652. *
  18653. * @private
  18654. * @param {Renderer} renderer - The renderer.
  18655. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  18656. */
  18657. function _getCache( renderer ) {
  18658. let rendererCache = _cache.get( renderer );
  18659. if ( rendererCache === undefined ) {
  18660. rendererCache = new WeakMap();
  18661. _cache.set( renderer, rendererCache );
  18662. }
  18663. return rendererCache;
  18664. }
  18665. /**
  18666. * This node represents a PMREM which is a special type of preprocessed
  18667. * environment map intended for PBR materials.
  18668. *
  18669. * ```js
  18670. * const material = new MeshStandardNodeMaterial();
  18671. * material.envNode = pmremTexture( envMap );
  18672. * ```
  18673. *
  18674. * @augments TempNode
  18675. */
  18676. class PMREMNode extends TempNode {
  18677. static get type() {
  18678. return 'PMREMNode';
  18679. }
  18680. /**
  18681. * Constructs a new function overloading node.
  18682. *
  18683. * @param {Texture} value - The input texture.
  18684. * @param {Node<vec2>} [uvNode=null] - The uv node.
  18685. * @param {Node<float>} [levelNode=null] - The level node.
  18686. */
  18687. constructor( value, uvNode = null, levelNode = null ) {
  18688. super( 'vec3' );
  18689. /**
  18690. * Reference to the input texture.
  18691. *
  18692. * @private
  18693. * @type {Texture}
  18694. */
  18695. this._value = value;
  18696. /**
  18697. * Reference to the generated PMREM.
  18698. *
  18699. * @private
  18700. * @type {Texture | null}
  18701. * @default null
  18702. */
  18703. this._pmrem = null;
  18704. /**
  18705. * The uv node.
  18706. *
  18707. * @type {Node<vec2>}
  18708. */
  18709. this.uvNode = uvNode;
  18710. /**
  18711. * The level node.
  18712. *
  18713. * @type {Node<float>}
  18714. */
  18715. this.levelNode = levelNode;
  18716. /**
  18717. * Reference to a PMREM generator.
  18718. *
  18719. * @private
  18720. * @type {?PMREMGenerator}
  18721. * @default null
  18722. */
  18723. this._generator = null;
  18724. const defaultTexture = new Texture();
  18725. defaultTexture.isRenderTargetTexture = true;
  18726. /**
  18727. * The texture node holding the generated PMREM.
  18728. *
  18729. * @private
  18730. * @type {TextureNode}
  18731. */
  18732. this._texture = texture( defaultTexture );
  18733. /**
  18734. * A uniform representing the PMREM's width.
  18735. *
  18736. * @private
  18737. * @type {UniformNode<float>}
  18738. */
  18739. this._width = uniform( 0 );
  18740. /**
  18741. * A uniform representing the PMREM's height.
  18742. *
  18743. * @private
  18744. * @type {UniformNode<float>}
  18745. */
  18746. this._height = uniform( 0 );
  18747. /**
  18748. * A uniform representing the PMREM's max Mip.
  18749. *
  18750. * @private
  18751. * @type {UniformNode<float>}
  18752. */
  18753. this._maxMip = uniform( 0 );
  18754. /**
  18755. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  18756. *
  18757. * @type {string}
  18758. * @default 'render'
  18759. */
  18760. this.updateBeforeType = NodeUpdateType.RENDER;
  18761. }
  18762. set value( value ) {
  18763. this._value = value;
  18764. this._pmrem = null;
  18765. }
  18766. /**
  18767. * The node's texture value.
  18768. *
  18769. * @type {Texture}
  18770. */
  18771. get value() {
  18772. return this._value;
  18773. }
  18774. /**
  18775. * Uses the given PMREM texture to update internal values.
  18776. *
  18777. * @param {Texture} texture - The PMREM texture.
  18778. */
  18779. updateFromTexture( texture ) {
  18780. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  18781. this._texture.value = texture;
  18782. this._width.value = cubeUVSize.texelWidth;
  18783. this._height.value = cubeUVSize.texelHeight;
  18784. this._maxMip.value = cubeUVSize.maxMip;
  18785. }
  18786. updateBefore( frame ) {
  18787. let pmrem = this._pmrem;
  18788. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  18789. const texture = this._value;
  18790. if ( pmremVersion !== texture.pmremVersion ) {
  18791. if ( texture.isPMREMTexture === true ) {
  18792. pmrem = texture;
  18793. } else {
  18794. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  18795. }
  18796. if ( pmrem !== null ) {
  18797. this._pmrem = pmrem;
  18798. this.updateFromTexture( pmrem );
  18799. }
  18800. }
  18801. }
  18802. setup( builder ) {
  18803. if ( this._generator === null ) {
  18804. this._generator = new PMREMGenerator( builder.renderer );
  18805. }
  18806. this.updateBefore( builder );
  18807. //
  18808. let uvNode = this.uvNode;
  18809. if ( uvNode === null && builder.context.getUV ) {
  18810. uvNode = builder.context.getUV( this, builder );
  18811. }
  18812. //
  18813. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  18814. //
  18815. let levelNode = this.levelNode;
  18816. if ( levelNode === null && builder.context.getTextureLevel ) {
  18817. levelNode = builder.context.getTextureLevel( this );
  18818. }
  18819. //
  18820. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  18821. }
  18822. dispose() {
  18823. super.dispose();
  18824. if ( this._generator !== null ) this._generator.dispose();
  18825. }
  18826. }
  18827. /**
  18828. * Returns `true` if the given cube map image has been fully loaded.
  18829. *
  18830. * @private
  18831. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  18832. * @return {boolean} Whether the given cube map is ready or not.
  18833. */
  18834. function isCubeMapReady( image ) {
  18835. if ( image === null || image === undefined ) return false;
  18836. let count = 0;
  18837. const length = 6;
  18838. for ( let i = 0; i < length; i ++ ) {
  18839. if ( image[ i ] !== undefined ) count ++;
  18840. }
  18841. return count === length;
  18842. }
  18843. /**
  18844. * Returns `true` if the given equirectangular image has been fully loaded.
  18845. *
  18846. * @private
  18847. * @param {(Image|Object)} image - The equirectangular image.
  18848. * @return {boolean} Whether the given cube map is ready or not.
  18849. */
  18850. function isEquirectangularMapReady( image ) {
  18851. if ( image === null || image === undefined ) return false;
  18852. return image.height > 0;
  18853. }
  18854. /**
  18855. * TSL function for creating a PMREM node.
  18856. *
  18857. * @tsl
  18858. * @function
  18859. * @param {Texture} value - The input texture.
  18860. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  18861. * @param {?Node<float>} [levelNode=null] - The level node.
  18862. * @returns {PMREMNode}
  18863. */
  18864. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  18865. const _rendererCache = new WeakMap();
  18866. /**
  18867. * Represents a physical model for Image-based lighting (IBL). The environment
  18868. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  18869. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  18870. *
  18871. * @augments LightingNode
  18872. */
  18873. class EnvironmentNode extends LightingNode {
  18874. static get type() {
  18875. return 'EnvironmentNode';
  18876. }
  18877. /**
  18878. * Constructs a new environment node.
  18879. *
  18880. * @param {Node} [envNode=null] - A node representing the environment.
  18881. */
  18882. constructor( envNode = null ) {
  18883. super();
  18884. /**
  18885. * A node representing the environment.
  18886. *
  18887. * @type {?Node}
  18888. * @default null
  18889. */
  18890. this.envNode = envNode;
  18891. }
  18892. setup( builder ) {
  18893. const { material } = builder;
  18894. let envNode = this.envNode;
  18895. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  18896. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  18897. const cache = this._getPMREMNodeCache( builder.renderer );
  18898. let cacheEnvNode = cache.get( value );
  18899. if ( cacheEnvNode === undefined ) {
  18900. cacheEnvNode = pmremTexture( value );
  18901. cache.set( value, cacheEnvNode );
  18902. }
  18903. envNode = cacheEnvNode;
  18904. }
  18905. //
  18906. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  18907. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  18908. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  18909. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  18910. const isolateRadiance = isolate( radiance );
  18911. const isolateIrradiance = isolate( irradiance );
  18912. //
  18913. builder.context.radiance.addAssign( isolateRadiance );
  18914. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  18915. //
  18916. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  18917. if ( clearcoatRadiance ) {
  18918. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  18919. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  18920. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  18921. }
  18922. }
  18923. /**
  18924. * Returns the PMREM node cache of the current renderer.
  18925. *
  18926. * @private
  18927. * @param {Renderer} renderer - The current renderer.
  18928. * @return {WeakMap} The node cache.
  18929. */
  18930. _getPMREMNodeCache( renderer ) {
  18931. let pmremCache = _rendererCache.get( renderer );
  18932. if ( pmremCache === undefined ) {
  18933. pmremCache = new WeakMap();
  18934. _rendererCache.set( renderer, pmremCache );
  18935. }
  18936. return pmremCache;
  18937. }
  18938. }
  18939. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  18940. let reflectVec = null;
  18941. return {
  18942. getUV: () => {
  18943. if ( reflectVec === null ) {
  18944. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  18945. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  18946. reflectVec = pow4( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  18947. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  18948. }
  18949. return reflectVec;
  18950. },
  18951. getTextureLevel: () => {
  18952. return roughnessNode;
  18953. }
  18954. };
  18955. };
  18956. const createIrradianceContext = ( normalWorldNode ) => {
  18957. return {
  18958. getUV: () => {
  18959. return normalWorldNode;
  18960. },
  18961. getTextureLevel: () => {
  18962. return float( 1.0 );
  18963. }
  18964. };
  18965. };
  18966. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  18967. /**
  18968. * Node material version of {@link MeshStandardMaterial}.
  18969. *
  18970. * @augments NodeMaterial
  18971. */
  18972. class MeshStandardNodeMaterial extends NodeMaterial {
  18973. static get type() {
  18974. return 'MeshStandardNodeMaterial';
  18975. }
  18976. /**
  18977. * Constructs a new mesh standard node material.
  18978. *
  18979. * @param {Object} [parameters] - The configuration parameter.
  18980. */
  18981. constructor( parameters ) {
  18982. super();
  18983. /**
  18984. * This flag can be used for type testing.
  18985. *
  18986. * @type {boolean}
  18987. * @readonly
  18988. * @default true
  18989. */
  18990. this.isMeshStandardNodeMaterial = true;
  18991. /**
  18992. * Set to `true` because standard materials react on lights.
  18993. *
  18994. * @type {boolean}
  18995. * @default true
  18996. */
  18997. this.lights = true;
  18998. /**
  18999. * The emissive color of standard materials is by default inferred from the `emissive`,
  19000. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  19001. * overwrite the default and define the emissive color with a node instead.
  19002. *
  19003. * If you don't want to overwrite the emissive color but modify the existing
  19004. * value instead, use {@link materialEmissive}.
  19005. *
  19006. * @type {?Node<vec3>}
  19007. * @default null
  19008. */
  19009. this.emissiveNode = null;
  19010. /**
  19011. * The metalness of standard materials is by default inferred from the `metalness`,
  19012. * and `metalnessMap` properties. This node property allows to
  19013. * overwrite the default and define the metalness with a node instead.
  19014. *
  19015. * If you don't want to overwrite the metalness but modify the existing
  19016. * value instead, use {@link materialMetalness}.
  19017. *
  19018. * @type {?Node<float>}
  19019. * @default null
  19020. */
  19021. this.metalnessNode = null;
  19022. /**
  19023. * The roughness of standard materials is by default inferred from the `roughness`,
  19024. * and `roughnessMap` properties. This node property allows to
  19025. * overwrite the default and define the roughness with a node instead.
  19026. *
  19027. * If you don't want to overwrite the roughness but modify the existing
  19028. * value instead, use {@link materialRoughness}.
  19029. *
  19030. * @type {?Node<float>}
  19031. * @default null
  19032. */
  19033. this.roughnessNode = null;
  19034. this.setDefaultValues( _defaultValues$6 );
  19035. this.setValues( parameters );
  19036. }
  19037. /**
  19038. * Overwritten since this type of material uses {@link EnvironmentNode}
  19039. * to implement the PBR (PMREM based) environment mapping. Besides, the
  19040. * method honors `Scene.environment`.
  19041. *
  19042. * @param {NodeBuilder} builder - The current node builder.
  19043. * @return {?EnvironmentNode<vec3>} The environment node.
  19044. */
  19045. setupEnvironment( builder ) {
  19046. let envNode = super.setupEnvironment( builder );
  19047. if ( envNode === null && builder.environmentNode ) {
  19048. envNode = builder.environmentNode;
  19049. }
  19050. return envNode ? new EnvironmentNode( envNode ) : null;
  19051. }
  19052. /**
  19053. * Setups the lighting model.
  19054. *
  19055. * @return {PhysicalLightingModel} The lighting model.
  19056. */
  19057. setupLightingModel( /*builder*/ ) {
  19058. return new PhysicalLightingModel();
  19059. }
  19060. /**
  19061. * Setups the specular related node variables.
  19062. */
  19063. setupSpecular() {
  19064. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  19065. specularColor.assign( vec3( 0.04 ) );
  19066. specularColorBlended.assign( specularColorNode );
  19067. specularF90.assign( 1.0 );
  19068. }
  19069. /**
  19070. * Setups the standard specific node variables.
  19071. *
  19072. * @param {NodeBuilder} builder - The current node builder.
  19073. */
  19074. setupVariants() {
  19075. // METALNESS
  19076. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  19077. metalness.assign( metalnessNode );
  19078. // ROUGHNESS
  19079. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  19080. roughnessNode = getRoughness( { roughness: roughnessNode } );
  19081. roughness.assign( roughnessNode );
  19082. // SPECULAR COLOR
  19083. this.setupSpecular();
  19084. // DIFFUSE COLOR
  19085. diffuseContribution.assign( diffuseColor.rgb.mul( metalnessNode.oneMinus() ) );
  19086. }
  19087. copy( source ) {
  19088. this.emissiveNode = source.emissiveNode;
  19089. this.metalnessNode = source.metalnessNode;
  19090. this.roughnessNode = source.roughnessNode;
  19091. return super.copy( source );
  19092. }
  19093. }
  19094. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  19095. /**
  19096. * Node material version of {@link MeshPhysicalMaterial}.
  19097. *
  19098. * @augments MeshStandardNodeMaterial
  19099. */
  19100. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  19101. static get type() {
  19102. return 'MeshPhysicalNodeMaterial';
  19103. }
  19104. /**
  19105. * Constructs a new mesh physical node material.
  19106. *
  19107. * @param {Object} [parameters] - The configuration parameter.
  19108. */
  19109. constructor( parameters ) {
  19110. super();
  19111. /**
  19112. * This flag can be used for type testing.
  19113. *
  19114. * @type {boolean}
  19115. * @readonly
  19116. * @default true
  19117. */
  19118. this.isMeshPhysicalNodeMaterial = true;
  19119. /**
  19120. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  19121. * and `clearcoatMap` properties. This node property allows to overwrite the default
  19122. * and define the clearcoat with a node instead.
  19123. *
  19124. * If you don't want to overwrite the clearcoat but modify the existing
  19125. * value instead, use {@link materialClearcoat}.
  19126. *
  19127. * @type {?Node<float>}
  19128. * @default null
  19129. */
  19130. this.clearcoatNode = null;
  19131. /**
  19132. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  19133. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  19134. * and define the clearcoat roughness with a node instead.
  19135. *
  19136. * If you don't want to overwrite the clearcoat roughness but modify the existing
  19137. * value instead, use {@link materialClearcoatRoughness}.
  19138. *
  19139. * @type {?Node<float>}
  19140. * @default null
  19141. */
  19142. this.clearcoatRoughnessNode = null;
  19143. /**
  19144. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  19145. * property. This node property allows to overwrite the default
  19146. * and define the clearcoat normal with a node instead.
  19147. *
  19148. * If you don't want to overwrite the clearcoat normal but modify the existing
  19149. * value instead, use {@link materialClearcoatNormal}.
  19150. *
  19151. * @type {?Node<vec3>}
  19152. * @default null
  19153. */
  19154. this.clearcoatNormalNode = null;
  19155. /**
  19156. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  19157. * and `sheenColorMap` properties. This node property allows to overwrite the default
  19158. * and define the sheen with a node instead.
  19159. *
  19160. * If you don't want to overwrite the sheen but modify the existing
  19161. * value instead, use {@link materialSheen}.
  19162. *
  19163. * @type {?Node<vec3>}
  19164. * @default null
  19165. */
  19166. this.sheenNode = null;
  19167. /**
  19168. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  19169. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  19170. * and define the sheen roughness with a node instead.
  19171. *
  19172. * If you don't want to overwrite the sheen roughness but modify the existing
  19173. * value instead, use {@link materialSheenRoughness}.
  19174. *
  19175. * @type {?Node<float>}
  19176. * @default null
  19177. */
  19178. this.sheenRoughnessNode = null;
  19179. /**
  19180. * The iridescence of physical materials is by default inferred from the `iridescence`
  19181. * property. This node property allows to overwrite the default
  19182. * and define the iridescence with a node instead.
  19183. *
  19184. * If you don't want to overwrite the iridescence but modify the existing
  19185. * value instead, use {@link materialIridescence}.
  19186. *
  19187. * @type {?Node<float>}
  19188. * @default null
  19189. */
  19190. this.iridescenceNode = null;
  19191. /**
  19192. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  19193. * property. This node property allows to overwrite the default
  19194. * and define the iridescence IOR with a node instead.
  19195. *
  19196. * If you don't want to overwrite the iridescence IOR but modify the existing
  19197. * value instead, use {@link materialIridescenceIOR}.
  19198. *
  19199. * @type {?Node<float>}
  19200. * @default null
  19201. */
  19202. this.iridescenceIORNode = null;
  19203. /**
  19204. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  19205. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  19206. * and define the iridescence thickness with a node instead.
  19207. *
  19208. * If you don't want to overwrite the iridescence thickness but modify the existing
  19209. * value instead, use {@link materialIridescenceThickness}.
  19210. *
  19211. * @type {?Node<float>}
  19212. * @default null
  19213. */
  19214. this.iridescenceThicknessNode = null;
  19215. /**
  19216. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  19217. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  19218. * and define the specular intensity with a node instead.
  19219. *
  19220. * If you don't want to overwrite the specular intensity but modify the existing
  19221. * value instead, use {@link materialSpecularIntensity}.
  19222. *
  19223. * @type {?Node<float>}
  19224. * @default null
  19225. */
  19226. this.specularIntensityNode = null;
  19227. /**
  19228. * The specular color of physical materials is by default inferred from the `specularColor`
  19229. * and `specularColorMap` properties. This node property allows to overwrite the default
  19230. * and define the specular color with a node instead.
  19231. *
  19232. * If you don't want to overwrite the specular color but modify the existing
  19233. * value instead, use {@link materialSpecularColor}.
  19234. *
  19235. * @type {?Node<vec3>}
  19236. * @default null
  19237. */
  19238. this.specularColorNode = null;
  19239. /**
  19240. * The ior of physical materials is by default inferred from the `ior`
  19241. * property. This node property allows to overwrite the default
  19242. * and define the ior with a node instead.
  19243. *
  19244. * If you don't want to overwrite the ior but modify the existing
  19245. * value instead, use {@link materialIOR}.
  19246. *
  19247. * @type {?Node<float>}
  19248. * @default null
  19249. */
  19250. this.iorNode = null;
  19251. /**
  19252. * The transmission of physical materials is by default inferred from the `transmission` and
  19253. * `transmissionMap` properties. This node property allows to overwrite the default
  19254. * and define the transmission with a node instead.
  19255. *
  19256. * If you don't want to overwrite the transmission but modify the existing
  19257. * value instead, use {@link materialTransmission}.
  19258. *
  19259. * @type {?Node<float>}
  19260. * @default null
  19261. */
  19262. this.transmissionNode = null;
  19263. /**
  19264. * The thickness of physical materials is by default inferred from the `thickness` and
  19265. * `thicknessMap` properties. This node property allows to overwrite the default
  19266. * and define the thickness with a node instead.
  19267. *
  19268. * If you don't want to overwrite the thickness but modify the existing
  19269. * value instead, use {@link materialThickness}.
  19270. *
  19271. * @type {?Node<float>}
  19272. * @default null
  19273. */
  19274. this.thicknessNode = null;
  19275. /**
  19276. * The attenuation distance of physical materials is by default inferred from the
  19277. * `attenuationDistance` property. This node property allows to overwrite the default
  19278. * and define the attenuation distance with a node instead.
  19279. *
  19280. * If you don't want to overwrite the attenuation distance but modify the existing
  19281. * value instead, use {@link materialAttenuationDistance}.
  19282. *
  19283. * @type {?Node<float>}
  19284. * @default null
  19285. */
  19286. this.attenuationDistanceNode = null;
  19287. /**
  19288. * The attenuation color of physical materials is by default inferred from the
  19289. * `attenuationColor` property. This node property allows to overwrite the default
  19290. * and define the attenuation color with a node instead.
  19291. *
  19292. * If you don't want to overwrite the attenuation color but modify the existing
  19293. * value instead, use {@link materialAttenuationColor}.
  19294. *
  19295. * @type {?Node<vec3>}
  19296. * @default null
  19297. */
  19298. this.attenuationColorNode = null;
  19299. /**
  19300. * The dispersion of physical materials is by default inferred from the
  19301. * `dispersion` property. This node property allows to overwrite the default
  19302. * and define the dispersion with a node instead.
  19303. *
  19304. * If you don't want to overwrite the dispersion but modify the existing
  19305. * value instead, use {@link materialDispersion}.
  19306. *
  19307. * @type {?Node<float>}
  19308. * @default null
  19309. */
  19310. this.dispersionNode = null;
  19311. /**
  19312. * The anisotropy of physical materials is by default inferred from the
  19313. * `anisotropy` property. This node property allows to overwrite the default
  19314. * and define the anisotropy with a node instead.
  19315. *
  19316. * If you don't want to overwrite the anisotropy but modify the existing
  19317. * value instead, use {@link materialAnisotropy}.
  19318. *
  19319. * @type {?Node<float>}
  19320. * @default null
  19321. */
  19322. this.anisotropyNode = null;
  19323. this.setDefaultValues( _defaultValues$5 );
  19324. this.setValues( parameters );
  19325. }
  19326. /**
  19327. * Whether the lighting model should use clearcoat or not.
  19328. *
  19329. * @type {boolean}
  19330. * @default true
  19331. */
  19332. get useClearcoat() {
  19333. return this.clearcoat > 0 || this.clearcoatNode !== null;
  19334. }
  19335. /**
  19336. * Whether the lighting model should use iridescence or not.
  19337. *
  19338. * @type {boolean}
  19339. * @default true
  19340. */
  19341. get useIridescence() {
  19342. return this.iridescence > 0 || this.iridescenceNode !== null;
  19343. }
  19344. /**
  19345. * Whether the lighting model should use sheen or not.
  19346. *
  19347. * @type {boolean}
  19348. * @default true
  19349. */
  19350. get useSheen() {
  19351. return this.sheen > 0 || this.sheenNode !== null;
  19352. }
  19353. /**
  19354. * Whether the lighting model should use anisotropy or not.
  19355. *
  19356. * @type {boolean}
  19357. * @default true
  19358. */
  19359. get useAnisotropy() {
  19360. return this.anisotropy > 0 || this.anisotropyNode !== null;
  19361. }
  19362. /**
  19363. * Whether the lighting model should use transmission or not.
  19364. *
  19365. * @type {boolean}
  19366. * @default true
  19367. */
  19368. get useTransmission() {
  19369. return this.transmission > 0 || this.transmissionNode !== null;
  19370. }
  19371. /**
  19372. * Whether the lighting model should use dispersion or not.
  19373. *
  19374. * @type {boolean}
  19375. * @default true
  19376. */
  19377. get useDispersion() {
  19378. return this.dispersion > 0 || this.dispersionNode !== null;
  19379. }
  19380. /**
  19381. * Setups the specular related node variables.
  19382. */
  19383. setupSpecular() {
  19384. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  19385. ior.assign( iorNode );
  19386. specularColor.assign( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ) );
  19387. specularColorBlended.assign( mix( specularColor, diffuseColor.rgb, metalness ) );
  19388. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  19389. }
  19390. /**
  19391. * Setups the lighting model.
  19392. *
  19393. * @return {PhysicalLightingModel} The lighting model.
  19394. */
  19395. setupLightingModel( /*builder*/ ) {
  19396. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  19397. }
  19398. /**
  19399. * Setups the physical specific node variables.
  19400. *
  19401. * @param {NodeBuilder} builder - The current node builder.
  19402. */
  19403. setupVariants( builder ) {
  19404. super.setupVariants( builder );
  19405. // CLEARCOAT
  19406. if ( this.useClearcoat ) {
  19407. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  19408. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  19409. clearcoat.assign( clearcoatNode );
  19410. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  19411. }
  19412. // SHEEN
  19413. if ( this.useSheen ) {
  19414. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  19415. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  19416. sheen.assign( sheenNode );
  19417. sheenRoughness.assign( sheenRoughnessNode );
  19418. }
  19419. // IRIDESCENCE
  19420. if ( this.useIridescence ) {
  19421. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  19422. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  19423. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  19424. iridescence.assign( iridescenceNode );
  19425. iridescenceIOR.assign( iridescenceIORNode );
  19426. iridescenceThickness.assign( iridescenceThicknessNode );
  19427. }
  19428. // ANISOTROPY
  19429. if ( this.useAnisotropy ) {
  19430. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  19431. anisotropy.assign( anisotropyV.length() );
  19432. If( anisotropy.equal( 0.0 ), () => {
  19433. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  19434. } ).Else( () => {
  19435. anisotropyV.divAssign( vec2( anisotropy ) );
  19436. anisotropy.assign( anisotropy.saturate() );
  19437. } );
  19438. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  19439. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  19440. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  19441. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  19442. }
  19443. // TRANSMISSION
  19444. if ( this.useTransmission ) {
  19445. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  19446. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  19447. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  19448. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  19449. transmission.assign( transmissionNode );
  19450. thickness.assign( thicknessNode );
  19451. attenuationDistance.assign( attenuationDistanceNode );
  19452. attenuationColor.assign( attenuationColorNode );
  19453. if ( this.useDispersion ) {
  19454. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  19455. dispersion.assign( dispersionNode );
  19456. }
  19457. }
  19458. }
  19459. /**
  19460. * Setups the clearcoat normal node.
  19461. *
  19462. * @return {Node<vec3>} The clearcoat normal.
  19463. */
  19464. setupClearcoatNormal() {
  19465. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  19466. }
  19467. setup( builder ) {
  19468. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  19469. super.setup( builder );
  19470. }
  19471. copy( source ) {
  19472. this.clearcoatNode = source.clearcoatNode;
  19473. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  19474. this.clearcoatNormalNode = source.clearcoatNormalNode;
  19475. this.sheenNode = source.sheenNode;
  19476. this.sheenRoughnessNode = source.sheenRoughnessNode;
  19477. this.iridescenceNode = source.iridescenceNode;
  19478. this.iridescenceIORNode = source.iridescenceIORNode;
  19479. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  19480. this.specularIntensityNode = source.specularIntensityNode;
  19481. this.specularColorNode = source.specularColorNode;
  19482. this.iorNode = source.iorNode;
  19483. this.transmissionNode = source.transmissionNode;
  19484. this.thicknessNode = source.thicknessNode;
  19485. this.attenuationDistanceNode = source.attenuationDistanceNode;
  19486. this.attenuationColorNode = source.attenuationColorNode;
  19487. this.dispersionNode = source.dispersionNode;
  19488. this.anisotropyNode = source.anisotropyNode;
  19489. return super.copy( source );
  19490. }
  19491. }
  19492. /**
  19493. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  19494. *
  19495. * @augments PhysicalLightingModel
  19496. */
  19497. class SSSLightingModel extends PhysicalLightingModel {
  19498. /**
  19499. * Constructs a new physical lighting model.
  19500. *
  19501. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  19502. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  19503. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  19504. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  19505. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  19506. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  19507. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  19508. */
  19509. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  19510. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  19511. /**
  19512. * Whether the lighting model should use SSS or not.
  19513. *
  19514. * @type {boolean}
  19515. * @default false
  19516. */
  19517. this.useSSS = sss;
  19518. }
  19519. /**
  19520. * Extends the default implementation with a SSS term.
  19521. *
  19522. * 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/)
  19523. *
  19524. * @param {Object} input - The input data.
  19525. * @param {NodeBuilder} builder - The current node builder.
  19526. */
  19527. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19528. if ( this.useSSS === true ) {
  19529. const material = builder.material;
  19530. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  19531. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  19532. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  19533. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  19534. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  19535. }
  19536. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  19537. }
  19538. }
  19539. /**
  19540. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  19541. * that implements a Subsurface scattering (SSS) term.
  19542. *
  19543. * @augments MeshPhysicalNodeMaterial
  19544. */
  19545. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  19546. static get type() {
  19547. return 'MeshSSSNodeMaterial';
  19548. }
  19549. /**
  19550. * Constructs a new mesh SSS node material.
  19551. *
  19552. * @param {Object} [parameters] - The configuration parameter.
  19553. */
  19554. constructor( parameters ) {
  19555. super( parameters );
  19556. /**
  19557. * Represents the thickness color.
  19558. *
  19559. * @type {?Node<vec3>}
  19560. * @default null
  19561. */
  19562. this.thicknessColorNode = null;
  19563. /**
  19564. * Represents the distortion factor.
  19565. *
  19566. * @type {?Node<float>}
  19567. */
  19568. this.thicknessDistortionNode = float( 0.1 );
  19569. /**
  19570. * Represents the thickness ambient factor.
  19571. *
  19572. * @type {?Node<float>}
  19573. */
  19574. this.thicknessAmbientNode = float( 0.0 );
  19575. /**
  19576. * Represents the thickness attenuation.
  19577. *
  19578. * @type {?Node<float>}
  19579. */
  19580. this.thicknessAttenuationNode = float( .1 );
  19581. /**
  19582. * Represents the thickness power.
  19583. *
  19584. * @type {?Node<float>}
  19585. */
  19586. this.thicknessPowerNode = float( 2.0 );
  19587. /**
  19588. * Represents the thickness scale.
  19589. *
  19590. * @type {?Node<float>}
  19591. */
  19592. this.thicknessScaleNode = float( 10.0 );
  19593. }
  19594. /**
  19595. * Whether the lighting model should use SSS or not.
  19596. *
  19597. * @type {boolean}
  19598. * @default true
  19599. */
  19600. get useSSS() {
  19601. return this.thicknessColorNode !== null;
  19602. }
  19603. /**
  19604. * Setups the lighting model.
  19605. *
  19606. * @return {SSSLightingModel} The lighting model.
  19607. */
  19608. setupLightingModel( /*builder*/ ) {
  19609. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  19610. }
  19611. copy( source ) {
  19612. this.thicknessColorNode = source.thicknessColorNode;
  19613. this.thicknessDistortionNode = source.thicknessDistortionNode;
  19614. this.thicknessAmbientNode = source.thicknessAmbientNode;
  19615. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  19616. this.thicknessPowerNode = source.thicknessPowerNode;
  19617. this.thicknessScaleNode = source.thicknessScaleNode;
  19618. return super.copy( source );
  19619. }
  19620. }
  19621. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  19622. // dotNL will be from -1.0 to 1.0
  19623. const dotNL = normal.dot( lightDirection );
  19624. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  19625. if ( builder.material.gradientMap ) {
  19626. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  19627. return vec3( gradientMap.r );
  19628. } else {
  19629. const fw = coord.fwidth().mul( 0.5 );
  19630. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  19631. }
  19632. } );
  19633. /**
  19634. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  19635. *
  19636. * @augments LightingModel
  19637. */
  19638. class ToonLightingModel extends LightingModel {
  19639. /**
  19640. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  19641. * reduced to a small number of discrete shades to create a comic-like, flat look.
  19642. *
  19643. * @param {Object} lightData - The light data.
  19644. * @param {NodeBuilder} builder - The current node builder.
  19645. */
  19646. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19647. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  19648. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  19649. }
  19650. /**
  19651. * Implements the indirect lighting.
  19652. *
  19653. * @param {NodeBuilder} builder - The current node builder.
  19654. */
  19655. indirect( builder ) {
  19656. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  19657. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  19658. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  19659. }
  19660. }
  19661. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  19662. /**
  19663. * Node material version of {@link MeshToonMaterial}.
  19664. *
  19665. * @augments NodeMaterial
  19666. */
  19667. class MeshToonNodeMaterial extends NodeMaterial {
  19668. static get type() {
  19669. return 'MeshToonNodeMaterial';
  19670. }
  19671. /**
  19672. * Constructs a new mesh toon node material.
  19673. *
  19674. * @param {Object} [parameters] - The configuration parameter.
  19675. */
  19676. constructor( parameters ) {
  19677. super();
  19678. /**
  19679. * This flag can be used for type testing.
  19680. *
  19681. * @type {boolean}
  19682. * @readonly
  19683. * @default true
  19684. */
  19685. this.isMeshToonNodeMaterial = true;
  19686. /**
  19687. * Set to `true` because toon materials react on lights.
  19688. *
  19689. * @type {boolean}
  19690. * @default true
  19691. */
  19692. this.lights = true;
  19693. this.setDefaultValues( _defaultValues$4 );
  19694. this.setValues( parameters );
  19695. }
  19696. /**
  19697. * Setups the lighting model.
  19698. *
  19699. * @return {ToonLightingModel} The lighting model.
  19700. */
  19701. setupLightingModel( /*builder*/ ) {
  19702. return new ToonLightingModel();
  19703. }
  19704. }
  19705. /**
  19706. * TSL function for creating a matcap uv node.
  19707. *
  19708. * Can be used to compute texture coordinates for projecting a
  19709. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  19710. *
  19711. * @tsl
  19712. * @function
  19713. * @returns {Node<vec2>} The matcap UV coordinates.
  19714. */
  19715. const matcapUV = /*@__PURE__*/ Fn( () => {
  19716. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  19717. const y = positionViewDirection.cross( x );
  19718. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  19719. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  19720. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  19721. /**
  19722. * Node material version of {@link MeshMatcapMaterial}.
  19723. *
  19724. * @augments NodeMaterial
  19725. */
  19726. class MeshMatcapNodeMaterial extends NodeMaterial {
  19727. static get type() {
  19728. return 'MeshMatcapNodeMaterial';
  19729. }
  19730. /**
  19731. * Constructs a new mesh normal node material.
  19732. *
  19733. * @param {Object} [parameters] - The configuration parameter.
  19734. */
  19735. constructor( parameters ) {
  19736. super();
  19737. /**
  19738. * This flag can be used for type testing.
  19739. *
  19740. * @type {boolean}
  19741. * @readonly
  19742. * @default true
  19743. */
  19744. this.isMeshMatcapNodeMaterial = true;
  19745. this.setDefaultValues( _defaultValues$3 );
  19746. this.setValues( parameters );
  19747. }
  19748. /**
  19749. * Setups the matcap specific node variables.
  19750. *
  19751. * @param {NodeBuilder} builder - The current node builder.
  19752. */
  19753. setupVariants( builder ) {
  19754. const uv = matcapUV;
  19755. let matcapColor;
  19756. if ( builder.material.matcap ) {
  19757. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  19758. } else {
  19759. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  19760. }
  19761. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  19762. }
  19763. }
  19764. /**
  19765. * Applies a rotation to the given position node.
  19766. *
  19767. * @augments TempNode
  19768. */
  19769. class RotateNode extends TempNode {
  19770. static get type() {
  19771. return 'RotateNode';
  19772. }
  19773. /**
  19774. * Constructs a new rotate node.
  19775. *
  19776. * @param {Node} positionNode - The position node.
  19777. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19778. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19779. */
  19780. constructor( positionNode, rotationNode ) {
  19781. super();
  19782. /**
  19783. * The position node.
  19784. *
  19785. * @type {Node}
  19786. */
  19787. this.positionNode = positionNode;
  19788. /**
  19789. * Represents the rotation that is applied to the position node.
  19790. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19791. *
  19792. * @type {Node}
  19793. */
  19794. this.rotationNode = rotationNode;
  19795. }
  19796. /**
  19797. * The type of the {@link RotateNode#positionNode} defines the node's type.
  19798. *
  19799. * @param {NodeBuilder} builder - The current node builder.
  19800. * @return {string} The node's type.
  19801. */
  19802. getNodeType( builder ) {
  19803. return this.positionNode.getNodeType( builder );
  19804. }
  19805. setup( builder ) {
  19806. const { rotationNode, positionNode } = this;
  19807. const nodeType = this.getNodeType( builder );
  19808. if ( nodeType === 'vec2' ) {
  19809. const cosAngle = rotationNode.cos();
  19810. const sinAngle = rotationNode.sin();
  19811. const rotationMatrix = mat2(
  19812. cosAngle, sinAngle,
  19813. sinAngle.negate(), cosAngle
  19814. );
  19815. return rotationMatrix.mul( positionNode );
  19816. } else {
  19817. const rotation = rotationNode;
  19818. 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 ) );
  19819. 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 ) );
  19820. 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 ) );
  19821. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  19822. }
  19823. }
  19824. }
  19825. /**
  19826. * TSL function for creating a rotate node.
  19827. *
  19828. * @tsl
  19829. * @function
  19830. * @param {Node} positionNode - The position node.
  19831. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19832. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19833. * @returns {RotateNode}
  19834. */
  19835. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  19836. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  19837. /**
  19838. * Node material version of {@link SpriteMaterial}.
  19839. *
  19840. * @augments NodeMaterial
  19841. */
  19842. class SpriteNodeMaterial extends NodeMaterial {
  19843. static get type() {
  19844. return 'SpriteNodeMaterial';
  19845. }
  19846. /**
  19847. * Constructs a new sprite node material.
  19848. *
  19849. * @param {Object} [parameters] - The configuration parameter.
  19850. */
  19851. constructor( parameters ) {
  19852. super();
  19853. /**
  19854. * This flag can be used for type testing.
  19855. *
  19856. * @type {boolean}
  19857. * @readonly
  19858. * @default true
  19859. */
  19860. this.isSpriteNodeMaterial = true;
  19861. this._useSizeAttenuation = true;
  19862. /**
  19863. * This property makes it possible to define the position of the sprite with a
  19864. * node. That can be useful when the material is used with instanced rendering
  19865. * and node data are defined with an instanced attribute node:
  19866. * ```js
  19867. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  19868. * material.positionNode = instancedBufferAttribute( positionAttribute );
  19869. * ```
  19870. * Another possibility is to compute the instanced data with a compute shader:
  19871. * ```js
  19872. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  19873. * particleMaterial.positionNode = positionBuffer.toAttribute();
  19874. * ```
  19875. *
  19876. * @type {?Node<vec2>}
  19877. * @default null
  19878. */
  19879. this.positionNode = null;
  19880. /**
  19881. * The rotation of sprite materials is by default inferred from the `rotation`,
  19882. * property. This node property allows to overwrite the default and define
  19883. * the rotation with a node instead.
  19884. *
  19885. * If you don't want to overwrite the rotation but modify the existing
  19886. * value instead, use {@link materialRotation}.
  19887. *
  19888. * @type {?Node<float>}
  19889. * @default null
  19890. */
  19891. this.rotationNode = null;
  19892. /**
  19893. * This node property provides an additional way to scale sprites next to
  19894. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  19895. * is multiplied with the scale value of this node in the vertex shader.
  19896. *
  19897. * @type {?Node<vec2>}
  19898. * @default null
  19899. */
  19900. this.scaleNode = null;
  19901. /**
  19902. * In Sprites, the transparent property is enabled by default.
  19903. *
  19904. * @type {boolean}
  19905. * @default true
  19906. */
  19907. this.transparent = true;
  19908. this.setDefaultValues( _defaultValues$2 );
  19909. this.setValues( parameters );
  19910. }
  19911. /**
  19912. * Setups the position node in view space. This method implements
  19913. * the sprite specific vertex shader.
  19914. *
  19915. * @param {NodeBuilder} builder - The current node builder.
  19916. * @return {Node<vec3>} The position in view space.
  19917. */
  19918. setupPositionView( builder ) {
  19919. const { object, camera } = builder;
  19920. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  19921. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  19922. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  19923. if ( scaleNode !== null ) {
  19924. scale = scale.mul( vec2( scaleNode ) );
  19925. }
  19926. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  19927. scale = scale.mul( mvPosition.z.negate() );
  19928. }
  19929. let alignedPosition = positionGeometry.xy;
  19930. if ( object.center && object.center.isVector2 === true ) {
  19931. const center = reference$1( 'center', 'vec2', object );
  19932. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  19933. }
  19934. alignedPosition = alignedPosition.mul( scale );
  19935. const rotation = float( rotationNode || materialRotation );
  19936. const rotatedPosition = rotate( alignedPosition, rotation );
  19937. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  19938. }
  19939. copy( source ) {
  19940. this.positionNode = source.positionNode;
  19941. this.rotationNode = source.rotationNode;
  19942. this.scaleNode = source.scaleNode;
  19943. return super.copy( source );
  19944. }
  19945. /**
  19946. * Whether to use size attenuation or not.
  19947. *
  19948. * @type {boolean}
  19949. * @default true
  19950. */
  19951. get sizeAttenuation() {
  19952. return this._useSizeAttenuation;
  19953. }
  19954. set sizeAttenuation( value ) {
  19955. if ( this._useSizeAttenuation !== value ) {
  19956. this._useSizeAttenuation = value;
  19957. this.needsUpdate = true;
  19958. }
  19959. }
  19960. }
  19961. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  19962. const _size$4 = /*@__PURE__*/ new Vector2();
  19963. /**
  19964. * Node material version of {@link PointsMaterial}.
  19965. *
  19966. * This material can be used in two ways:
  19967. *
  19968. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  19969. * with a pixel size of `1`, it's not possible to define a size.
  19970. *
  19971. * ```js
  19972. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  19973. * ```
  19974. *
  19975. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  19976. * see {@link PointsNodeMaterial#sizeNode}.
  19977. *
  19978. * ```js
  19979. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  19980. * ```
  19981. *
  19982. * @augments SpriteNodeMaterial
  19983. */
  19984. class PointsNodeMaterial extends SpriteNodeMaterial {
  19985. static get type() {
  19986. return 'PointsNodeMaterial';
  19987. }
  19988. /**
  19989. * Constructs a new points node material.
  19990. *
  19991. * @param {Object} [parameters] - The configuration parameter.
  19992. */
  19993. constructor( parameters ) {
  19994. super();
  19995. /**
  19996. * This node property provides an additional way to set the point size.
  19997. *
  19998. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  19999. * this node has no effect when the material is used with {@link Points} and a WebGPU
  20000. * backend. If an application wants to render points with a size larger than 1 pixel,
  20001. * the material should be used with {@link Sprite} and instancing.
  20002. *
  20003. * @type {?Node<vec2>}
  20004. * @default null
  20005. */
  20006. this.sizeNode = null;
  20007. /**
  20008. * This flag can be used for type testing.
  20009. *
  20010. * @type {boolean}
  20011. * @readonly
  20012. * @default true
  20013. */
  20014. this.isPointsNodeMaterial = true;
  20015. this.setDefaultValues( _defaultValues$1 );
  20016. this.setValues( parameters );
  20017. }
  20018. setupPositionView() {
  20019. const { positionNode } = this;
  20020. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  20021. }
  20022. setupVertexSprite( builder ) {
  20023. const { material, camera } = builder;
  20024. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  20025. let mvp = super.setupVertex( builder );
  20026. // skip further processing if the material is not a node material
  20027. if ( material.isNodeMaterial !== true ) {
  20028. return mvp;
  20029. }
  20030. // point size
  20031. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  20032. pointSize = pointSize.mul( screenDPR );
  20033. // size attenuation
  20034. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  20035. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  20036. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  20037. }
  20038. // scale
  20039. if ( scaleNode && scaleNode.isNode ) {
  20040. pointSize = pointSize.mul( vec2( scaleNode ) );
  20041. }
  20042. // compute offset
  20043. let offset = positionGeometry.xy;
  20044. // apply rotation
  20045. if ( rotationNode && rotationNode.isNode ) {
  20046. const rotation = float( rotationNode );
  20047. offset = rotate( offset, rotation );
  20048. }
  20049. // account for point size
  20050. offset = offset.mul( pointSize );
  20051. // scale by viewport size
  20052. offset = offset.div( viewportSize.div( 2 ) );
  20053. // compensate for the perspective divide
  20054. offset = offset.mul( mvp.w );
  20055. // add offset
  20056. mvp = mvp.add( vec4( offset, 0, 0 ) );
  20057. return mvp;
  20058. }
  20059. setupVertex( builder ) {
  20060. if ( builder.object.isPoints ) {
  20061. return super.setupVertex( builder );
  20062. } else {
  20063. return this.setupVertexSprite( builder );
  20064. }
  20065. }
  20066. /**
  20067. * Whether alpha to coverage should be used or not.
  20068. *
  20069. * @type {boolean}
  20070. * @default true
  20071. */
  20072. get alphaToCoverage() {
  20073. return this._useAlphaToCoverage;
  20074. }
  20075. set alphaToCoverage( value ) {
  20076. if ( this._useAlphaToCoverage !== value ) {
  20077. this._useAlphaToCoverage = value;
  20078. this.needsUpdate = true;
  20079. }
  20080. }
  20081. }
  20082. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  20083. const size = renderer.getSize( _size$4 ); // logical units
  20084. this.value = 0.5 * size.y;
  20085. } );
  20086. /**
  20087. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  20088. *
  20089. * @augments LightingModel
  20090. */
  20091. class ShadowMaskModel extends LightingModel {
  20092. /**
  20093. * Constructs a new shadow mask model.
  20094. */
  20095. constructor() {
  20096. super();
  20097. /**
  20098. * The shadow mask node.
  20099. *
  20100. * @type {Node}
  20101. */
  20102. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  20103. }
  20104. /**
  20105. * Only used to save the shadow mask.
  20106. *
  20107. * @param {Object} input - The input data.
  20108. */
  20109. direct( { lightNode } ) {
  20110. if ( lightNode.shadowNode !== null ) {
  20111. this.shadowNode.mulAssign( lightNode.shadowNode );
  20112. }
  20113. }
  20114. /**
  20115. * Uses the shadow mask to produce the final color.
  20116. *
  20117. * @param {NodeBuilder} builder - The current node builder.
  20118. */
  20119. finish( { context } ) {
  20120. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  20121. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  20122. }
  20123. }
  20124. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  20125. /**
  20126. * Node material version of {@link ShadowMaterial}.
  20127. *
  20128. * @augments NodeMaterial
  20129. */
  20130. class ShadowNodeMaterial extends NodeMaterial {
  20131. static get type() {
  20132. return 'ShadowNodeMaterial';
  20133. }
  20134. /**
  20135. * Constructs a new shadow node material.
  20136. *
  20137. * @param {Object} [parameters] - The configuration parameter.
  20138. */
  20139. constructor( parameters ) {
  20140. super();
  20141. /**
  20142. * This flag can be used for type testing.
  20143. *
  20144. * @type {boolean}
  20145. * @readonly
  20146. * @default true
  20147. */
  20148. this.isShadowNodeMaterial = true;
  20149. /**
  20150. * Set to `true` because so it's possible to implement
  20151. * the shadow mask effect.
  20152. *
  20153. * @type {boolean}
  20154. * @default true
  20155. */
  20156. this.lights = true;
  20157. /**
  20158. * Overwritten since shadow materials are transparent
  20159. * by default.
  20160. *
  20161. * @type {boolean}
  20162. * @default true
  20163. */
  20164. this.transparent = true;
  20165. this.setDefaultValues( _defaultValues );
  20166. this.setValues( parameters );
  20167. }
  20168. /**
  20169. * Setups the lighting model.
  20170. *
  20171. * @return {ShadowMaskModel} The lighting model.
  20172. */
  20173. setupLightingModel( /*builder*/ ) {
  20174. return new ShadowMaskModel();
  20175. }
  20176. }
  20177. const scatteringDensity = property( 'vec3' );
  20178. const linearDepthRay = property( 'vec3' );
  20179. const outgoingRayLight = property( 'vec3' );
  20180. /**
  20181. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  20182. * This model calculates the scattering and transmittance of light through a volumetric medium.
  20183. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  20184. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  20185. *
  20186. * @augments LightingModel
  20187. */
  20188. class VolumetricLightingModel extends LightingModel {
  20189. constructor() {
  20190. super();
  20191. }
  20192. start( builder ) {
  20193. const { material } = builder;
  20194. const startPos = property( 'vec3' );
  20195. const endPos = property( 'vec3' );
  20196. // This approach dynamically changes the direction of the ray,
  20197. // 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.
  20198. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  20199. startPos.assign( cameraPosition );
  20200. endPos.assign( positionWorld );
  20201. } ).Else( () => {
  20202. startPos.assign( positionWorld );
  20203. endPos.assign( cameraPosition );
  20204. } );
  20205. //
  20206. const viewVector = endPos.sub( startPos );
  20207. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  20208. const stepSize = viewVector.length().div( steps ).toVar();
  20209. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  20210. const distTravelled = float( 0.0 ).toVar();
  20211. const transmittance = vec3( 1 ).toVar();
  20212. if ( material.offsetNode ) {
  20213. // reduce banding
  20214. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  20215. }
  20216. Loop( steps, () => {
  20217. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  20218. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  20219. if ( material.depthNode !== null ) {
  20220. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  20221. builder.context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  20222. }
  20223. builder.context.positionWorld = positionRay;
  20224. builder.context.shadowPositionWorld = positionRay;
  20225. builder.context.positionView = positionViewRay;
  20226. scatteringDensity.assign( 0 );
  20227. let scatteringNode;
  20228. if ( material.scatteringNode ) {
  20229. scatteringNode = material.scatteringNode( {
  20230. positionRay
  20231. } );
  20232. }
  20233. super.start( builder );
  20234. if ( scatteringNode ) {
  20235. scatteringDensity.mulAssign( scatteringNode );
  20236. }
  20237. // beer's law
  20238. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  20239. transmittance.mulAssign( falloff );
  20240. // move along the ray
  20241. distTravelled.addAssign( stepSize );
  20242. } );
  20243. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  20244. }
  20245. scatteringLight( lightColor, builder ) {
  20246. const sceneDepthNode = builder.context.sceneDepthNode;
  20247. if ( sceneDepthNode ) {
  20248. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  20249. scatteringDensity.addAssign( lightColor );
  20250. } );
  20251. } else {
  20252. scatteringDensity.addAssign( lightColor );
  20253. }
  20254. }
  20255. direct( { lightNode, lightColor }, builder ) {
  20256. // Ignore lights with infinite distance
  20257. if ( lightNode.light.distance === undefined ) return;
  20258. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  20259. const directLight = lightColor.xyz.toVar();
  20260. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  20261. this.scatteringLight( directLight, builder );
  20262. }
  20263. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  20264. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  20265. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  20266. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  20267. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  20268. const P = builder.context.positionView;
  20269. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  20270. this.scatteringLight( directLight, builder );
  20271. }
  20272. finish( builder ) {
  20273. builder.context.outgoingLight.assign( outgoingRayLight );
  20274. }
  20275. }
  20276. /**
  20277. * Volume node material.
  20278. *
  20279. * @augments NodeMaterial
  20280. */
  20281. class VolumeNodeMaterial extends NodeMaterial {
  20282. static get type() {
  20283. return 'VolumeNodeMaterial';
  20284. }
  20285. /**
  20286. * Constructs a new volume node material.
  20287. *
  20288. * @param {Object} [parameters] - The configuration parameter.
  20289. */
  20290. constructor( parameters ) {
  20291. super();
  20292. /**
  20293. * This flag can be used for type testing.
  20294. *
  20295. * @type {boolean}
  20296. * @readonly
  20297. * @default true
  20298. */
  20299. this.isVolumeNodeMaterial = true;
  20300. /**
  20301. * Number of steps used for raymarching.
  20302. *
  20303. * @type {number}
  20304. * @default 25
  20305. */
  20306. this.steps = 25;
  20307. /**
  20308. * Offsets the distance a ray has been traveled through a volume.
  20309. * Can be used to implement dithering to reduce banding.
  20310. *
  20311. * @type {Node<float>}
  20312. * @default null
  20313. */
  20314. this.offsetNode = null;
  20315. /**
  20316. * Node used for scattering calculations.
  20317. *
  20318. * @type {Function|FunctionNode<vec4>}
  20319. * @default null
  20320. */
  20321. this.scatteringNode = null;
  20322. this.lights = true;
  20323. this.transparent = true;
  20324. this.side = BackSide;
  20325. this.depthTest = false;
  20326. this.depthWrite = false;
  20327. this.setValues( parameters );
  20328. }
  20329. setupLightingModel() {
  20330. return new VolumetricLightingModel();
  20331. }
  20332. }
  20333. /**
  20334. * This module manages the internal animation loop of the renderer.
  20335. *
  20336. * @private
  20337. */
  20338. class Animation {
  20339. /**
  20340. * Constructs a new animation loop management component.
  20341. *
  20342. * @param {Renderer} renderer - A reference to the main renderer.
  20343. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20344. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20345. */
  20346. constructor( renderer, nodes, info ) {
  20347. /**
  20348. * A reference to the main renderer.
  20349. *
  20350. * @type {Renderer}
  20351. */
  20352. this.renderer = renderer;
  20353. /**
  20354. * Renderer component for managing nodes related logic.
  20355. *
  20356. * @type {Nodes}
  20357. */
  20358. this.nodes = nodes;
  20359. /**
  20360. * Renderer component for managing metrics and monitoring data.
  20361. *
  20362. * @type {Info}
  20363. */
  20364. this.info = info;
  20365. /**
  20366. * A reference to the context from `requestAnimationFrame()` can
  20367. * be called (usually `window`).
  20368. *
  20369. * @type {?(Window|XRSession)}
  20370. */
  20371. this._context = typeof self !== 'undefined' ? self : null;
  20372. /**
  20373. * The user-defined animation loop.
  20374. *
  20375. * @type {?Function}
  20376. * @default null
  20377. */
  20378. this._animationLoop = null;
  20379. /**
  20380. * The requestId which is returned from the `requestAnimationFrame()` call.
  20381. * Can be used to cancel the stop the animation loop.
  20382. *
  20383. * @type {?number}
  20384. * @default null
  20385. */
  20386. this._requestId = null;
  20387. }
  20388. /**
  20389. * Starts the internal animation loop.
  20390. */
  20391. start() {
  20392. const update = ( time, xrFrame ) => {
  20393. this._requestId = this._context.requestAnimationFrame( update );
  20394. if ( this.info.autoReset === true ) this.info.reset();
  20395. this.nodes.nodeFrame.update();
  20396. this.info.frame = this.nodes.nodeFrame.frameId;
  20397. this.renderer._inspector.begin();
  20398. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  20399. this.renderer._inspector.finish();
  20400. };
  20401. update();
  20402. }
  20403. /**
  20404. * Stops the internal animation loop.
  20405. */
  20406. stop() {
  20407. this._context.cancelAnimationFrame( this._requestId );
  20408. this._requestId = null;
  20409. }
  20410. /**
  20411. * Returns the user-level animation loop.
  20412. *
  20413. * @return {?Function} The animation loop.
  20414. */
  20415. getAnimationLoop() {
  20416. return this._animationLoop;
  20417. }
  20418. /**
  20419. * Defines the user-level animation loop.
  20420. *
  20421. * @param {?Function} callback - The animation loop.
  20422. */
  20423. setAnimationLoop( callback ) {
  20424. this._animationLoop = callback;
  20425. }
  20426. /**
  20427. * Returns the animation context.
  20428. *
  20429. * @return {Window|XRSession} The animation context.
  20430. */
  20431. getContext() {
  20432. return this._context;
  20433. }
  20434. /**
  20435. * Defines the context in which `requestAnimationFrame()` is executed.
  20436. *
  20437. * @param {Window|XRSession} context - The context to set.
  20438. */
  20439. setContext( context ) {
  20440. this._context = context;
  20441. }
  20442. /**
  20443. * Frees all internal resources and stops the animation loop.
  20444. */
  20445. dispose() {
  20446. this.stop();
  20447. }
  20448. }
  20449. /**
  20450. * Data structure for the renderer. It allows defining values
  20451. * with chained, hierarchical keys. Keys are meant to be
  20452. * objects since the module internally works with Weak Maps
  20453. * for performance reasons.
  20454. *
  20455. * @private
  20456. */
  20457. class ChainMap {
  20458. /**
  20459. * Constructs a new Chain Map.
  20460. */
  20461. constructor() {
  20462. /**
  20463. * A map of Weak Maps by their key length.
  20464. *
  20465. * @type {Object<number, WeakMap>}
  20466. */
  20467. this.weakMaps = {};
  20468. }
  20469. /**
  20470. * Returns the Weak Map for the given keys.
  20471. *
  20472. * @param {Array<Object>} keys - List of keys.
  20473. * @return {WeakMap} The weak map.
  20474. */
  20475. _getWeakMap( keys ) {
  20476. const length = keys.length;
  20477. let weakMap = this.weakMaps[ length ];
  20478. if ( weakMap === undefined ) {
  20479. weakMap = new WeakMap();
  20480. this.weakMaps[ length ] = weakMap;
  20481. }
  20482. return weakMap;
  20483. }
  20484. /**
  20485. * Returns the value for the given array of keys.
  20486. *
  20487. * @param {Array<Object>} keys - List of keys.
  20488. * @return {any} The value. Returns `undefined` if no value was found.
  20489. */
  20490. get( keys ) {
  20491. let map = this._getWeakMap( keys );
  20492. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20493. map = map.get( keys[ i ] );
  20494. if ( map === undefined ) return undefined;
  20495. }
  20496. return map.get( keys[ keys.length - 1 ] );
  20497. }
  20498. /**
  20499. * Sets the value for the given keys.
  20500. *
  20501. * @param {Array<Object>} keys - List of keys.
  20502. * @param {any} value - The value to set.
  20503. * @return {ChainMap} A reference to this Chain Map.
  20504. */
  20505. set( keys, value ) {
  20506. let map = this._getWeakMap( keys );
  20507. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20508. const key = keys[ i ];
  20509. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  20510. map = map.get( key );
  20511. }
  20512. map.set( keys[ keys.length - 1 ], value );
  20513. return this;
  20514. }
  20515. /**
  20516. * Deletes a value for the given keys.
  20517. *
  20518. * @param {Array<Object>} keys - The keys.
  20519. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  20520. */
  20521. delete( keys ) {
  20522. let map = this._getWeakMap( keys );
  20523. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20524. map = map.get( keys[ i ] );
  20525. if ( map === undefined ) return false;
  20526. }
  20527. return map.delete( keys[ keys.length - 1 ] );
  20528. }
  20529. }
  20530. let _id$a = 0;
  20531. function getKeys( obj ) {
  20532. const keys = Object.keys( obj );
  20533. let proto = Object.getPrototypeOf( obj );
  20534. while ( proto ) {
  20535. const descriptors = Object.getOwnPropertyDescriptors( proto );
  20536. for ( const key in descriptors ) {
  20537. if ( descriptors[ key ] !== undefined ) {
  20538. const descriptor = descriptors[ key ];
  20539. if ( descriptor && typeof descriptor.get === 'function' ) {
  20540. keys.push( key );
  20541. }
  20542. }
  20543. }
  20544. proto = Object.getPrototypeOf( proto );
  20545. }
  20546. return keys;
  20547. }
  20548. /**
  20549. * A render object is the renderer's representation of single entity that gets drawn
  20550. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  20551. * scene since render objects also depend from the used material, the current render context
  20552. * and the current scene's lighting.
  20553. *
  20554. * In general, the basic process of the renderer is:
  20555. *
  20556. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  20557. * - Process the render lists by calling one or more render commands for each render item.
  20558. * - For each render command, request a render object and perform the draw.
  20559. *
  20560. * The module provides an interface to get data required for the draw command like the actual
  20561. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  20562. * creating render objects should only be done when necessary.
  20563. *
  20564. * @private
  20565. */
  20566. class RenderObject {
  20567. /**
  20568. * Constructs a new render object.
  20569. *
  20570. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20571. * @param {Geometries} geometries - Renderer component for managing geometries.
  20572. * @param {Renderer} renderer - The renderer.
  20573. * @param {Object3D} object - The 3D object.
  20574. * @param {Material} material - The 3D object's material.
  20575. * @param {Scene} scene - The scene the 3D object belongs to.
  20576. * @param {Camera} camera - The camera the object should be rendered with.
  20577. * @param {LightsNode} lightsNode - The lights node.
  20578. * @param {RenderContext} renderContext - The render context.
  20579. * @param {ClippingContext} clippingContext - The clipping context.
  20580. */
  20581. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  20582. this.id = _id$a ++;
  20583. /**
  20584. * Renderer component for managing nodes related logic.
  20585. *
  20586. * @type {Nodes}
  20587. * @private
  20588. */
  20589. this._nodes = nodes;
  20590. /**
  20591. * Renderer component for managing geometries.
  20592. *
  20593. * @type {Geometries}
  20594. * @private
  20595. */
  20596. this._geometries = geometries;
  20597. /**
  20598. * The renderer.
  20599. *
  20600. * @type {Renderer}
  20601. */
  20602. this.renderer = renderer;
  20603. /**
  20604. * The 3D object.
  20605. *
  20606. * @type {Object3D}
  20607. */
  20608. this.object = object;
  20609. /**
  20610. * The 3D object's material.
  20611. *
  20612. * @type {Material}
  20613. */
  20614. this.material = material;
  20615. /**
  20616. * The scene the 3D object belongs to.
  20617. *
  20618. * @type {Scene}
  20619. */
  20620. this.scene = scene;
  20621. /**
  20622. * The camera the 3D object should be rendered with.
  20623. *
  20624. * @type {Camera}
  20625. */
  20626. this.camera = camera;
  20627. /**
  20628. * The lights node.
  20629. *
  20630. * @type {LightsNode}
  20631. */
  20632. this.lightsNode = lightsNode;
  20633. /**
  20634. * The render context.
  20635. *
  20636. * @type {RenderContext}
  20637. */
  20638. this.context = renderContext;
  20639. /**
  20640. * The 3D object's geometry.
  20641. *
  20642. * @type {BufferGeometry}
  20643. */
  20644. this.geometry = object.geometry;
  20645. /**
  20646. * The render object's version.
  20647. *
  20648. * @type {number}
  20649. */
  20650. this.version = material.version;
  20651. /**
  20652. * The draw range of the geometry.
  20653. *
  20654. * @type {?Object}
  20655. * @default null
  20656. */
  20657. this.drawRange = null;
  20658. /**
  20659. * An array holding the buffer attributes
  20660. * of the render object. This entails attribute
  20661. * definitions on geometry and node level.
  20662. *
  20663. * @type {?Array<BufferAttribute>}
  20664. * @default null
  20665. */
  20666. this.attributes = null;
  20667. /**
  20668. * An object holding the version of the
  20669. * attributes. The keys are the attribute names
  20670. * and the values are the attribute versions.
  20671. *
  20672. * @type {?Object<string, number>}
  20673. * @default null
  20674. */
  20675. this.attributesId = null;
  20676. /**
  20677. * A reference to a render pipeline the render
  20678. * object is processed with.
  20679. *
  20680. * @type {RenderPipeline}
  20681. * @default null
  20682. */
  20683. this.pipeline = null;
  20684. /**
  20685. * Only relevant for objects using
  20686. * multiple materials. This represents a group entry
  20687. * from the respective `BufferGeometry`.
  20688. *
  20689. * @type {?{start: number, count: number}}
  20690. * @default null
  20691. */
  20692. this.group = null;
  20693. /**
  20694. * An array holding the vertex buffers which can
  20695. * be buffer attributes but also interleaved buffers.
  20696. *
  20697. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  20698. * @default null
  20699. */
  20700. this.vertexBuffers = null;
  20701. /**
  20702. * The parameters for the draw command.
  20703. *
  20704. * @type {?Object}
  20705. * @default null
  20706. */
  20707. this.drawParams = null;
  20708. /**
  20709. * If this render object is used inside a render bundle,
  20710. * this property points to the respective bundle group.
  20711. *
  20712. * @type {?BundleGroup}
  20713. * @default null
  20714. */
  20715. this.bundle = null;
  20716. /**
  20717. * The clipping context.
  20718. *
  20719. * @type {ClippingContext}
  20720. */
  20721. this.clippingContext = clippingContext;
  20722. /**
  20723. * The clipping context's cache key.
  20724. *
  20725. * @type {string}
  20726. */
  20727. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  20728. /**
  20729. * The initial node cache key.
  20730. *
  20731. * @type {number}
  20732. */
  20733. this.initialNodesCacheKey = this.getDynamicCacheKey();
  20734. /**
  20735. * The initial cache key.
  20736. *
  20737. * @type {number}
  20738. */
  20739. this.initialCacheKey = this.getCacheKey();
  20740. /**
  20741. * The node builder state.
  20742. *
  20743. * @type {?NodeBuilderState}
  20744. * @private
  20745. * @default null
  20746. */
  20747. this._nodeBuilderState = null;
  20748. /**
  20749. * An array of bindings.
  20750. *
  20751. * @type {?Array<BindGroup>}
  20752. * @private
  20753. * @default null
  20754. */
  20755. this._bindings = null;
  20756. /**
  20757. * Reference to the node material observer.
  20758. *
  20759. * @type {?NodeMaterialObserver}
  20760. * @private
  20761. * @default null
  20762. */
  20763. this._monitor = null;
  20764. /**
  20765. * An event listener which is defined by `RenderObjects`. It performs
  20766. * clean up tasks when `dispose()` on this render object.
  20767. *
  20768. * @method
  20769. */
  20770. this.onDispose = null;
  20771. /**
  20772. * This flag can be used for type testing.
  20773. *
  20774. * @type {boolean}
  20775. * @readonly
  20776. * @default true
  20777. */
  20778. this.isRenderObject = true;
  20779. /**
  20780. * An event listener which is executed when `dispose()` is called on
  20781. * the material of this render object.
  20782. *
  20783. * @method
  20784. */
  20785. this.onMaterialDispose = () => {
  20786. this.dispose();
  20787. };
  20788. /**
  20789. * An event listener which is executed when `dispose()` is called on
  20790. * the geometry of this render object.
  20791. *
  20792. * @method
  20793. */
  20794. this.onGeometryDispose = () => {
  20795. // clear geometry cache attributes
  20796. this.attributes = null;
  20797. this.attributesId = null;
  20798. };
  20799. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  20800. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  20801. }
  20802. /**
  20803. * Updates the clipping context.
  20804. *
  20805. * @param {ClippingContext} context - The clipping context to set.
  20806. */
  20807. updateClipping( context ) {
  20808. this.clippingContext = context;
  20809. }
  20810. /**
  20811. * Whether the clipping requires an update or not.
  20812. *
  20813. * @type {boolean}
  20814. * @readonly
  20815. */
  20816. get clippingNeedsUpdate() {
  20817. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  20818. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  20819. return true;
  20820. }
  20821. /**
  20822. * The number of clipping planes defined in context of hardware clipping.
  20823. *
  20824. * @type {number}
  20825. * @readonly
  20826. */
  20827. get hardwareClippingPlanes() {
  20828. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  20829. }
  20830. /**
  20831. * Returns the node builder state of this render object.
  20832. *
  20833. * @return {NodeBuilderState} The node builder state.
  20834. */
  20835. getNodeBuilderState() {
  20836. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  20837. }
  20838. /**
  20839. * Returns the node material observer of this render object.
  20840. *
  20841. * @return {NodeMaterialObserver} The node material observer.
  20842. */
  20843. getMonitor() {
  20844. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  20845. }
  20846. /**
  20847. * Returns an array of bind groups of this render object.
  20848. *
  20849. * @return {Array<BindGroup>} The bindings.
  20850. */
  20851. getBindings() {
  20852. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  20853. }
  20854. /**
  20855. * Returns a binding group by group name of this render object.
  20856. *
  20857. * @param {string} name - The name of the binding group.
  20858. * @return {?BindGroup} The bindings.
  20859. */
  20860. getBindingGroup( name ) {
  20861. for ( const bindingGroup of this.getBindings() ) {
  20862. if ( bindingGroup.name === name ) {
  20863. return bindingGroup;
  20864. }
  20865. }
  20866. }
  20867. /**
  20868. * Returns the index of the render object's geometry.
  20869. *
  20870. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20871. */
  20872. getIndex() {
  20873. return this._geometries.getIndex( this );
  20874. }
  20875. /**
  20876. * Returns the indirect buffer attribute.
  20877. *
  20878. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20879. */
  20880. getIndirect() {
  20881. return this._geometries.getIndirect( this );
  20882. }
  20883. /**
  20884. * Returns the byte offset into the indirect attribute buffer.
  20885. *
  20886. * @return {number|Array<number>} The byte offset into the indirect attribute buffer.
  20887. */
  20888. getIndirectOffset() {
  20889. return this._geometries.getIndirectOffset( this );
  20890. }
  20891. /**
  20892. * Returns an array that acts as a key for identifying the render object in a chain map.
  20893. *
  20894. * @return {Array<Object>} An array with object references.
  20895. */
  20896. getChainArray() {
  20897. return [ this.object, this.material, this.context, this.lightsNode ];
  20898. }
  20899. /**
  20900. * This method is used when the geometry of a 3D object has been exchanged and the
  20901. * respective render object now requires an update.
  20902. *
  20903. * @param {BufferGeometry} geometry - The geometry to set.
  20904. */
  20905. setGeometry( geometry ) {
  20906. this.geometry = geometry;
  20907. this.attributes = null;
  20908. this.attributesId = null;
  20909. }
  20910. /**
  20911. * Returns the buffer attributes of the render object. The returned array holds
  20912. * attribute definitions on geometry and node level.
  20913. *
  20914. * @return {Array<BufferAttribute>} An array with buffer attributes.
  20915. */
  20916. getAttributes() {
  20917. if ( this.attributes !== null ) return this.attributes;
  20918. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  20919. const geometry = this.geometry;
  20920. const attributes = [];
  20921. const vertexBuffers = new Set();
  20922. const attributesId = {};
  20923. for ( const nodeAttribute of nodeAttributes ) {
  20924. let attribute;
  20925. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  20926. // node attribute
  20927. attribute = nodeAttribute.node.attribute;
  20928. } else {
  20929. // geometry attribute
  20930. attribute = geometry.getAttribute( nodeAttribute.name );
  20931. attributesId[ nodeAttribute.name ] = attribute.id;
  20932. }
  20933. if ( attribute === undefined ) continue;
  20934. attributes.push( attribute );
  20935. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20936. vertexBuffers.add( bufferAttribute );
  20937. }
  20938. this.attributes = attributes;
  20939. this.attributesId = attributesId;
  20940. this.vertexBuffers = Array.from( vertexBuffers.values() );
  20941. return attributes;
  20942. }
  20943. /**
  20944. * Returns the vertex buffers of the render object.
  20945. *
  20946. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  20947. */
  20948. getVertexBuffers() {
  20949. if ( this.vertexBuffers === null ) this.getAttributes();
  20950. return this.vertexBuffers;
  20951. }
  20952. /**
  20953. * Returns the draw parameters for the render object.
  20954. *
  20955. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  20956. */
  20957. getDrawParameters() {
  20958. const { object, material, geometry, group, drawRange } = this;
  20959. const drawParams = this.drawParams || ( this.drawParams = {
  20960. vertexCount: 0,
  20961. firstVertex: 0,
  20962. instanceCount: 0,
  20963. firstInstance: 0
  20964. } );
  20965. const index = this.getIndex();
  20966. const hasIndex = ( index !== null );
  20967. let instanceCount = 1;
  20968. if ( geometry.isInstancedBufferGeometry === true ) {
  20969. instanceCount = geometry.instanceCount;
  20970. } else if ( object.count !== undefined ) {
  20971. instanceCount = Math.max( 0, object.count );
  20972. }
  20973. if ( instanceCount === 0 ) return null;
  20974. drawParams.instanceCount = instanceCount;
  20975. if ( object.isBatchedMesh === true ) return drawParams;
  20976. let rangeFactor = 1;
  20977. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  20978. rangeFactor = 2;
  20979. }
  20980. let firstVertex = drawRange.start * rangeFactor;
  20981. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  20982. if ( group !== null ) {
  20983. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  20984. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  20985. }
  20986. const position = geometry.attributes.position;
  20987. let itemCount = Infinity;
  20988. if ( hasIndex ) {
  20989. itemCount = index.count;
  20990. } else if ( position !== undefined && position !== null ) {
  20991. itemCount = position.count;
  20992. }
  20993. firstVertex = Math.max( firstVertex, 0 );
  20994. lastVertex = Math.min( lastVertex, itemCount );
  20995. const count = lastVertex - firstVertex;
  20996. if ( count < 0 || count === Infinity ) return null;
  20997. drawParams.vertexCount = count;
  20998. drawParams.firstVertex = firstVertex;
  20999. return drawParams;
  21000. }
  21001. /**
  21002. * Returns the render object's geometry cache key.
  21003. *
  21004. * The geometry cache key is part of the material cache key.
  21005. *
  21006. * @return {string} The geometry cache key.
  21007. */
  21008. getGeometryCacheKey() {
  21009. const { geometry } = this;
  21010. let cacheKey = '';
  21011. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  21012. const attribute = geometry.attributes[ name ];
  21013. cacheKey += name + ',';
  21014. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  21015. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  21016. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  21017. if ( attribute.normalized ) cacheKey += 'n,';
  21018. }
  21019. // structural equality isn't sufficient for morph targets since the
  21020. // data are maintained in textures. only if the targets are all equal
  21021. // the texture and thus the instance of `MorphNode` can be shared.
  21022. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  21023. const targets = geometry.morphAttributes[ name ];
  21024. cacheKey += 'morph-' + name + ',';
  21025. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  21026. const attribute = targets[ i ];
  21027. cacheKey += attribute.id + ',';
  21028. }
  21029. }
  21030. if ( geometry.index ) {
  21031. cacheKey += 'index,';
  21032. }
  21033. return cacheKey;
  21034. }
  21035. /**
  21036. * Returns the render object's material cache key.
  21037. *
  21038. * The material cache key is part of the render object cache key.
  21039. *
  21040. * @return {number} The material cache key.
  21041. */
  21042. getMaterialCacheKey() {
  21043. const { object, material, renderer } = this;
  21044. let cacheKey = material.customProgramCacheKey();
  21045. for ( const property of getKeys( material ) ) {
  21046. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  21047. const value = material[ property ];
  21048. let valueKey;
  21049. if ( value !== null ) {
  21050. // some material values require a formatting
  21051. const type = typeof value;
  21052. if ( type === 'number' ) {
  21053. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  21054. } else if ( type === 'object' ) {
  21055. valueKey = '{';
  21056. if ( value.isTexture ) {
  21057. valueKey += value.mapping;
  21058. // WebGPU must honor the sampler data because they are part of the bindings
  21059. if ( renderer.backend.isWebGPUBackend === true ) {
  21060. valueKey += value.magFilter;
  21061. valueKey += value.minFilter;
  21062. valueKey += value.wrapS;
  21063. valueKey += value.wrapT;
  21064. valueKey += value.wrapR;
  21065. }
  21066. }
  21067. valueKey += '}';
  21068. } else {
  21069. valueKey = String( value );
  21070. }
  21071. } else {
  21072. valueKey = String( value );
  21073. }
  21074. cacheKey += /*property + ':' +*/ valueKey + ',';
  21075. }
  21076. cacheKey += this.clippingContextCacheKey + ',';
  21077. if ( object.geometry ) {
  21078. cacheKey += this.getGeometryCacheKey();
  21079. }
  21080. if ( object.skeleton ) {
  21081. cacheKey += object.skeleton.bones.length + ',';
  21082. }
  21083. if ( object.isBatchedMesh ) {
  21084. cacheKey += object._matricesTexture.uuid + ',';
  21085. if ( object._colorsTexture !== null ) {
  21086. cacheKey += object._colorsTexture.uuid + ',';
  21087. }
  21088. }
  21089. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  21090. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  21091. cacheKey += object.uuid + ',';
  21092. }
  21093. cacheKey += this.context.id + ',';
  21094. cacheKey += object.receiveShadow + ',';
  21095. return hashString( cacheKey );
  21096. }
  21097. /**
  21098. * Whether the geometry requires an update or not.
  21099. *
  21100. * @type {boolean}
  21101. * @readonly
  21102. */
  21103. get needsGeometryUpdate() {
  21104. if ( this.geometry.id !== this.object.geometry.id ) return true;
  21105. if ( this.attributes !== null ) {
  21106. const attributesId = this.attributesId;
  21107. for ( const name in attributesId ) {
  21108. const attribute = this.geometry.getAttribute( name );
  21109. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  21110. return true;
  21111. }
  21112. }
  21113. }
  21114. return false;
  21115. }
  21116. /**
  21117. * Whether the render object requires an update or not.
  21118. *
  21119. * Note: There are two distinct places where render objects are checked for an update.
  21120. *
  21121. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  21122. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  21123. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  21124. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  21125. * a need for a refresh due to material, geometry or object related value changes.
  21126. *
  21127. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  21128. * that performs the 'needsUpdate' check.
  21129. *
  21130. * @type {boolean}
  21131. * @readonly
  21132. */
  21133. get needsUpdate() {
  21134. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  21135. }
  21136. /**
  21137. * Returns the dynamic cache key which represents a key that is computed per draw command.
  21138. *
  21139. * @return {number} The cache key.
  21140. */
  21141. getDynamicCacheKey() {
  21142. let cacheKey = 0;
  21143. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  21144. // the renderer is inside a shadow pass.
  21145. if ( this.material.isShadowPassMaterial !== true ) {
  21146. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  21147. }
  21148. if ( this.camera.isArrayCamera ) {
  21149. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  21150. }
  21151. if ( this.object.receiveShadow ) {
  21152. cacheKey = hash$1( cacheKey, 1 );
  21153. }
  21154. cacheKey = hash$1( cacheKey, this.renderer.contextNode.id, this.renderer.contextNode.version );
  21155. return cacheKey;
  21156. }
  21157. /**
  21158. * Returns the render object's cache key.
  21159. *
  21160. * @return {number} The cache key.
  21161. */
  21162. getCacheKey() {
  21163. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  21164. }
  21165. /**
  21166. * Frees internal resources.
  21167. */
  21168. dispose() {
  21169. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  21170. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  21171. this.onDispose();
  21172. }
  21173. }
  21174. const _chainKeys$3 = [];
  21175. /**
  21176. * This module manages the render objects of the renderer.
  21177. *
  21178. * @private
  21179. */
  21180. class RenderObjects {
  21181. /**
  21182. * Constructs a new render object management component.
  21183. *
  21184. * @param {Renderer} renderer - The renderer.
  21185. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21186. * @param {Geometries} geometries - Renderer component for managing geometries.
  21187. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  21188. * @param {Bindings} bindings - Renderer component for managing bindings.
  21189. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21190. */
  21191. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  21192. /**
  21193. * The renderer.
  21194. *
  21195. * @type {Renderer}
  21196. */
  21197. this.renderer = renderer;
  21198. /**
  21199. * Renderer component for managing nodes related logic.
  21200. *
  21201. * @type {Nodes}
  21202. */
  21203. this.nodes = nodes;
  21204. /**
  21205. * Renderer component for managing geometries.
  21206. *
  21207. * @type {Geometries}
  21208. */
  21209. this.geometries = geometries;
  21210. /**
  21211. * Renderer component for managing pipelines.
  21212. *
  21213. * @type {Pipelines}
  21214. */
  21215. this.pipelines = pipelines;
  21216. /**
  21217. * Renderer component for managing bindings.
  21218. *
  21219. * @type {Bindings}
  21220. */
  21221. this.bindings = bindings;
  21222. /**
  21223. * Renderer component for managing metrics and monitoring data.
  21224. *
  21225. * @type {Info}
  21226. */
  21227. this.info = info;
  21228. /**
  21229. * A dictionary that manages render contexts in chain maps
  21230. * for each pass ID.
  21231. *
  21232. * @type {Object<string,ChainMap>}
  21233. */
  21234. this.chainMaps = {};
  21235. }
  21236. /**
  21237. * Returns a render object for the given object and state data.
  21238. *
  21239. * @param {Object3D} object - The 3D object.
  21240. * @param {Material} material - The 3D object's material.
  21241. * @param {Scene} scene - The scene the 3D object belongs to.
  21242. * @param {Camera} camera - The camera the 3D object should be rendered with.
  21243. * @param {LightsNode} lightsNode - The lights node.
  21244. * @param {RenderContext} renderContext - The render context.
  21245. * @param {ClippingContext} clippingContext - The clipping context.
  21246. * @param {string} [passId] - An optional ID for identifying the pass.
  21247. * @return {RenderObject} The render object.
  21248. */
  21249. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21250. const chainMap = this.getChainMap( passId );
  21251. // set chain keys
  21252. _chainKeys$3[ 0 ] = object;
  21253. _chainKeys$3[ 1 ] = material;
  21254. _chainKeys$3[ 2 ] = renderContext;
  21255. _chainKeys$3[ 3 ] = lightsNode;
  21256. //
  21257. let renderObject = chainMap.get( _chainKeys$3 );
  21258. if ( renderObject === undefined ) {
  21259. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21260. chainMap.set( _chainKeys$3, renderObject );
  21261. } else {
  21262. // update references
  21263. renderObject.camera = camera;
  21264. //
  21265. renderObject.updateClipping( clippingContext );
  21266. if ( renderObject.needsGeometryUpdate ) {
  21267. renderObject.setGeometry( object.geometry );
  21268. }
  21269. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21270. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21271. renderObject.dispose();
  21272. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21273. } else {
  21274. renderObject.version = material.version;
  21275. }
  21276. }
  21277. }
  21278. // reset chain array
  21279. _chainKeys$3[ 0 ] = null;
  21280. _chainKeys$3[ 1 ] = null;
  21281. _chainKeys$3[ 2 ] = null;
  21282. _chainKeys$3[ 3 ] = null;
  21283. //
  21284. return renderObject;
  21285. }
  21286. /**
  21287. * Returns a chain map for the given pass ID.
  21288. *
  21289. * @param {string} [passId='default'] - The pass ID.
  21290. * @return {ChainMap} The chain map.
  21291. */
  21292. getChainMap( passId = 'default' ) {
  21293. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21294. }
  21295. /**
  21296. * Frees internal resources.
  21297. */
  21298. dispose() {
  21299. this.chainMaps = {};
  21300. }
  21301. /**
  21302. * Factory method for creating render objects with the given list of parameters.
  21303. *
  21304. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21305. * @param {Geometries} geometries - Renderer component for managing geometries.
  21306. * @param {Renderer} renderer - The renderer.
  21307. * @param {Object3D} object - The 3D object.
  21308. * @param {Material} material - The object's material.
  21309. * @param {Scene} scene - The scene the 3D object belongs to.
  21310. * @param {Camera} camera - The camera the object should be rendered with.
  21311. * @param {LightsNode} lightsNode - The lights node.
  21312. * @param {RenderContext} renderContext - The render context.
  21313. * @param {ClippingContext} clippingContext - The clipping context.
  21314. * @param {string} [passId] - An optional ID for identifying the pass.
  21315. * @return {RenderObject} The render object.
  21316. */
  21317. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21318. const chainMap = this.getChainMap( passId );
  21319. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  21320. renderObject.onDispose = () => {
  21321. this.pipelines.delete( renderObject );
  21322. this.bindings.deleteForRender( renderObject );
  21323. this.nodes.delete( renderObject );
  21324. chainMap.delete( renderObject.getChainArray() );
  21325. };
  21326. return renderObject;
  21327. }
  21328. }
  21329. /**
  21330. * Data structure for the renderer. It is intended to manage
  21331. * data of objects in dictionaries.
  21332. *
  21333. * @private
  21334. */
  21335. class DataMap {
  21336. /**
  21337. * Constructs a new data map.
  21338. */
  21339. constructor() {
  21340. /**
  21341. * `DataMap` internally uses a weak map
  21342. * to manage its data.
  21343. *
  21344. * @type {WeakMap<Object, Object>}
  21345. */
  21346. this.data = new WeakMap();
  21347. }
  21348. /**
  21349. * Returns the dictionary for the given object.
  21350. *
  21351. * @param {Object} object - The object.
  21352. * @return {Object} The dictionary.
  21353. */
  21354. get( object ) {
  21355. let map = this.data.get( object );
  21356. if ( map === undefined ) {
  21357. map = {};
  21358. this.data.set( object, map );
  21359. }
  21360. return map;
  21361. }
  21362. /**
  21363. * Deletes the dictionary for the given object.
  21364. *
  21365. * @param {Object} object - The object.
  21366. * @return {?Object} The deleted dictionary.
  21367. */
  21368. delete( object ) {
  21369. let map = null;
  21370. if ( this.data.has( object ) ) {
  21371. map = this.data.get( object );
  21372. this.data.delete( object );
  21373. }
  21374. return map;
  21375. }
  21376. /**
  21377. * Returns `true` if the given object has a dictionary defined.
  21378. *
  21379. * @param {Object} object - The object to test.
  21380. * @return {boolean} Whether a dictionary is defined or not.
  21381. */
  21382. has( object ) {
  21383. return this.data.has( object );
  21384. }
  21385. /**
  21386. * Frees internal resources.
  21387. */
  21388. dispose() {
  21389. this.data = new WeakMap();
  21390. }
  21391. }
  21392. const AttributeType = {
  21393. VERTEX: 1,
  21394. INDEX: 2,
  21395. STORAGE: 3,
  21396. INDIRECT: 4
  21397. };
  21398. // size of a chunk in bytes (STD140 layout)
  21399. const GPU_CHUNK_BYTES = 16;
  21400. // @TODO: Move to src/constants.js
  21401. const BlendColorFactor = 211;
  21402. const OneMinusBlendColorFactor = 212;
  21403. /**
  21404. * This renderer module manages geometry attributes.
  21405. *
  21406. * @private
  21407. * @augments DataMap
  21408. */
  21409. class Attributes extends DataMap {
  21410. /**
  21411. * Constructs a new attribute management component.
  21412. *
  21413. * @param {Backend} backend - The renderer's backend.
  21414. */
  21415. constructor( backend ) {
  21416. super();
  21417. /**
  21418. * The renderer's backend.
  21419. *
  21420. * @type {Backend}
  21421. */
  21422. this.backend = backend;
  21423. }
  21424. /**
  21425. * Deletes the data for the given attribute.
  21426. *
  21427. * @param {BufferAttribute} attribute - The attribute.
  21428. * @return {?Object} The deleted attribute data.
  21429. */
  21430. delete( attribute ) {
  21431. const attributeData = super.delete( attribute );
  21432. if ( attributeData !== null ) {
  21433. this.backend.destroyAttribute( attribute );
  21434. }
  21435. return attributeData;
  21436. }
  21437. /**
  21438. * Updates the given attribute. This method creates attribute buffers
  21439. * for new attributes and updates data for existing ones.
  21440. *
  21441. * @param {BufferAttribute} attribute - The attribute to update.
  21442. * @param {number} type - The attribute type.
  21443. */
  21444. update( attribute, type ) {
  21445. const data = this.get( attribute );
  21446. if ( data.version === undefined ) {
  21447. if ( type === AttributeType.VERTEX ) {
  21448. this.backend.createAttribute( attribute );
  21449. } else if ( type === AttributeType.INDEX ) {
  21450. this.backend.createIndexAttribute( attribute );
  21451. } else if ( type === AttributeType.STORAGE ) {
  21452. this.backend.createStorageAttribute( attribute );
  21453. } else if ( type === AttributeType.INDIRECT ) {
  21454. this.backend.createIndirectStorageAttribute( attribute );
  21455. }
  21456. data.version = this._getBufferAttribute( attribute ).version;
  21457. } else {
  21458. const bufferAttribute = this._getBufferAttribute( attribute );
  21459. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21460. this.backend.updateAttribute( attribute );
  21461. data.version = bufferAttribute.version;
  21462. }
  21463. }
  21464. }
  21465. /**
  21466. * Utility method for handling interleaved buffer attributes correctly.
  21467. * To process them, their `InterleavedBuffer` is returned.
  21468. *
  21469. * @param {BufferAttribute} attribute - The attribute.
  21470. * @return {BufferAttribute|InterleavedBuffer}
  21471. */
  21472. _getBufferAttribute( attribute ) {
  21473. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21474. return attribute;
  21475. }
  21476. }
  21477. /**
  21478. * Returns the wireframe version for the given geometry.
  21479. *
  21480. * @private
  21481. * @function
  21482. * @param {BufferGeometry} geometry - The geometry.
  21483. * @return {number} The version.
  21484. */
  21485. function getWireframeVersion( geometry ) {
  21486. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21487. }
  21488. /**
  21489. * Returns the wireframe ID for the given geometry.
  21490. *
  21491. * @private
  21492. * @function
  21493. * @param {BufferGeometry} geometry - The geometry.
  21494. * @return {number} The ID.
  21495. */
  21496. function getWireframeId( geometry ) {
  21497. return ( geometry.index !== null ) ? geometry.index.id : geometry.attributes.position.id;
  21498. }
  21499. /**
  21500. * Returns a wireframe index attribute for the given geometry.
  21501. *
  21502. * @private
  21503. * @function
  21504. * @param {BufferGeometry} geometry - The geometry.
  21505. * @return {BufferAttribute} The wireframe index attribute.
  21506. */
  21507. function getWireframeIndex( geometry ) {
  21508. const indices = [];
  21509. const geometryIndex = geometry.index;
  21510. const geometryPosition = geometry.attributes.position;
  21511. if ( geometryIndex !== null ) {
  21512. const array = geometryIndex.array;
  21513. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21514. const a = array[ i + 0 ];
  21515. const b = array[ i + 1 ];
  21516. const c = array[ i + 2 ];
  21517. indices.push( a, b, b, c, c, a );
  21518. }
  21519. } else {
  21520. const array = geometryPosition.array;
  21521. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21522. const a = i + 0;
  21523. const b = i + 1;
  21524. const c = i + 2;
  21525. indices.push( a, b, b, c, c, a );
  21526. }
  21527. }
  21528. const attribute = new ( geometryPosition.count >= 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21529. attribute.version = getWireframeVersion( geometry );
  21530. attribute.__id = getWireframeId( geometry );
  21531. return attribute;
  21532. }
  21533. /**
  21534. * This renderer module manages geometries.
  21535. *
  21536. * @private
  21537. * @augments DataMap
  21538. */
  21539. class Geometries extends DataMap {
  21540. /**
  21541. * Constructs a new geometry management component.
  21542. *
  21543. * @param {Attributes} attributes - Renderer component for managing attributes.
  21544. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21545. */
  21546. constructor( attributes, info ) {
  21547. super();
  21548. /**
  21549. * Renderer component for managing attributes.
  21550. *
  21551. * @type {Attributes}
  21552. */
  21553. this.attributes = attributes;
  21554. /**
  21555. * Renderer component for managing metrics and monitoring data.
  21556. *
  21557. * @type {Info}
  21558. */
  21559. this.info = info;
  21560. /**
  21561. * Weak Map for managing attributes for wireframe rendering.
  21562. *
  21563. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  21564. */
  21565. this.wireframes = new WeakMap();
  21566. /**
  21567. * This Weak Map is used to make sure buffer attributes are
  21568. * updated only once per render call.
  21569. *
  21570. * @type {WeakMap<BufferAttribute,number>}
  21571. */
  21572. this.attributeCall = new WeakMap();
  21573. /**
  21574. * Stores the event listeners attached to geometries.
  21575. *
  21576. * @private
  21577. * @type {Map<BufferGeometry,Function>}
  21578. */
  21579. this._geometryDisposeListeners = new Map();
  21580. }
  21581. /**
  21582. * Returns `true` if the given render object has an initialized geometry.
  21583. *
  21584. * @param {RenderObject} renderObject - The render object.
  21585. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  21586. */
  21587. has( renderObject ) {
  21588. const geometry = renderObject.geometry;
  21589. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21590. }
  21591. /**
  21592. * Prepares the geometry of the given render object for rendering.
  21593. *
  21594. * @param {RenderObject} renderObject - The render object.
  21595. */
  21596. updateForRender( renderObject ) {
  21597. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21598. this.updateAttributes( renderObject );
  21599. }
  21600. /**
  21601. * Initializes the geometry of the given render object.
  21602. *
  21603. * @param {RenderObject} renderObject - The render object.
  21604. */
  21605. initGeometry( renderObject ) {
  21606. const geometry = renderObject.geometry;
  21607. const geometryData = this.get( geometry );
  21608. geometryData.initialized = true;
  21609. this.info.memory.geometries ++;
  21610. const onDispose = () => {
  21611. this.info.memory.geometries --;
  21612. const index = geometry.index;
  21613. const geometryAttributes = renderObject.getAttributes();
  21614. if ( index !== null ) {
  21615. this.attributes.delete( index );
  21616. }
  21617. for ( const geometryAttribute of geometryAttributes ) {
  21618. this.attributes.delete( geometryAttribute );
  21619. }
  21620. const wireframeAttribute = this.wireframes.get( geometry );
  21621. if ( wireframeAttribute !== undefined ) {
  21622. this.attributes.delete( wireframeAttribute );
  21623. }
  21624. geometry.removeEventListener( 'dispose', onDispose );
  21625. this._geometryDisposeListeners.delete( geometry );
  21626. };
  21627. geometry.addEventListener( 'dispose', onDispose );
  21628. // see #31798 why tracking separate remove listeners is required right now
  21629. // TODO: Re-evaluate how onDispose() is managed in this component
  21630. this._geometryDisposeListeners.set( geometry, onDispose );
  21631. }
  21632. /**
  21633. * Updates the geometry attributes of the given render object.
  21634. *
  21635. * @param {RenderObject} renderObject - The render object.
  21636. */
  21637. updateAttributes( renderObject ) {
  21638. // attributes
  21639. const attributes = renderObject.getAttributes();
  21640. for ( const attribute of attributes ) {
  21641. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21642. this.updateAttribute( attribute, AttributeType.STORAGE );
  21643. } else {
  21644. this.updateAttribute( attribute, AttributeType.VERTEX );
  21645. }
  21646. }
  21647. // indexes
  21648. const index = this.getIndex( renderObject );
  21649. if ( index !== null ) {
  21650. this.updateAttribute( index, AttributeType.INDEX );
  21651. }
  21652. // indirect
  21653. const indirect = renderObject.geometry.indirect;
  21654. if ( indirect !== null ) {
  21655. this.updateAttribute( indirect, AttributeType.INDIRECT );
  21656. }
  21657. }
  21658. /**
  21659. * Updates the given attribute.
  21660. *
  21661. * @param {BufferAttribute} attribute - The attribute to update.
  21662. * @param {number} type - The attribute type.
  21663. */
  21664. updateAttribute( attribute, type ) {
  21665. const callId = this.info.render.calls;
  21666. if ( ! attribute.isInterleavedBufferAttribute ) {
  21667. if ( this.attributeCall.get( attribute ) !== callId ) {
  21668. this.attributes.update( attribute, type );
  21669. this.attributeCall.set( attribute, callId );
  21670. }
  21671. } else {
  21672. if ( this.attributeCall.get( attribute ) === undefined ) {
  21673. this.attributes.update( attribute, type );
  21674. this.attributeCall.set( attribute, callId );
  21675. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21676. this.attributes.update( attribute, type );
  21677. this.attributeCall.set( attribute.data, callId );
  21678. this.attributeCall.set( attribute, callId );
  21679. }
  21680. }
  21681. }
  21682. /**
  21683. * Returns the indirect buffer attribute of the given render object.
  21684. *
  21685. * @param {RenderObject} renderObject - The render object.
  21686. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21687. */
  21688. getIndirect( renderObject ) {
  21689. return renderObject.geometry.indirect;
  21690. }
  21691. /**
  21692. * Returns the byte offset into the indirect attribute buffer of the given render object.
  21693. *
  21694. * @param {RenderObject} renderObject - The render object.
  21695. * @return {number} The byte offset into the indirect attribute buffer.
  21696. */
  21697. getIndirectOffset( renderObject ) {
  21698. return renderObject.geometry.indirectOffset;
  21699. }
  21700. /**
  21701. * Returns the index of the given render object's geometry. This is implemented
  21702. * in a method to return a wireframe index if necessary.
  21703. *
  21704. * @param {RenderObject} renderObject - The render object.
  21705. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21706. */
  21707. getIndex( renderObject ) {
  21708. const { geometry, material } = renderObject;
  21709. let index = geometry.index;
  21710. if ( material.wireframe === true ) {
  21711. const wireframes = this.wireframes;
  21712. let wireframeAttribute = wireframes.get( geometry );
  21713. if ( wireframeAttribute === undefined ) {
  21714. wireframeAttribute = getWireframeIndex( geometry );
  21715. wireframes.set( geometry, wireframeAttribute );
  21716. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) || wireframeAttribute.__id !== getWireframeId( geometry ) ) {
  21717. this.attributes.delete( wireframeAttribute );
  21718. wireframeAttribute = getWireframeIndex( geometry );
  21719. wireframes.set( geometry, wireframeAttribute );
  21720. }
  21721. index = wireframeAttribute;
  21722. }
  21723. return index;
  21724. }
  21725. dispose() {
  21726. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  21727. geometry.removeEventListener( 'dispose', onDispose );
  21728. }
  21729. this._geometryDisposeListeners.clear();
  21730. }
  21731. }
  21732. /**
  21733. * This renderer module provides a series of statistical information
  21734. * about the GPU memory and the rendering process. Useful for debugging
  21735. * and monitoring.
  21736. */
  21737. class Info {
  21738. /**
  21739. * Constructs a new info component.
  21740. */
  21741. constructor() {
  21742. /**
  21743. * Whether frame related metrics should automatically
  21744. * be resetted or not. This property should be set to `false`
  21745. * by apps which manage their own animation loop. They must
  21746. * then call `renderer.info.reset()` once per frame manually.
  21747. *
  21748. * @type {boolean}
  21749. * @default true
  21750. */
  21751. this.autoReset = true;
  21752. /**
  21753. * The current frame ID. This ID is managed
  21754. * by `NodeFrame`.
  21755. *
  21756. * @type {number}
  21757. * @readonly
  21758. * @default 0
  21759. */
  21760. this.frame = 0;
  21761. /**
  21762. * The number of render calls since the
  21763. * app has been started.
  21764. *
  21765. * @type {number}
  21766. * @readonly
  21767. * @default 0
  21768. */
  21769. this.calls = 0;
  21770. /**
  21771. * Render related metrics.
  21772. *
  21773. * @type {Object}
  21774. * @readonly
  21775. * @property {number} calls - The number of render calls since the app has been started.
  21776. * @property {number} frameCalls - The number of render calls of the current frame.
  21777. * @property {number} drawCalls - The number of draw calls of the current frame.
  21778. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  21779. * @property {number} points - The number of rendered point primitives of the current frame.
  21780. * @property {number} lines - The number of rendered line primitives of the current frame.
  21781. * @property {number} timestamp - The timestamp of the frame.
  21782. */
  21783. this.render = {
  21784. calls: 0,
  21785. frameCalls: 0,
  21786. drawCalls: 0,
  21787. triangles: 0,
  21788. points: 0,
  21789. lines: 0,
  21790. timestamp: 0,
  21791. };
  21792. /**
  21793. * Compute related metrics.
  21794. *
  21795. * @type {Object}
  21796. * @readonly
  21797. * @property {number} calls - The number of compute calls since the app has been started.
  21798. * @property {number} frameCalls - The number of compute calls of the current frame.
  21799. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  21800. */
  21801. this.compute = {
  21802. calls: 0,
  21803. frameCalls: 0,
  21804. timestamp: 0
  21805. };
  21806. /**
  21807. * Memory related metrics.
  21808. *
  21809. * @type {Object}
  21810. * @readonly
  21811. * @property {number} geometries - The number of active geometries.
  21812. * @property {number} frameCalls - The number of active textures.
  21813. */
  21814. this.memory = {
  21815. geometries: 0,
  21816. textures: 0
  21817. };
  21818. }
  21819. /**
  21820. * This method should be executed per draw call and updates the corresponding metrics.
  21821. *
  21822. * @param {Object3D} object - The 3D object that is going to be rendered.
  21823. * @param {number} count - The vertex or index count.
  21824. * @param {number} instanceCount - The instance count.
  21825. */
  21826. update( object, count, instanceCount ) {
  21827. this.render.drawCalls ++;
  21828. if ( object.isMesh || object.isSprite ) {
  21829. this.render.triangles += instanceCount * ( count / 3 );
  21830. } else if ( object.isPoints ) {
  21831. this.render.points += instanceCount * count;
  21832. } else if ( object.isLineSegments ) {
  21833. this.render.lines += instanceCount * ( count / 2 );
  21834. } else if ( object.isLine ) {
  21835. this.render.lines += instanceCount * ( count - 1 );
  21836. } else {
  21837. error( 'WebGPUInfo: Unknown object type.' );
  21838. }
  21839. }
  21840. /**
  21841. * Resets frame related metrics.
  21842. */
  21843. reset() {
  21844. this.render.drawCalls = 0;
  21845. this.render.frameCalls = 0;
  21846. this.compute.frameCalls = 0;
  21847. this.render.triangles = 0;
  21848. this.render.points = 0;
  21849. this.render.lines = 0;
  21850. }
  21851. /**
  21852. * Performs a complete reset of the object.
  21853. */
  21854. dispose() {
  21855. this.reset();
  21856. this.calls = 0;
  21857. this.render.calls = 0;
  21858. this.compute.calls = 0;
  21859. this.render.timestamp = 0;
  21860. this.compute.timestamp = 0;
  21861. this.memory.geometries = 0;
  21862. this.memory.textures = 0;
  21863. }
  21864. }
  21865. /**
  21866. * Abstract class for representing pipelines.
  21867. *
  21868. * @private
  21869. * @abstract
  21870. */
  21871. class Pipeline {
  21872. /**
  21873. * Constructs a new pipeline.
  21874. *
  21875. * @param {string} cacheKey - The pipeline's cache key.
  21876. */
  21877. constructor( cacheKey ) {
  21878. /**
  21879. * The pipeline's cache key.
  21880. *
  21881. * @type {string}
  21882. */
  21883. this.cacheKey = cacheKey;
  21884. /**
  21885. * How often the pipeline is currently in use.
  21886. *
  21887. * @type {number}
  21888. * @default 0
  21889. */
  21890. this.usedTimes = 0;
  21891. }
  21892. }
  21893. /**
  21894. * Class for representing render pipelines.
  21895. *
  21896. * @private
  21897. * @augments Pipeline
  21898. */
  21899. class RenderObjectPipeline extends Pipeline {
  21900. /**
  21901. * Constructs a new render object pipeline.
  21902. *
  21903. * @param {string} cacheKey - The pipeline's cache key.
  21904. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  21905. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  21906. */
  21907. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21908. super( cacheKey );
  21909. /**
  21910. * The pipeline's vertex shader.
  21911. *
  21912. * @type {ProgrammableStage}
  21913. */
  21914. this.vertexProgram = vertexProgram;
  21915. /**
  21916. * The pipeline's fragment shader.
  21917. *
  21918. * @type {ProgrammableStage}
  21919. */
  21920. this.fragmentProgram = fragmentProgram;
  21921. }
  21922. }
  21923. /**
  21924. * Class for representing compute pipelines.
  21925. *
  21926. * @private
  21927. * @augments Pipeline
  21928. */
  21929. class ComputePipeline extends Pipeline {
  21930. /**
  21931. * Constructs a new render pipeline.
  21932. *
  21933. * @param {string} cacheKey - The pipeline's cache key.
  21934. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  21935. */
  21936. constructor( cacheKey, computeProgram ) {
  21937. super( cacheKey );
  21938. /**
  21939. * The pipeline's compute shader.
  21940. *
  21941. * @type {ProgrammableStage}
  21942. */
  21943. this.computeProgram = computeProgram;
  21944. /**
  21945. * This flag can be used for type testing.
  21946. *
  21947. * @type {boolean}
  21948. * @readonly
  21949. * @default true
  21950. */
  21951. this.isComputePipeline = true;
  21952. }
  21953. }
  21954. let _id$9 = 0;
  21955. /**
  21956. * Class for representing programmable stages which are vertex,
  21957. * fragment or compute shaders. Unlike fixed-function states (like blending),
  21958. * they represent the programmable part of a pipeline.
  21959. *
  21960. * @private
  21961. */
  21962. class ProgrammableStage {
  21963. /**
  21964. * Constructs a new programmable stage.
  21965. *
  21966. * @param {string} code - The shader code.
  21967. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  21968. * @param {string} name - The name of the shader.
  21969. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21970. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21971. */
  21972. constructor( code, stage, name, transforms = null, attributes = null ) {
  21973. /**
  21974. * The id of the programmable stage.
  21975. *
  21976. * @type {number}
  21977. */
  21978. this.id = _id$9 ++;
  21979. /**
  21980. * The shader code.
  21981. *
  21982. * @type {string}
  21983. */
  21984. this.code = code;
  21985. /**
  21986. * The type of stage.
  21987. *
  21988. * @type {string}
  21989. */
  21990. this.stage = stage;
  21991. /**
  21992. * The name of the stage.
  21993. * This is used for debugging purposes.
  21994. *
  21995. * @type {string}
  21996. */
  21997. this.name = name;
  21998. /**
  21999. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22000. *
  22001. * @type {?Array<Object>}
  22002. */
  22003. this.transforms = transforms;
  22004. /**
  22005. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  22006. *
  22007. * @type {?Array<Object>}
  22008. */
  22009. this.attributes = attributes;
  22010. /**
  22011. * How often the programmable stage is currently in use.
  22012. *
  22013. * @type {number}
  22014. * @default 0
  22015. */
  22016. this.usedTimes = 0;
  22017. }
  22018. }
  22019. /**
  22020. * This renderer module manages the pipelines of the renderer.
  22021. *
  22022. * @private
  22023. * @augments DataMap
  22024. */
  22025. class Pipelines extends DataMap {
  22026. /**
  22027. * Constructs a new pipeline management component.
  22028. *
  22029. * @param {Backend} backend - The renderer's backend.
  22030. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  22031. */
  22032. constructor( backend, nodes ) {
  22033. super();
  22034. /**
  22035. * The renderer's backend.
  22036. *
  22037. * @type {Backend}
  22038. */
  22039. this.backend = backend;
  22040. /**
  22041. * Renderer component for managing nodes related logic.
  22042. *
  22043. * @type {Nodes}
  22044. */
  22045. this.nodes = nodes;
  22046. /**
  22047. * A references to the bindings management component.
  22048. * This reference will be set inside the `Bindings`
  22049. * constructor.
  22050. *
  22051. * @type {?Bindings}
  22052. * @default null
  22053. */
  22054. this.bindings = null;
  22055. /**
  22056. * Internal cache for maintaining pipelines.
  22057. * The key of the map is a cache key, the value the pipeline.
  22058. *
  22059. * @type {Map<string,Pipeline>}
  22060. */
  22061. this.caches = new Map();
  22062. /**
  22063. * This dictionary maintains for each shader stage type (vertex,
  22064. * fragment and compute) the programmable stage objects which
  22065. * represent the actual shader code.
  22066. *
  22067. * @type {Object<string,Map<string, ProgrammableStage>>}
  22068. */
  22069. this.programs = {
  22070. vertex: new Map(),
  22071. fragment: new Map(),
  22072. compute: new Map()
  22073. };
  22074. }
  22075. /**
  22076. * Returns a compute pipeline for the given compute node.
  22077. *
  22078. * @param {Node} computeNode - The compute node.
  22079. * @param {Array<BindGroup>} bindings - The bindings.
  22080. * @return {ComputePipeline} The compute pipeline.
  22081. */
  22082. getForCompute( computeNode, bindings ) {
  22083. const { backend } = this;
  22084. const data = this.get( computeNode );
  22085. if ( this._needsComputeUpdate( computeNode ) ) {
  22086. const previousPipeline = data.pipeline;
  22087. if ( previousPipeline ) {
  22088. previousPipeline.usedTimes --;
  22089. previousPipeline.computeProgram.usedTimes --;
  22090. }
  22091. // get shader
  22092. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  22093. // programmable stage
  22094. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  22095. if ( stageCompute === undefined ) {
  22096. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  22097. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  22098. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  22099. backend.createProgram( stageCompute );
  22100. }
  22101. // determine compute pipeline
  22102. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  22103. let pipeline = this.caches.get( cacheKey );
  22104. if ( pipeline === undefined ) {
  22105. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22106. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  22107. }
  22108. // keep track of all used times
  22109. pipeline.usedTimes ++;
  22110. stageCompute.usedTimes ++;
  22111. //
  22112. data.version = computeNode.version;
  22113. data.pipeline = pipeline;
  22114. }
  22115. return data.pipeline;
  22116. }
  22117. /**
  22118. * Returns a render pipeline for the given render object.
  22119. *
  22120. * @param {RenderObject} renderObject - The render object.
  22121. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  22122. * @return {RenderObjectPipeline} The render pipeline.
  22123. */
  22124. getForRender( renderObject, promises = null ) {
  22125. const { backend } = this;
  22126. const data = this.get( renderObject );
  22127. if ( this._needsRenderUpdate( renderObject ) ) {
  22128. const previousPipeline = data.pipeline;
  22129. if ( previousPipeline ) {
  22130. previousPipeline.usedTimes --;
  22131. previousPipeline.vertexProgram.usedTimes --;
  22132. previousPipeline.fragmentProgram.usedTimes --;
  22133. }
  22134. // get shader
  22135. const nodeBuilderState = renderObject.getNodeBuilderState();
  22136. const name = renderObject.material ? renderObject.material.name : '';
  22137. // programmable stages
  22138. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  22139. if ( stageVertex === undefined ) {
  22140. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  22141. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  22142. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  22143. backend.createProgram( stageVertex );
  22144. }
  22145. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  22146. if ( stageFragment === undefined ) {
  22147. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  22148. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  22149. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  22150. backend.createProgram( stageFragment );
  22151. }
  22152. // determine render pipeline
  22153. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22154. let pipeline = this.caches.get( cacheKey );
  22155. if ( pipeline === undefined ) {
  22156. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22157. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  22158. } else {
  22159. renderObject.pipeline = pipeline;
  22160. }
  22161. // keep track of all used times
  22162. pipeline.usedTimes ++;
  22163. stageVertex.usedTimes ++;
  22164. stageFragment.usedTimes ++;
  22165. //
  22166. data.pipeline = pipeline;
  22167. }
  22168. return data.pipeline;
  22169. }
  22170. /**
  22171. * Deletes the pipeline for the given render object.
  22172. *
  22173. * @param {RenderObject} object - The render object.
  22174. * @return {?Object} The deleted dictionary.
  22175. */
  22176. delete( object ) {
  22177. const pipeline = this.get( object ).pipeline;
  22178. if ( pipeline ) {
  22179. // pipeline
  22180. pipeline.usedTimes --;
  22181. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  22182. // programs
  22183. if ( pipeline.isComputePipeline ) {
  22184. pipeline.computeProgram.usedTimes --;
  22185. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  22186. } else {
  22187. pipeline.fragmentProgram.usedTimes --;
  22188. pipeline.vertexProgram.usedTimes --;
  22189. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  22190. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  22191. }
  22192. }
  22193. return super.delete( object );
  22194. }
  22195. /**
  22196. * Frees internal resources.
  22197. */
  22198. dispose() {
  22199. super.dispose();
  22200. this.caches = new Map();
  22201. this.programs = {
  22202. vertex: new Map(),
  22203. fragment: new Map(),
  22204. compute: new Map()
  22205. };
  22206. }
  22207. /**
  22208. * Updates the pipeline for the given render object.
  22209. *
  22210. * @param {RenderObject} renderObject - The render object.
  22211. */
  22212. updateForRender( renderObject ) {
  22213. this.getForRender( renderObject );
  22214. }
  22215. /**
  22216. * Returns a compute pipeline for the given parameters.
  22217. *
  22218. * @private
  22219. * @param {Node} computeNode - The compute node.
  22220. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  22221. * @param {string} cacheKey - The cache key.
  22222. * @param {Array<BindGroup>} bindings - The bindings.
  22223. * @return {ComputePipeline} The compute pipeline.
  22224. */
  22225. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  22226. // check for existing pipeline
  22227. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  22228. let pipeline = this.caches.get( cacheKey );
  22229. if ( pipeline === undefined ) {
  22230. pipeline = new ComputePipeline( cacheKey, stageCompute );
  22231. this.caches.set( cacheKey, pipeline );
  22232. this.backend.createComputePipeline( pipeline, bindings );
  22233. }
  22234. return pipeline;
  22235. }
  22236. /**
  22237. * Returns a render pipeline for the given parameters.
  22238. *
  22239. * @private
  22240. * @param {RenderObject} renderObject - The render object.
  22241. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22242. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22243. * @param {string} cacheKey - The cache key.
  22244. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  22245. * @return {RenderObjectPipeline} The render pipeline.
  22246. */
  22247. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22248. // check for existing pipeline
  22249. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22250. let pipeline = this.caches.get( cacheKey );
  22251. if ( pipeline === undefined ) {
  22252. pipeline = new RenderObjectPipeline( cacheKey, stageVertex, stageFragment );
  22253. this.caches.set( cacheKey, pipeline );
  22254. renderObject.pipeline = pipeline;
  22255. // The `promises` array is `null` by default and only set to an empty array when
  22256. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  22257. // pending promises that resolve when the render pipelines are ready for rendering.
  22258. this.backend.createRenderPipeline( renderObject, promises );
  22259. }
  22260. return pipeline;
  22261. }
  22262. /**
  22263. * Computes a cache key representing a compute pipeline.
  22264. *
  22265. * @private
  22266. * @param {Node} computeNode - The compute node.
  22267. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  22268. * @return {string} The cache key.
  22269. */
  22270. _getComputeCacheKey( computeNode, stageCompute ) {
  22271. return computeNode.id + ',' + stageCompute.id;
  22272. }
  22273. /**
  22274. * Computes a cache key representing a render pipeline.
  22275. *
  22276. * @private
  22277. * @param {RenderObject} renderObject - The render object.
  22278. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22279. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22280. * @return {string} The cache key.
  22281. */
  22282. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22283. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22284. }
  22285. /**
  22286. * Releases the given pipeline.
  22287. *
  22288. * @private
  22289. * @param {Pipeline} pipeline - The pipeline to release.
  22290. */
  22291. _releasePipeline( pipeline ) {
  22292. this.caches.delete( pipeline.cacheKey );
  22293. }
  22294. /**
  22295. * Releases the shader program.
  22296. *
  22297. * @private
  22298. * @param {Object} program - The shader program to release.
  22299. */
  22300. _releaseProgram( program ) {
  22301. const code = program.code;
  22302. const stage = program.stage;
  22303. this.programs[ stage ].delete( code );
  22304. }
  22305. /**
  22306. * Returns `true` if the compute pipeline for the given compute node requires an update.
  22307. *
  22308. * @private
  22309. * @param {Node} computeNode - The compute node.
  22310. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  22311. */
  22312. _needsComputeUpdate( computeNode ) {
  22313. const data = this.get( computeNode );
  22314. return data.pipeline === undefined || data.version !== computeNode.version;
  22315. }
  22316. /**
  22317. * Returns `true` if the render pipeline for the given render object requires an update.
  22318. *
  22319. * @private
  22320. * @param {RenderObject} renderObject - The render object.
  22321. * @return {boolean} Whether the render object for the given render object requires an update or not.
  22322. */
  22323. _needsRenderUpdate( renderObject ) {
  22324. const data = this.get( renderObject );
  22325. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22326. }
  22327. }
  22328. /**
  22329. * This renderer module manages the bindings of the renderer.
  22330. *
  22331. * @private
  22332. * @augments DataMap
  22333. */
  22334. class Bindings extends DataMap {
  22335. /**
  22336. * Constructs a new bindings management component.
  22337. *
  22338. * @param {Backend} backend - The renderer's backend.
  22339. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  22340. * @param {Textures} textures - Renderer component for managing textures.
  22341. * @param {Attributes} attributes - Renderer component for managing attributes.
  22342. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  22343. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22344. */
  22345. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22346. super();
  22347. /**
  22348. * The renderer's backend.
  22349. *
  22350. * @type {Backend}
  22351. */
  22352. this.backend = backend;
  22353. /**
  22354. * Renderer component for managing textures.
  22355. *
  22356. * @type {Textures}
  22357. */
  22358. this.textures = textures;
  22359. /**
  22360. * Renderer component for managing pipelines.
  22361. *
  22362. * @type {Pipelines}
  22363. */
  22364. this.pipelines = pipelines;
  22365. /**
  22366. * Renderer component for managing attributes.
  22367. *
  22368. * @type {Attributes}
  22369. */
  22370. this.attributes = attributes;
  22371. /**
  22372. * Renderer component for managing nodes related logic.
  22373. *
  22374. * @type {Nodes}
  22375. */
  22376. this.nodes = nodes;
  22377. /**
  22378. * Renderer component for managing metrics and monitoring data.
  22379. *
  22380. * @type {Info}
  22381. */
  22382. this.info = info;
  22383. this.pipelines.bindings = this; // assign bindings to pipelines
  22384. }
  22385. /**
  22386. * Returns the bind groups for the given render object.
  22387. *
  22388. * @param {RenderObject} renderObject - The render object.
  22389. * @return {Array<BindGroup>} The bind groups.
  22390. */
  22391. getForRender( renderObject ) {
  22392. const bindings = renderObject.getBindings();
  22393. for ( const bindGroup of bindings ) {
  22394. const groupData = this.get( bindGroup );
  22395. if ( groupData.bindGroup === undefined ) {
  22396. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22397. this._init( bindGroup );
  22398. this.backend.createBindings( bindGroup, bindings, 0 );
  22399. groupData.bindGroup = bindGroup;
  22400. }
  22401. }
  22402. return bindings;
  22403. }
  22404. /**
  22405. * Returns the bind groups for the given compute node.
  22406. *
  22407. * @param {Node} computeNode - The compute node.
  22408. * @return {Array<BindGroup>} The bind groups.
  22409. */
  22410. getForCompute( computeNode ) {
  22411. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22412. for ( const bindGroup of bindings ) {
  22413. const groupData = this.get( bindGroup );
  22414. if ( groupData.bindGroup === undefined ) {
  22415. this._init( bindGroup );
  22416. this.backend.createBindings( bindGroup, bindings, 0 );
  22417. groupData.bindGroup = bindGroup;
  22418. }
  22419. }
  22420. return bindings;
  22421. }
  22422. /**
  22423. * Updates the bindings for the given compute node.
  22424. *
  22425. * @param {Node} computeNode - The compute node.
  22426. */
  22427. updateForCompute( computeNode ) {
  22428. this._updateBindings( this.getForCompute( computeNode ) );
  22429. }
  22430. /**
  22431. * Updates the bindings for the given render object.
  22432. *
  22433. * @param {RenderObject} renderObject - The render object.
  22434. */
  22435. updateForRender( renderObject ) {
  22436. this._updateBindings( this.getForRender( renderObject ) );
  22437. }
  22438. /**
  22439. * Deletes the bindings for the given compute node.
  22440. *
  22441. * @param {Node} computeNode - The compute node.
  22442. */
  22443. deleteForCompute( computeNode ) {
  22444. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22445. for ( const bindGroup of bindings ) {
  22446. this.backend.deleteBindGroupData( bindGroup );
  22447. this.delete( bindGroup );
  22448. }
  22449. }
  22450. /**
  22451. * Deletes the bindings for the given renderObject node.
  22452. *
  22453. * @param {RenderObject} renderObject - The renderObject.
  22454. */
  22455. deleteForRender( renderObject ) {
  22456. const bindings = renderObject.getBindings();
  22457. for ( const bindGroup of bindings ) {
  22458. this.backend.deleteBindGroupData( bindGroup );
  22459. this.delete( bindGroup );
  22460. }
  22461. }
  22462. /**
  22463. * Updates the given array of bindings.
  22464. *
  22465. * @param {Array<BindGroup>} bindings - The bind groups.
  22466. */
  22467. _updateBindings( bindings ) {
  22468. for ( const bindGroup of bindings ) {
  22469. this._update( bindGroup, bindings );
  22470. }
  22471. }
  22472. /**
  22473. * Initializes the given bind group.
  22474. *
  22475. * @param {BindGroup} bindGroup - The bind group to initialize.
  22476. */
  22477. _init( bindGroup ) {
  22478. for ( const binding of bindGroup.bindings ) {
  22479. if ( binding.isSampledTexture ) {
  22480. this.textures.updateTexture( binding.texture );
  22481. } else if ( binding.isSampler ) {
  22482. this.textures.updateSampler( binding.texture );
  22483. } else if ( binding.isStorageBuffer ) {
  22484. const attribute = binding.attribute;
  22485. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22486. this.attributes.update( attribute, attributeType );
  22487. }
  22488. }
  22489. }
  22490. /**
  22491. * Updates the given bind group.
  22492. *
  22493. * @param {BindGroup} bindGroup - The bind group to update.
  22494. * @param {Array<BindGroup>} bindings - The bind groups.
  22495. */
  22496. _update( bindGroup, bindings ) {
  22497. const { backend } = this;
  22498. let needsBindingsUpdate = false;
  22499. let cacheBindings = true;
  22500. let cacheIndex = 0;
  22501. let version = 0;
  22502. // iterate over all bindings and check if buffer updates or a new binding group is required
  22503. for ( const binding of bindGroup.bindings ) {
  22504. const updatedGroup = this.nodes.updateGroup( binding );
  22505. // every uniforms group is a uniform buffer. So if no update is required,
  22506. // we move one with the next binding. Otherwise the next if block will update the group.
  22507. if ( updatedGroup === false ) continue;
  22508. //
  22509. if ( binding.isStorageBuffer ) {
  22510. const attribute = binding.attribute;
  22511. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22512. const bindingData = backend.get( binding );
  22513. this.attributes.update( attribute, attributeType );
  22514. if ( bindingData.attribute !== attribute ) {
  22515. bindingData.attribute = attribute;
  22516. needsBindingsUpdate = true;
  22517. }
  22518. }
  22519. if ( binding.isUniformBuffer ) {
  22520. const updated = binding.update();
  22521. if ( updated ) {
  22522. backend.updateBinding( binding );
  22523. }
  22524. } else if ( binding.isSampledTexture ) {
  22525. const updated = binding.update();
  22526. // get the texture data after the update, to sync the texture reference from node
  22527. const texture = binding.texture;
  22528. const texturesTextureData = this.textures.get( texture );
  22529. if ( updated ) {
  22530. // version: update the texture data or create a new one
  22531. this.textures.updateTexture( texture );
  22532. // generation: update the bindings if a new texture has been created
  22533. if ( binding.generation !== texturesTextureData.generation ) {
  22534. binding.generation = texturesTextureData.generation;
  22535. needsBindingsUpdate = true;
  22536. cacheBindings = false;
  22537. }
  22538. }
  22539. const textureData = backend.get( texture );
  22540. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  22541. cacheBindings = false;
  22542. } else {
  22543. cacheIndex = cacheIndex * 10 + texture.id;
  22544. version += texture.version;
  22545. }
  22546. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  22547. const textureData = this.get( texture );
  22548. if ( binding.store === true ) {
  22549. textureData.needsMipmap = true;
  22550. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22551. this.backend.generateMipmaps( texture );
  22552. textureData.needsMipmap = false;
  22553. }
  22554. }
  22555. } else if ( binding.isSampler ) {
  22556. const updated = binding.update();
  22557. if ( updated ) {
  22558. const samplerKey = this.textures.updateSampler( binding.texture );
  22559. if ( binding.samplerKey !== samplerKey ) {
  22560. binding.samplerKey = samplerKey;
  22561. needsBindingsUpdate = true;
  22562. cacheBindings = false;
  22563. }
  22564. }
  22565. }
  22566. if ( binding.isBuffer && binding.updateRanges.length > 0 ) {
  22567. binding.clearUpdateRanges();
  22568. }
  22569. }
  22570. if ( needsBindingsUpdate === true ) {
  22571. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  22572. }
  22573. }
  22574. }
  22575. /**
  22576. * Default sorting function for opaque render items.
  22577. *
  22578. * @private
  22579. * @function
  22580. * @param {Object} a - The first render item.
  22581. * @param {Object} b - The second render item.
  22582. * @return {number} A numeric value which defines the sort order.
  22583. */
  22584. function painterSortStable( a, b ) {
  22585. if ( a.groupOrder !== b.groupOrder ) {
  22586. return a.groupOrder - b.groupOrder;
  22587. } else if ( a.renderOrder !== b.renderOrder ) {
  22588. return a.renderOrder - b.renderOrder;
  22589. } else if ( a.z !== b.z ) {
  22590. return a.z - b.z;
  22591. } else {
  22592. return a.id - b.id;
  22593. }
  22594. }
  22595. /**
  22596. * Default sorting function for transparent render items.
  22597. *
  22598. * @private
  22599. * @function
  22600. * @param {Object} a - The first render item.
  22601. * @param {Object} b - The second render item.
  22602. * @return {number} A numeric value which defines the sort order.
  22603. */
  22604. function reversePainterSortStable( a, b ) {
  22605. if ( a.groupOrder !== b.groupOrder ) {
  22606. return a.groupOrder - b.groupOrder;
  22607. } else if ( a.renderOrder !== b.renderOrder ) {
  22608. return a.renderOrder - b.renderOrder;
  22609. } else if ( a.z !== b.z ) {
  22610. return b.z - a.z;
  22611. } else {
  22612. return a.id - b.id;
  22613. }
  22614. }
  22615. /**
  22616. * Returns `true` if the given transparent material requires a double pass.
  22617. *
  22618. * @private
  22619. * @function
  22620. * @param {Material} material - The transparent material.
  22621. * @return {boolean} Whether the given material requires a double pass or not.
  22622. */
  22623. function needsDoublePass( material ) {
  22624. const hasTransmission = material.transmission > 0 || ( material.transmissionNode && material.transmissionNode.isNode );
  22625. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  22626. }
  22627. /**
  22628. * When the renderer analyzes the scene at the beginning of a render call,
  22629. * it stores 3D object for further processing in render lists. Depending on the
  22630. * properties of a 3D objects (like their transformation or material state), the
  22631. * objects are maintained in ordered lists for the actual rendering.
  22632. *
  22633. * Render lists are unique per scene and camera combination.
  22634. *
  22635. * @private
  22636. * @augments Pipeline
  22637. */
  22638. class RenderList {
  22639. /**
  22640. * Constructs a render list.
  22641. *
  22642. * @param {Lighting} lighting - The lighting management component.
  22643. * @param {Scene} scene - The scene.
  22644. * @param {Camera} camera - The camera the scene is rendered with.
  22645. */
  22646. constructor( lighting, scene, camera ) {
  22647. /**
  22648. * 3D objects are transformed into render items and stored in this array.
  22649. *
  22650. * @type {Array<Object>}
  22651. */
  22652. this.renderItems = [];
  22653. /**
  22654. * The current render items index.
  22655. *
  22656. * @type {number}
  22657. * @default 0
  22658. */
  22659. this.renderItemsIndex = 0;
  22660. /**
  22661. * A list with opaque render items.
  22662. *
  22663. * @type {Array<Object>}
  22664. */
  22665. this.opaque = [];
  22666. /**
  22667. * A list with transparent render items which require
  22668. * double pass rendering (e.g. transmissive objects).
  22669. *
  22670. * @type {Array<Object>}
  22671. */
  22672. this.transparentDoublePass = [];
  22673. /**
  22674. * A list with transparent render items.
  22675. *
  22676. * @type {Array<Object>}
  22677. */
  22678. this.transparent = [];
  22679. /**
  22680. * A list with transparent render bundle data.
  22681. *
  22682. * @type {Array<Object>}
  22683. */
  22684. this.bundles = [];
  22685. /**
  22686. * The render list's lights node. This node is later
  22687. * relevant for the actual analytical light nodes which
  22688. * compute the scene's lighting in the shader.
  22689. *
  22690. * @type {LightsNode}
  22691. */
  22692. this.lightsNode = lighting.getNode( scene, camera );
  22693. /**
  22694. * The scene's lights stored in an array. This array
  22695. * is used to setup the lights node.
  22696. *
  22697. * @type {Array<Light>}
  22698. */
  22699. this.lightsArray = [];
  22700. /**
  22701. * The scene.
  22702. *
  22703. * @type {Scene}
  22704. */
  22705. this.scene = scene;
  22706. /**
  22707. * The camera the scene is rendered with.
  22708. *
  22709. * @type {Camera}
  22710. */
  22711. this.camera = camera;
  22712. /**
  22713. * How many objects perform occlusion query tests.
  22714. *
  22715. * @type {number}
  22716. * @default 0
  22717. */
  22718. this.occlusionQueryCount = 0;
  22719. }
  22720. /**
  22721. * This method is called right at the beginning of a render call
  22722. * before the scene is analyzed. It prepares the internal data
  22723. * structures for the upcoming render lists generation.
  22724. *
  22725. * @return {RenderList} A reference to this render list.
  22726. */
  22727. begin() {
  22728. this.renderItemsIndex = 0;
  22729. this.opaque.length = 0;
  22730. this.transparentDoublePass.length = 0;
  22731. this.transparent.length = 0;
  22732. this.bundles.length = 0;
  22733. this.lightsArray.length = 0;
  22734. this.occlusionQueryCount = 0;
  22735. return this;
  22736. }
  22737. /**
  22738. * Returns a render item for the giving render item state. The state is defined
  22739. * by a series of object-related parameters.
  22740. *
  22741. * The method avoids object creation by holding render items and reusing them in
  22742. * subsequent render calls (just with different property values).
  22743. *
  22744. * @param {Object3D} object - The 3D object.
  22745. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22746. * @param {Material} material - The 3D object's material.
  22747. * @param {number} groupOrder - The current group order.
  22748. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22749. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22750. * @param {ClippingContext} clippingContext - The current clipping context.
  22751. * @return {Object} The render item.
  22752. */
  22753. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22754. let renderItem = this.renderItems[ this.renderItemsIndex ];
  22755. if ( renderItem === undefined ) {
  22756. renderItem = {
  22757. id: object.id,
  22758. object: object,
  22759. geometry: geometry,
  22760. material: material,
  22761. groupOrder: groupOrder,
  22762. renderOrder: object.renderOrder,
  22763. z: z,
  22764. group: group,
  22765. clippingContext: clippingContext
  22766. };
  22767. this.renderItems[ this.renderItemsIndex ] = renderItem;
  22768. } else {
  22769. renderItem.id = object.id;
  22770. renderItem.object = object;
  22771. renderItem.geometry = geometry;
  22772. renderItem.material = material;
  22773. renderItem.groupOrder = groupOrder;
  22774. renderItem.renderOrder = object.renderOrder;
  22775. renderItem.z = z;
  22776. renderItem.group = group;
  22777. renderItem.clippingContext = clippingContext;
  22778. }
  22779. this.renderItemsIndex ++;
  22780. return renderItem;
  22781. }
  22782. /**
  22783. * Pushes the given object as a render item to the internal render lists.
  22784. * The selected lists depend on the object properties.
  22785. *
  22786. * @param {Object3D} object - The 3D object.
  22787. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22788. * @param {Material} material - The 3D object's material.
  22789. * @param {number} groupOrder - The current group order.
  22790. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22791. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22792. * @param {ClippingContext} clippingContext - The current clipping context.
  22793. */
  22794. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22795. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22796. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  22797. if ( material.transparent === true || material.transmission > 0 ||
  22798. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22799. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22800. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  22801. this.transparent.push( renderItem );
  22802. } else {
  22803. this.opaque.push( renderItem );
  22804. }
  22805. }
  22806. /**
  22807. * Inserts the given object as a render item at the start of the internal render lists.
  22808. * The selected lists depend on the object properties.
  22809. *
  22810. * @param {Object3D} object - The 3D object.
  22811. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22812. * @param {Material} material - The 3D object's material.
  22813. * @param {number} groupOrder - The current group order.
  22814. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22815. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22816. * @param {ClippingContext} clippingContext - The current clipping context.
  22817. */
  22818. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22819. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22820. if ( material.transparent === true || material.transmission > 0 ||
  22821. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22822. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22823. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  22824. this.transparent.unshift( renderItem );
  22825. } else {
  22826. this.opaque.unshift( renderItem );
  22827. }
  22828. }
  22829. /**
  22830. * Pushes render bundle group data into the render list.
  22831. *
  22832. * @param {Object} group - Bundle group data.
  22833. */
  22834. pushBundle( group ) {
  22835. this.bundles.push( group );
  22836. }
  22837. /**
  22838. * Pushes a light into the render list.
  22839. *
  22840. * @param {Light} light - The light.
  22841. */
  22842. pushLight( light ) {
  22843. this.lightsArray.push( light );
  22844. }
  22845. /**
  22846. * Sorts the internal render lists.
  22847. *
  22848. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  22849. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  22850. */
  22851. sort( customOpaqueSort, customTransparentSort ) {
  22852. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  22853. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  22854. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  22855. }
  22856. /**
  22857. * This method performs finalizing tasks right after the render lists
  22858. * have been generated.
  22859. */
  22860. finish() {
  22861. // update lights
  22862. this.lightsNode.setLights( this.lightsArray );
  22863. // Clear references from inactive renderItems in the list
  22864. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  22865. const renderItem = this.renderItems[ i ];
  22866. if ( renderItem.id === null ) break;
  22867. renderItem.id = null;
  22868. renderItem.object = null;
  22869. renderItem.geometry = null;
  22870. renderItem.material = null;
  22871. renderItem.groupOrder = null;
  22872. renderItem.renderOrder = null;
  22873. renderItem.z = null;
  22874. renderItem.group = null;
  22875. renderItem.clippingContext = null;
  22876. }
  22877. }
  22878. }
  22879. const _chainKeys$2 = [];
  22880. /**
  22881. * This renderer module manages the render lists which are unique
  22882. * per scene and camera combination.
  22883. *
  22884. * @private
  22885. */
  22886. class RenderLists {
  22887. /**
  22888. * Constructs a render lists management component.
  22889. *
  22890. * @param {Lighting} lighting - The lighting management component.
  22891. */
  22892. constructor( lighting ) {
  22893. /**
  22894. * The lighting management component.
  22895. *
  22896. * @type {Lighting}
  22897. */
  22898. this.lighting = lighting;
  22899. /**
  22900. * The internal chain map which holds the render lists.
  22901. *
  22902. * @type {ChainMap}
  22903. */
  22904. this.lists = new ChainMap();
  22905. }
  22906. /**
  22907. * Returns a render list for the given scene and camera.
  22908. *
  22909. * @param {Scene} scene - The scene.
  22910. * @param {Camera} camera - The camera.
  22911. * @return {RenderList} The render list.
  22912. */
  22913. get( scene, camera ) {
  22914. const lists = this.lists;
  22915. _chainKeys$2[ 0 ] = scene;
  22916. _chainKeys$2[ 1 ] = camera;
  22917. let list = lists.get( _chainKeys$2 );
  22918. if ( list === undefined ) {
  22919. list = new RenderList( this.lighting, scene, camera );
  22920. lists.set( _chainKeys$2, list );
  22921. }
  22922. _chainKeys$2[ 0 ] = null;
  22923. _chainKeys$2[ 1 ] = null;
  22924. return list;
  22925. }
  22926. /**
  22927. * Frees all internal resources.
  22928. */
  22929. dispose() {
  22930. this.lists = new ChainMap();
  22931. }
  22932. }
  22933. let _id$8 = 0;
  22934. /**
  22935. * Any render or compute command is executed in a specific context that defines
  22936. * the state of the renderer and its backend. Typical examples for such context
  22937. * data are the current clear values or data from the active framebuffer. This
  22938. * module is used to represent these contexts as objects.
  22939. *
  22940. * @private
  22941. */
  22942. class RenderContext {
  22943. /**
  22944. * Constructs a new render context.
  22945. */
  22946. constructor() {
  22947. /**
  22948. * The context's ID.
  22949. *
  22950. * @type {number}
  22951. */
  22952. this.id = _id$8 ++;
  22953. /**
  22954. * The MRT configuration.
  22955. *
  22956. * @type {?MRTNode}
  22957. * @default null
  22958. */
  22959. this.mrt = null;
  22960. /**
  22961. * Whether the current active framebuffer has a color attachment.
  22962. *
  22963. * @type {boolean}
  22964. * @default true
  22965. */
  22966. this.color = true;
  22967. /**
  22968. * Whether the color attachment should be cleared or not.
  22969. *
  22970. * @type {boolean}
  22971. * @default true
  22972. */
  22973. this.clearColor = true;
  22974. /**
  22975. * The clear color value.
  22976. *
  22977. * @type {Object}
  22978. * @default true
  22979. */
  22980. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  22981. /**
  22982. * Whether the current active framebuffer has a depth attachment.
  22983. *
  22984. * @type {boolean}
  22985. * @default true
  22986. */
  22987. this.depth = true;
  22988. /**
  22989. * Whether the depth attachment should be cleared or not.
  22990. *
  22991. * @type {boolean}
  22992. * @default true
  22993. */
  22994. this.clearDepth = true;
  22995. /**
  22996. * The clear depth value.
  22997. *
  22998. * @type {number}
  22999. * @default 1
  23000. */
  23001. this.clearDepthValue = 1;
  23002. /**
  23003. * Whether the current active framebuffer has a stencil attachment.
  23004. *
  23005. * @type {boolean}
  23006. * @default false
  23007. */
  23008. this.stencil = false;
  23009. /**
  23010. * Whether the stencil attachment should be cleared or not.
  23011. *
  23012. * @type {boolean}
  23013. * @default true
  23014. */
  23015. this.clearStencil = true;
  23016. /**
  23017. * The clear stencil value.
  23018. *
  23019. * @type {number}
  23020. * @default 1
  23021. */
  23022. this.clearStencilValue = 1;
  23023. /**
  23024. * By default the viewport encloses the entire framebuffer If a smaller
  23025. * viewport is manually defined, this property is to `true` by the renderer.
  23026. *
  23027. * @type {boolean}
  23028. * @default false
  23029. */
  23030. this.viewport = false;
  23031. /**
  23032. * The viewport value. This value is in physical pixels meaning it incorporates
  23033. * the renderer's pixel ratio. The viewport property of render targets or
  23034. * the renderer is in logical pixels.
  23035. *
  23036. * @type {Vector4}
  23037. */
  23038. this.viewportValue = new Vector4();
  23039. /**
  23040. * When the scissor test is active and scissor rectangle smaller than the
  23041. * framebuffers dimensions, this property is to `true` by the renderer.
  23042. *
  23043. * @type {boolean}
  23044. * @default false
  23045. */
  23046. this.scissor = false;
  23047. /**
  23048. * The scissor rectangle.
  23049. *
  23050. * @type {Vector4}
  23051. */
  23052. this.scissorValue = new Vector4();
  23053. /**
  23054. * The active render target.
  23055. *
  23056. * @type {?RenderTarget}
  23057. * @default null
  23058. */
  23059. this.renderTarget = null;
  23060. /**
  23061. * The textures of the active render target.
  23062. * `null` when no render target is set.
  23063. *
  23064. * @type {?Array<Texture>}
  23065. * @default null
  23066. */
  23067. this.textures = null;
  23068. /**
  23069. * The depth texture of the active render target.
  23070. * `null` when no render target is set.
  23071. *
  23072. * @type {?DepthTexture}
  23073. * @default null
  23074. */
  23075. this.depthTexture = null;
  23076. /**
  23077. * The active cube face.
  23078. *
  23079. * @type {number}
  23080. * @default 0
  23081. */
  23082. this.activeCubeFace = 0;
  23083. /**
  23084. * The active mipmap level.
  23085. *
  23086. * @type {number}
  23087. * @default 0
  23088. */
  23089. this.activeMipmapLevel = 0;
  23090. /**
  23091. * The number of MSAA samples. This value is always `1` when
  23092. * MSAA isn't used.
  23093. *
  23094. * @type {number}
  23095. * @default 1
  23096. */
  23097. this.sampleCount = 1;
  23098. /**
  23099. * The active render target's width in physical pixels.
  23100. *
  23101. * @type {number}
  23102. * @default 0
  23103. */
  23104. this.width = 0;
  23105. /**
  23106. * The active render target's height in physical pixels.
  23107. *
  23108. * @type {number}
  23109. * @default 0
  23110. */
  23111. this.height = 0;
  23112. /**
  23113. * The occlusion query count.
  23114. *
  23115. * @type {number}
  23116. * @default 0
  23117. */
  23118. this.occlusionQueryCount = 0;
  23119. /**
  23120. * The current clipping context.
  23121. *
  23122. * @type {?ClippingContext}
  23123. * @default null
  23124. */
  23125. this.clippingContext = null;
  23126. /**
  23127. * The current camera.
  23128. *
  23129. * @type {?Camera}
  23130. * @default null
  23131. */
  23132. this.camera = null;
  23133. /**
  23134. * This flag can be used for type testing.
  23135. *
  23136. * @type {boolean}
  23137. * @readonly
  23138. * @default true
  23139. */
  23140. this.isRenderContext = true;
  23141. }
  23142. /**
  23143. * Returns the cache key of this render context.
  23144. *
  23145. * @return {number} The cache key.
  23146. */
  23147. getCacheKey() {
  23148. return getCacheKey( this );
  23149. }
  23150. }
  23151. /**
  23152. * Computes a cache key for the given render context. This key
  23153. * should identify the render target state so it is possible to
  23154. * configure the correct attachments in the respective backend.
  23155. *
  23156. * @param {RenderContext} renderContext - The render context.
  23157. * @return {number} The cache key.
  23158. */
  23159. function getCacheKey( renderContext ) {
  23160. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  23161. const values = [ activeCubeFace, activeMipmapLevel ];
  23162. for ( const texture of textures ) {
  23163. values.push( texture.id );
  23164. }
  23165. return hashArray( values );
  23166. }
  23167. /**
  23168. * This module manages the render contexts of the renderer.
  23169. *
  23170. * @private
  23171. */
  23172. class RenderContexts {
  23173. /**
  23174. * Constructs a new render context management component.
  23175. *
  23176. * @param {Renderer} renderer - The renderer.
  23177. */
  23178. constructor( renderer ) {
  23179. /**
  23180. * The renderer.
  23181. *
  23182. * @type {Renderer}
  23183. */
  23184. this.renderer = renderer;
  23185. /**
  23186. * A dictionary that manages render contexts.
  23187. *
  23188. * @type {Object<string,RenderContext>}
  23189. */
  23190. this._renderContexts = {};
  23191. }
  23192. /**
  23193. * Returns a render context for the given scene, camera and render target.
  23194. *
  23195. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  23196. * @param {?MRTNode} [mrt=null] - The MRT configuration
  23197. * @param {?number} [callDepth=0] - The call depth of the renderer.
  23198. * @return {RenderContext} The render context.
  23199. */
  23200. get( renderTarget = null, mrt = null, callDepth = 0 ) {
  23201. //
  23202. let attachmentState;
  23203. if ( renderTarget === null ) {
  23204. attachmentState = 'default';
  23205. } else {
  23206. const format = renderTarget.texture.format;
  23207. const type = renderTarget.texture.type;
  23208. const count = renderTarget.textures.length;
  23209. attachmentState = `${ count }:${ format }:${ type }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  23210. }
  23211. //
  23212. const mrtState = ( mrt !== null ) ? mrt.id : 'default';
  23213. //
  23214. const renderStateKey = attachmentState + '-' + mrtState + '-' + callDepth;
  23215. let renderState = this._renderContexts[ renderStateKey ];
  23216. if ( renderState === undefined ) {
  23217. renderState = new RenderContext();
  23218. renderState.mrt = mrt;
  23219. this._renderContexts[ renderStateKey ] = renderState;
  23220. }
  23221. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  23222. renderState.clearDepthValue = this.renderer.getClearDepth();
  23223. renderState.clearStencilValue = this.renderer.getClearStencil();
  23224. return renderState;
  23225. }
  23226. /**
  23227. * Frees internal resources.
  23228. */
  23229. dispose() {
  23230. this._renderContexts = {};
  23231. }
  23232. }
  23233. const _size$3 = /*@__PURE__*/ new Vector3();
  23234. /**
  23235. * This module manages the textures of the renderer.
  23236. *
  23237. * @private
  23238. * @augments DataMap
  23239. */
  23240. class Textures extends DataMap {
  23241. /**
  23242. * Constructs a new texture management component.
  23243. *
  23244. * @param {Renderer} renderer - The renderer.
  23245. * @param {Backend} backend - The renderer's backend.
  23246. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  23247. */
  23248. constructor( renderer, backend, info ) {
  23249. super();
  23250. /**
  23251. * The renderer.
  23252. *
  23253. * @type {Renderer}
  23254. */
  23255. this.renderer = renderer;
  23256. /**
  23257. * The backend.
  23258. *
  23259. * @type {Backend}
  23260. */
  23261. this.backend = backend;
  23262. /**
  23263. * Renderer component for managing metrics and monitoring data.
  23264. *
  23265. * @type {Info}
  23266. */
  23267. this.info = info;
  23268. }
  23269. /**
  23270. * Updates the given render target. Based on the given render target configuration,
  23271. * it updates the texture states representing the attachments of the framebuffer.
  23272. *
  23273. * @param {RenderTarget} renderTarget - The render target to update.
  23274. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  23275. */
  23276. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  23277. const renderTargetData = this.get( renderTarget );
  23278. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  23279. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  23280. const textures = renderTarget.textures;
  23281. const size = this.getSize( textures[ 0 ] );
  23282. const mipWidth = size.width >> activeMipmapLevel;
  23283. const mipHeight = size.height >> activeMipmapLevel;
  23284. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  23285. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  23286. let textureNeedsUpdate = false;
  23287. if ( depthTexture === undefined && useDepthTexture ) {
  23288. depthTexture = new DepthTexture();
  23289. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  23290. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  23291. depthTexture.image.width = mipWidth;
  23292. depthTexture.image.height = mipHeight;
  23293. depthTexture.image.depth = size.depth;
  23294. depthTexture.renderTarget = renderTarget;
  23295. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  23296. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  23297. }
  23298. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  23299. textureNeedsUpdate = true;
  23300. if ( depthTexture ) {
  23301. depthTexture.needsUpdate = true;
  23302. depthTexture.image.width = mipWidth;
  23303. depthTexture.image.height = mipHeight;
  23304. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  23305. }
  23306. }
  23307. renderTargetData.width = size.width;
  23308. renderTargetData.height = size.height;
  23309. renderTargetData.textures = textures;
  23310. renderTargetData.depthTexture = depthTexture || null;
  23311. renderTargetData.depth = renderTarget.depthBuffer;
  23312. renderTargetData.stencil = renderTarget.stencilBuffer;
  23313. renderTargetData.renderTarget = renderTarget;
  23314. if ( renderTargetData.sampleCount !== sampleCount ) {
  23315. textureNeedsUpdate = true;
  23316. if ( depthTexture ) {
  23317. depthTexture.needsUpdate = true;
  23318. }
  23319. renderTargetData.sampleCount = sampleCount;
  23320. }
  23321. //
  23322. const options = { sampleCount };
  23323. // XR render targets require no texture updates
  23324. if ( renderTarget.isXRRenderTarget !== true ) {
  23325. for ( let i = 0; i < textures.length; i ++ ) {
  23326. const texture = textures[ i ];
  23327. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  23328. this.updateTexture( texture, options );
  23329. }
  23330. if ( depthTexture ) {
  23331. this.updateTexture( depthTexture, options );
  23332. }
  23333. }
  23334. // dispose handler
  23335. if ( renderTargetData.initialized !== true ) {
  23336. renderTargetData.initialized = true;
  23337. // dispose
  23338. renderTargetData.onDispose = () => {
  23339. this._destroyRenderTarget( renderTarget );
  23340. };
  23341. renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );
  23342. }
  23343. }
  23344. /**
  23345. * Updates the given texture. Depending on the texture state, this method
  23346. * triggers the upload of texture data to the GPU memory. If the texture data are
  23347. * not yet ready for the upload, it uses default texture data for as a placeholder.
  23348. *
  23349. * @param {Texture} texture - The texture to update.
  23350. * @param {Object} [options={}] - The options.
  23351. */
  23352. updateTexture( texture, options = {} ) {
  23353. const textureData = this.get( texture );
  23354. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  23355. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  23356. const backend = this.backend;
  23357. if ( isRenderTarget && textureData.initialized === true ) {
  23358. // it's an update
  23359. backend.destroyTexture( texture );
  23360. }
  23361. //
  23362. if ( texture.isFramebufferTexture ) {
  23363. const renderTarget = this.renderer.getRenderTarget();
  23364. if ( renderTarget ) {
  23365. texture.type = renderTarget.texture.type;
  23366. } else {
  23367. texture.type = UnsignedByteType;
  23368. }
  23369. }
  23370. //
  23371. const { width, height, depth } = this.getSize( texture );
  23372. options.width = width;
  23373. options.height = height;
  23374. options.depth = depth;
  23375. options.needsMipmaps = this.needsMipmaps( texture );
  23376. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  23377. // TODO: Uniformly handle mipmap definitions
  23378. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  23379. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  23380. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  23381. //
  23382. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  23383. backend.createTexture( texture, options );
  23384. textureData.generation = texture.version;
  23385. } else {
  23386. if ( texture.version > 0 ) {
  23387. const image = texture.image;
  23388. if ( image === undefined ) {
  23389. warn( 'Renderer: Texture marked for update but image is undefined.' );
  23390. } else if ( image.complete === false ) {
  23391. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  23392. } else {
  23393. if ( texture.images ) {
  23394. const images = [];
  23395. for ( const image of texture.images ) {
  23396. images.push( image );
  23397. }
  23398. options.images = images;
  23399. } else {
  23400. options.image = image;
  23401. }
  23402. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  23403. backend.createTexture( texture, options );
  23404. textureData.isDefaultTexture = false;
  23405. textureData.generation = texture.version;
  23406. }
  23407. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  23408. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  23409. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  23410. backend.generateMipmaps( texture );
  23411. }
  23412. if ( texture.onUpdate ) texture.onUpdate( texture );
  23413. }
  23414. } else {
  23415. // async update
  23416. backend.createDefaultTexture( texture );
  23417. textureData.isDefaultTexture = true;
  23418. textureData.generation = texture.version;
  23419. }
  23420. }
  23421. // dispose handler
  23422. if ( textureData.initialized !== true ) {
  23423. textureData.initialized = true;
  23424. textureData.generation = texture.version;
  23425. //
  23426. this.info.memory.textures ++;
  23427. //
  23428. if ( texture.isVideoTexture && ColorManagement.enabled === true && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  23429. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  23430. }
  23431. // dispose
  23432. textureData.onDispose = () => {
  23433. this._destroyTexture( texture );
  23434. };
  23435. texture.addEventListener( 'dispose', textureData.onDispose );
  23436. }
  23437. //
  23438. textureData.version = texture.version;
  23439. }
  23440. /**
  23441. * Updates the sampler for the given texture. This method has no effect
  23442. * for the WebGL backend since it has no concept of samplers. Texture
  23443. * parameters are configured with the `texParameter()` command for each
  23444. * texture.
  23445. *
  23446. * In WebGPU, samplers are objects like textures and it's possible to share
  23447. * them when the texture parameters match.
  23448. *
  23449. * @param {Texture} texture - The texture to update the sampler for.
  23450. * @return {string} The current sampler key.
  23451. */
  23452. updateSampler( texture ) {
  23453. return this.backend.updateSampler( texture );
  23454. }
  23455. /**
  23456. * Computes the size of the given texture and writes the result
  23457. * into the target vector. This vector is also returned by the
  23458. * method.
  23459. *
  23460. * If no texture data are available for the compute yet, the method
  23461. * returns default size values.
  23462. *
  23463. * @param {Texture} texture - The texture to compute the size for.
  23464. * @param {Vector3} target - The target vector.
  23465. * @return {Vector3} The target vector.
  23466. */
  23467. getSize( texture, target = _size$3 ) {
  23468. let image = texture.images ? texture.images[ 0 ] : texture.image;
  23469. if ( image ) {
  23470. if ( image.image !== undefined ) image = image.image;
  23471. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  23472. target.width = image.videoWidth || 1;
  23473. target.height = image.videoHeight || 1;
  23474. target.depth = 1;
  23475. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  23476. target.width = image.displayWidth || 1;
  23477. target.height = image.displayHeight || 1;
  23478. target.depth = 1;
  23479. } else {
  23480. target.width = image.width || 1;
  23481. target.height = image.height || 1;
  23482. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  23483. }
  23484. } else {
  23485. target.width = target.height = target.depth = 1;
  23486. }
  23487. return target;
  23488. }
  23489. /**
  23490. * Computes the number of mipmap levels for the given texture.
  23491. *
  23492. * @param {Texture} texture - The texture.
  23493. * @param {number} width - The texture's width.
  23494. * @param {number} height - The texture's height.
  23495. * @return {number} The number of mipmap levels.
  23496. */
  23497. getMipLevels( texture, width, height ) {
  23498. let mipLevelCount;
  23499. if ( texture.mipmaps.length > 0 ) {
  23500. mipLevelCount = texture.mipmaps.length;
  23501. } else {
  23502. if ( texture.isCompressedTexture === true ) {
  23503. // it is not possible to compute mipmaps for compressed textures. So
  23504. // when no mipmaps are defined in "texture.mipmaps", force a texture
  23505. // level of 1
  23506. mipLevelCount = 1;
  23507. } else {
  23508. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  23509. }
  23510. }
  23511. return mipLevelCount;
  23512. }
  23513. /**
  23514. * Returns `true` if the given texture makes use of mipmapping.
  23515. *
  23516. * @param {Texture} texture - The texture.
  23517. * @return {boolean} Whether mipmaps are required or not.
  23518. */
  23519. needsMipmaps( texture ) {
  23520. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  23521. }
  23522. /**
  23523. * Frees internal resources when the given render target isn't
  23524. * required anymore.
  23525. *
  23526. * @param {RenderTarget} renderTarget - The render target to destroy.
  23527. */
  23528. _destroyRenderTarget( renderTarget ) {
  23529. if ( this.has( renderTarget ) === true ) {
  23530. const renderTargetData = this.get( renderTarget );
  23531. const textures = renderTargetData.textures;
  23532. const depthTexture = renderTargetData.depthTexture;
  23533. //
  23534. renderTarget.removeEventListener( 'dispose', renderTargetData.onDispose );
  23535. //
  23536. for ( let i = 0; i < textures.length; i ++ ) {
  23537. this._destroyTexture( textures[ i ] );
  23538. }
  23539. if ( depthTexture ) {
  23540. this._destroyTexture( depthTexture );
  23541. }
  23542. this.delete( renderTarget );
  23543. this.backend.delete( renderTarget );
  23544. }
  23545. }
  23546. /**
  23547. * Frees internal resource when the given texture isn't
  23548. * required anymore.
  23549. *
  23550. * @param {Texture} texture - The texture to destroy.
  23551. */
  23552. _destroyTexture( texture ) {
  23553. if ( this.has( texture ) === true ) {
  23554. const textureData = this.get( texture );
  23555. //
  23556. texture.removeEventListener( 'dispose', textureData.onDispose );
  23557. // if a texture is not ready for use, it falls back to a default texture so it's possible
  23558. // to use it for rendering. If a texture in this state is disposed, it's important to
  23559. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  23560. // other textures.
  23561. const isDefaultTexture = textureData.isDefaultTexture;
  23562. this.backend.destroyTexture( texture, isDefaultTexture );
  23563. this.delete( texture );
  23564. this.info.memory.textures --;
  23565. }
  23566. }
  23567. }
  23568. /**
  23569. * A four-component version of {@link Color} which is internally
  23570. * used by the renderer to represents clear color with alpha as
  23571. * one object.
  23572. *
  23573. * @private
  23574. * @augments Color
  23575. */
  23576. class Color4 extends Color {
  23577. /**
  23578. * Constructs a new four-component color.
  23579. * You can also pass a single THREE.Color, hex or
  23580. * string argument to this constructor.
  23581. *
  23582. * @param {number|string} [r=1] - The red value.
  23583. * @param {number} [g=1] - The green value.
  23584. * @param {number} [b=1] - The blue value.
  23585. * @param {number} [a=1] - The alpha value.
  23586. */
  23587. constructor( r, g, b, a = 1 ) {
  23588. super( r, g, b );
  23589. this.a = a;
  23590. }
  23591. /**
  23592. * Overwrites the default to honor alpha.
  23593. * You can also pass a single THREE.Color, hex or
  23594. * string argument to this method.
  23595. *
  23596. * @param {number|string|Color} r - The red value.
  23597. * @param {number} [g] - The green value.
  23598. * @param {number} [b] - The blue value.
  23599. * @param {number} [a=1] - The alpha value.
  23600. * @return {Color4} A reference to this object.
  23601. */
  23602. set( r, g, b, a = 1 ) {
  23603. this.a = a;
  23604. return super.set( r, g, b );
  23605. }
  23606. /**
  23607. * Overwrites the default to honor alpha.
  23608. *
  23609. * @param {Color4} color - The color to copy.
  23610. * @return {Color4} A reference to this object.
  23611. */
  23612. copy( color ) {
  23613. if ( color.a !== undefined ) this.a = color.a;
  23614. return super.copy( color );
  23615. }
  23616. /**
  23617. * Overwrites the default to honor alpha.
  23618. *
  23619. * @return {Color4} The cloned color.
  23620. */
  23621. clone() {
  23622. return new this.constructor( this.r, this.g, this.b, this.a );
  23623. }
  23624. }
  23625. /**
  23626. * Special version of {@link PropertyNode} which is used for parameters.
  23627. *
  23628. * @augments PropertyNode
  23629. */
  23630. class ParameterNode extends PropertyNode {
  23631. static get type() {
  23632. return 'ParameterNode';
  23633. }
  23634. /**
  23635. * Constructs a new parameter node.
  23636. *
  23637. * @param {string} nodeType - The type of the node.
  23638. * @param {?string} [name=null] - The name of the parameter in the shader.
  23639. */
  23640. constructor( nodeType, name = null ) {
  23641. super( nodeType, name );
  23642. /**
  23643. * This flag can be used for type testing.
  23644. *
  23645. * @type {boolean}
  23646. * @readonly
  23647. * @default true
  23648. */
  23649. this.isParameterNode = true;
  23650. }
  23651. /**
  23652. * Gets the type of a member variable in the parameter node.
  23653. *
  23654. * @param {NodeBuilder} builder - The node builder.
  23655. * @param {string} name - The name of the member variable.
  23656. * @returns {string}
  23657. */
  23658. getMemberType( builder, name ) {
  23659. const type = this.getNodeType( builder );
  23660. const struct = builder.getStructTypeNode( type );
  23661. let memberType;
  23662. if ( struct !== null ) {
  23663. memberType = struct.getMemberType( builder, name );
  23664. } else {
  23665. error( `TSL: Member "${ name }" not found in struct "${ type }".`, new StackTrace() );
  23666. memberType = 'float';
  23667. }
  23668. return memberType;
  23669. }
  23670. getHash() {
  23671. return this.uuid;
  23672. }
  23673. generate() {
  23674. return this.name;
  23675. }
  23676. }
  23677. /**
  23678. * TSL function for creating a parameter node.
  23679. *
  23680. * @tsl
  23681. * @function
  23682. * @param {string} type - The type of the node.
  23683. * @param {?string} name - The name of the parameter in the shader.
  23684. * @returns {ParameterNode}
  23685. */
  23686. const parameter = ( type, name ) => new ParameterNode( type, name );
  23687. /**
  23688. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  23689. * They are usually needed in cases like `If`, `Else`.
  23690. *
  23691. * @augments Node
  23692. */
  23693. class StackNode extends Node {
  23694. static get type() {
  23695. return 'StackNode';
  23696. }
  23697. /**
  23698. * Constructs a new stack node.
  23699. *
  23700. * @param {?StackNode} [parent=null] - The parent stack node.
  23701. */
  23702. constructor( parent = null ) {
  23703. super();
  23704. /**
  23705. * List of nodes.
  23706. *
  23707. * @type {Array<Node>}
  23708. */
  23709. this.nodes = [];
  23710. /**
  23711. * The output node.
  23712. *
  23713. * @type {?Node}
  23714. * @default null
  23715. */
  23716. this.outputNode = null;
  23717. /**
  23718. * The parent stack node.
  23719. *
  23720. * @type {?StackNode}
  23721. * @default null
  23722. */
  23723. this.parent = parent;
  23724. /**
  23725. * The current conditional node.
  23726. *
  23727. * @private
  23728. * @type {ConditionalNode}
  23729. * @default null
  23730. */
  23731. this._currentCond = null;
  23732. /**
  23733. * The expression node. Only
  23734. * relevant for Switch/Case.
  23735. *
  23736. * @private
  23737. * @type {Node}
  23738. * @default null
  23739. */
  23740. this._expressionNode = null;
  23741. /**
  23742. * The current node being processed.
  23743. *
  23744. * @private
  23745. * @type {Node}
  23746. * @default null
  23747. */
  23748. this._currentNode = null;
  23749. /**
  23750. * This flag can be used for type testing.
  23751. *
  23752. * @type {boolean}
  23753. * @readonly
  23754. * @default true
  23755. */
  23756. this.isStackNode = true;
  23757. }
  23758. getElementType( builder ) {
  23759. return this.hasOutput( builder ) ? this.outputNode.getElementType( builder ) : 'void';
  23760. }
  23761. getNodeType( builder ) {
  23762. return this.hasOutput( builder ) ? this.outputNode.getNodeType( builder ) : 'void';
  23763. }
  23764. getMemberType( builder, name ) {
  23765. return this.hasOutput( builder ) ? this.outputNode.getMemberType( builder, name ) : 'void';
  23766. }
  23767. /**
  23768. * Adds a node to this stack.
  23769. *
  23770. * @param {Node} node - The node to add.
  23771. * @param {number} [index=this.nodes.length] - The index where the node should be added.
  23772. * @return {StackNode} A reference to this stack node.
  23773. */
  23774. addToStack( node, index = this.nodes.length ) {
  23775. if ( node.isNode !== true ) {
  23776. error( 'TSL: Invalid node added to stack.', new StackTrace() );
  23777. return this;
  23778. }
  23779. this.nodes.splice( index, 0, node );
  23780. return this;
  23781. }
  23782. /**
  23783. * Adds a node to the stack before the current node.
  23784. *
  23785. * @param {Node} node - The node to add.
  23786. * @return {StackNode} A reference to this stack node.
  23787. */
  23788. addToStackBefore( node ) {
  23789. const index = this._currentNode ? this.nodes.indexOf( this._currentNode ) : 0;
  23790. return this.addToStack( node, index );
  23791. }
  23792. /**
  23793. * Represent an `if` statement in TSL.
  23794. *
  23795. * @param {Node} boolNode - Represents the condition.
  23796. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23797. * @return {StackNode} A reference to this stack node.
  23798. */
  23799. If( boolNode, method ) {
  23800. const methodNode = new ShaderNode( method );
  23801. this._currentCond = select( boolNode, methodNode );
  23802. return this.addToStack( this._currentCond );
  23803. }
  23804. /**
  23805. * Represent an `elseif` statement in TSL.
  23806. *
  23807. * @param {Node} boolNode - Represents the condition.
  23808. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23809. * @return {StackNode} A reference to this stack node.
  23810. */
  23811. ElseIf( boolNode, method ) {
  23812. const methodNode = new ShaderNode( method );
  23813. const ifNode = select( boolNode, methodNode );
  23814. this._currentCond.elseNode = ifNode;
  23815. this._currentCond = ifNode;
  23816. return this;
  23817. }
  23818. /**
  23819. * Represent an `else` statement in TSL.
  23820. *
  23821. * @param {Function} method - TSL code which is executed in the `else` case.
  23822. * @return {StackNode} A reference to this stack node.
  23823. */
  23824. Else( method ) {
  23825. this._currentCond.elseNode = new ShaderNode( method );
  23826. return this;
  23827. }
  23828. /**
  23829. * Represents a `switch` statement in TSL.
  23830. *
  23831. * @param {any} expression - Represents the expression.
  23832. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23833. * @return {StackNode} A reference to this stack node.
  23834. */
  23835. Switch( expression ) {
  23836. this._expressionNode = nodeObject( expression );
  23837. return this;
  23838. }
  23839. /**
  23840. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  23841. * The last parameter must be the callback method that should be executed in the `true` case.
  23842. *
  23843. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  23844. * @return {StackNode} A reference to this stack node.
  23845. */
  23846. Case( ...params ) {
  23847. const caseNodes = [];
  23848. // extract case nodes from the parameter list
  23849. if ( params.length >= 2 ) {
  23850. for ( let i = 0; i < params.length - 1; i ++ ) {
  23851. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  23852. }
  23853. } else {
  23854. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.', new StackTrace() );
  23855. }
  23856. // extract method
  23857. const method = params[ params.length - 1 ];
  23858. const methodNode = new ShaderNode( method );
  23859. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  23860. let caseNode = caseNodes[ 0 ];
  23861. for ( let i = 1; i < caseNodes.length; i ++ ) {
  23862. caseNode = caseNode.or( caseNodes[ i ] );
  23863. }
  23864. // build condition
  23865. const condNode = select( caseNode, methodNode );
  23866. if ( this._currentCond === null ) {
  23867. this._currentCond = condNode;
  23868. return this.addToStack( this._currentCond );
  23869. } else {
  23870. this._currentCond.elseNode = condNode;
  23871. this._currentCond = condNode;
  23872. return this;
  23873. }
  23874. }
  23875. /**
  23876. * Represents the default code block of a Switch/Case statement.
  23877. *
  23878. * @param {Function} method - TSL code which is executed in the `else` case.
  23879. * @return {StackNode} A reference to this stack node.
  23880. */
  23881. Default( method ) {
  23882. this.Else( method );
  23883. return this;
  23884. }
  23885. setup( builder ) {
  23886. const nodeProperties = builder.getNodeProperties( this );
  23887. let index = 0;
  23888. for ( const childNode of this.getChildren() ) {
  23889. if ( childNode.isVarNode && childNode.isIntent( builder ) ) {
  23890. if ( childNode.isAssign( builder ) !== true ) {
  23891. continue;
  23892. }
  23893. }
  23894. nodeProperties[ 'node' + index ++ ] = childNode;
  23895. }
  23896. // return a outputNode if exists or null
  23897. return nodeProperties.outputNode || null;
  23898. }
  23899. hasOutput( builder ) {
  23900. return this.outputNode && this.outputNode.isNode && this.outputNode.getNodeType( builder ) !== 'void';
  23901. }
  23902. build( builder, ...params ) {
  23903. const previousStack = getCurrentStack();
  23904. const buildStage = builder.buildStage;
  23905. setCurrentStack( this );
  23906. builder.setActiveStack( this );
  23907. //
  23908. const buildNode = ( node ) => {
  23909. this._currentNode = node;
  23910. if ( node.isVarNode && node.isIntent( builder ) ) {
  23911. if ( node.isAssign( builder ) !== true ) {
  23912. return;
  23913. }
  23914. }
  23915. if ( buildStage === 'setup' ) {
  23916. node.build( builder );
  23917. } else if ( buildStage === 'analyze' ) {
  23918. node.build( builder, this );
  23919. } else if ( buildStage === 'generate' ) {
  23920. const stages = builder.getDataFromNode( node, 'any' ).stages;
  23921. const parents = stages && stages[ builder.shaderStage ];
  23922. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  23923. return; // skip var nodes that are only used in .toVarying()
  23924. }
  23925. node.build( builder, 'void' );
  23926. }
  23927. };
  23928. //
  23929. const nodes = [ ...this.nodes ];
  23930. for ( const node of nodes ) {
  23931. buildNode( node );
  23932. }
  23933. this._currentNode = null;
  23934. const newNodes = this.nodes.filter( ( node ) => nodes.indexOf( node ) === -1 );
  23935. for ( const node of newNodes ) {
  23936. buildNode( node );
  23937. }
  23938. //
  23939. let result;
  23940. if ( this.hasOutput( builder ) ) {
  23941. result = this.outputNode.build( builder, ...params );
  23942. } else {
  23943. result = super.build( builder, ...params );
  23944. }
  23945. setCurrentStack( previousStack );
  23946. builder.removeActiveStack( this );
  23947. return result;
  23948. }
  23949. }
  23950. /**
  23951. * TSL function for creating a stack node.
  23952. *
  23953. * @tsl
  23954. * @function
  23955. * @param {?StackNode} [parent=null] - The parent stack node.
  23956. * @returns {StackNode}
  23957. */
  23958. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  23959. /**
  23960. * Generates a layout for struct members.
  23961. * This function takes an object representing struct members and returns an array of member layouts.
  23962. * Each member layout includes the member's name, type, and whether it is atomic.
  23963. *
  23964. * @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.
  23965. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  23966. */
  23967. function getMembersLayout( members ) {
  23968. return Object.entries( members ).map( ( [ name, value ] ) => {
  23969. if ( typeof value === 'string' ) {
  23970. return { name, type: value, atomic: false };
  23971. }
  23972. return { name, type: value.type, atomic: value.atomic || false };
  23973. } );
  23974. }
  23975. /**
  23976. * Represents a struct type node in the node-based system.
  23977. * This class is used to define and manage the layout and types of struct members.
  23978. * It extends the base Node class and provides methods to get the length of the struct,
  23979. * retrieve member types, and generate the struct type for a builder.
  23980. *
  23981. * @augments Node
  23982. */
  23983. class StructTypeNode extends Node {
  23984. static get type() {
  23985. return 'StructTypeNode';
  23986. }
  23987. /**
  23988. * Creates an instance of StructTypeNode.
  23989. *
  23990. * @param {Object} membersLayout - The layout of the members for the struct.
  23991. * @param {?string} [name=null] - The optional name of the struct.
  23992. */
  23993. constructor( membersLayout, name = null ) {
  23994. super( 'struct' );
  23995. /**
  23996. * The layout of the members for the struct
  23997. *
  23998. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  23999. */
  24000. this.membersLayout = getMembersLayout( membersLayout );
  24001. /**
  24002. * The name of the struct.
  24003. *
  24004. * @type {?string}
  24005. * @default null
  24006. */
  24007. this.name = name;
  24008. /**
  24009. * This flag can be used for type testing.
  24010. *
  24011. * @type {boolean}
  24012. * @readonly
  24013. * @default true
  24014. */
  24015. this.isStructLayoutNode = true;
  24016. }
  24017. /**
  24018. * Returns the length of the struct.
  24019. * The length is calculated by summing the lengths of the struct's members.
  24020. *
  24021. * @returns {number} The length of the struct.
  24022. */
  24023. getLength() {
  24024. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  24025. let maxAlignment = 1; // maximum alignment value in this struct
  24026. let offset = 0; // global buffer offset in 4 byte elements
  24027. for ( const member of this.membersLayout ) {
  24028. const type = member.type;
  24029. const itemSize = getMemoryLengthFromType( type );
  24030. const alignment = getAlignmentFromType( type ) / BYTES_PER_ELEMENT;
  24031. maxAlignment = Math.max( maxAlignment, alignment );
  24032. const chunkOffset = offset % maxAlignment; // offset in the current chunk of maxAlignment elements
  24033. const overhang = chunkOffset % alignment; // distance from the last aligned offset
  24034. if ( overhang !== 0 ) {
  24035. offset += alignment - overhang; // move to next aligned offset
  24036. }
  24037. offset += itemSize;
  24038. }
  24039. return ( Math.ceil( offset / maxAlignment ) * maxAlignment ); // ensure length is a multiple of maxAlignment
  24040. }
  24041. getMemberType( builder, name ) {
  24042. const member = this.membersLayout.find( m => m.name === name );
  24043. return member ? member.type : 'void';
  24044. }
  24045. getNodeType( builder ) {
  24046. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  24047. return structType.name;
  24048. }
  24049. setup( builder ) {
  24050. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  24051. builder.addInclude( this );
  24052. }
  24053. generate( builder ) {
  24054. return this.getNodeType( builder );
  24055. }
  24056. }
  24057. /**
  24058. * StructNode allows to create custom structures with multiple members.
  24059. * This can also be used to define structures in attribute and uniform data.
  24060. *
  24061. * ```js
  24062. * // Define a custom struct
  24063. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  24064. *
  24065. * // Create a new instance of the struct
  24066. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  24067. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  24068. *
  24069. * // Access the struct members
  24070. * const min = bb.get( 'min' );
  24071. *
  24072. * // Assign a new value to a member
  24073. * min.assign( vec3() );
  24074. * ```
  24075. * @augments Node
  24076. */
  24077. class StructNode extends Node {
  24078. static get type() {
  24079. return 'StructNode';
  24080. }
  24081. constructor( structTypeNode, values ) {
  24082. super( 'vec3' );
  24083. this.structTypeNode = structTypeNode;
  24084. this.values = values;
  24085. this.isStructNode = true;
  24086. }
  24087. getNodeType( builder ) {
  24088. return this.structTypeNode.getNodeType( builder );
  24089. }
  24090. getMemberType( builder, name ) {
  24091. return this.structTypeNode.getMemberType( builder, name );
  24092. }
  24093. _getChildren() {
  24094. // Ensure struct type is the last child for correct code generation order
  24095. const children = super._getChildren();
  24096. const structTypeProperty = children.find( child => child.childNode === this.structTypeNode );
  24097. children.splice( children.indexOf( structTypeProperty ), 1 );
  24098. children.push( structTypeProperty );
  24099. return children;
  24100. }
  24101. generate( builder ) {
  24102. const nodeVar = builder.getVarFromNode( this );
  24103. const structType = nodeVar.type;
  24104. const propertyName = builder.getPropertyName( nodeVar );
  24105. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  24106. return nodeVar.name;
  24107. }
  24108. }
  24109. /**
  24110. * TSL function for creating a struct node.
  24111. *
  24112. * @tsl
  24113. * @function
  24114. * @param {Object} membersLayout - The layout of the struct members.
  24115. * @param {?string} [name=null] - The name of the struct.
  24116. * @returns {Function} The struct function.
  24117. */
  24118. const struct = ( membersLayout, name = null ) => {
  24119. const structLayout = new StructTypeNode( membersLayout, name );
  24120. const struct = ( ...params ) => {
  24121. let values = null;
  24122. if ( params.length > 0 ) {
  24123. if ( params[ 0 ].isNode ) {
  24124. values = {};
  24125. const names = Object.keys( membersLayout );
  24126. for ( let i = 0; i < params.length; i ++ ) {
  24127. values[ names[ i ] ] = params[ i ];
  24128. }
  24129. } else {
  24130. values = params[ 0 ];
  24131. }
  24132. }
  24133. return new StructNode( structLayout, values );
  24134. };
  24135. struct.layout = structLayout;
  24136. struct.isStruct = true;
  24137. return struct;
  24138. };
  24139. /**
  24140. * This node can be used to define multiple outputs in a shader programs.
  24141. *
  24142. * @augments Node
  24143. */
  24144. class OutputStructNode extends Node {
  24145. static get type() {
  24146. return 'OutputStructNode';
  24147. }
  24148. /**
  24149. * Constructs a new output struct node. The constructor can be invoked with an
  24150. * arbitrary number of nodes representing the members.
  24151. *
  24152. * @param {...Node} members - A parameter list of nodes.
  24153. */
  24154. constructor( ...members ) {
  24155. super();
  24156. /**
  24157. * An array of nodes which defines the output.
  24158. *
  24159. * @type {Array<Node>}
  24160. */
  24161. this.members = members;
  24162. /**
  24163. * This flag can be used for type testing.
  24164. *
  24165. * @type {boolean}
  24166. * @readonly
  24167. * @default true
  24168. */
  24169. this.isOutputStructNode = true;
  24170. }
  24171. getNodeType( /*builder*/ ) {
  24172. return 'OutputType';
  24173. }
  24174. generate( builder ) {
  24175. const nodeData = builder.getDataFromNode( this );
  24176. if ( nodeData.membersLayout === undefined ) {
  24177. const members = this.members;
  24178. const membersLayout = [];
  24179. for ( let i = 0; i < members.length; i ++ ) {
  24180. const name = 'm' + i;
  24181. const type = members[ i ].getNodeType( builder );
  24182. membersLayout.push( { name, type, index: i } );
  24183. }
  24184. nodeData.membersLayout = membersLayout;
  24185. nodeData.structType = builder.getOutputStructTypeFromNode( this, nodeData.membersLayout );
  24186. }
  24187. //
  24188. const propertyName = builder.getOutputStructName();
  24189. const members = this.members;
  24190. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  24191. for ( let i = 0; i < members.length; i ++ ) {
  24192. const snippet = members[ i ].build( builder );
  24193. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  24194. }
  24195. return propertyName;
  24196. }
  24197. }
  24198. /**
  24199. * TSL function for creating an output struct node.
  24200. *
  24201. * @tsl
  24202. * @function
  24203. * @param {...Node} members - A parameter list of nodes.
  24204. * @returns {OutputStructNode}
  24205. */
  24206. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  24207. /**
  24208. * Represents blending configuration.
  24209. *
  24210. * This class encapsulates all blending-related properties that control how
  24211. * a material's colors are combined with the colors already in the frame buffer.
  24212. */
  24213. class BlendMode {
  24214. /**
  24215. * Constructs a new blending configuration.
  24216. *
  24217. * @param {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending|MaterialBlending)} [blending=NormalBlending] - The blending mode.
  24218. */
  24219. constructor( blending = NormalBlending ) {
  24220. /**
  24221. * Defines the blending type.
  24222. *
  24223. * It must be set to `CustomBlending` if custom blending properties like
  24224. * {@link BlendMode#blendSrc}, {@link BlendMode#blendDst} or {@link BlendMode#blendEquation}
  24225. * should have any effect.
  24226. *
  24227. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending|MaterialBlending)}
  24228. * @default NormalBlending
  24229. */
  24230. this.blending = blending;
  24231. /**
  24232. * Defines the blending source factor.
  24233. *
  24234. * This determines how the source (incoming) fragment color is factored before being added
  24235. * to the destination (existing) fragment color in the frame buffer.
  24236. *
  24237. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  24238. * @default SrcAlphaFactor
  24239. */
  24240. this.blendSrc = SrcAlphaFactor;
  24241. /**
  24242. * Defines the blending destination factor.
  24243. *
  24244. * This determines how the destination (existing) fragment color in the frame buffer
  24245. * is factored before being combined with the source (incoming) fragment color.
  24246. *
  24247. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  24248. * @default OneMinusSrcAlphaFactor
  24249. */
  24250. this.blendDst = OneMinusSrcAlphaFactor;
  24251. /**
  24252. * Defines the blending equation.
  24253. *
  24254. * This determines how the source and destination colors are combined.
  24255. *
  24256. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  24257. * @default AddEquation
  24258. */
  24259. this.blendEquation = AddEquation;
  24260. /**
  24261. * Defines the blending source alpha factor.
  24262. *
  24263. * When set, this allows separate control of the alpha channel's source blending factor.
  24264. * If `null`, {@link BlendMode#blendSrc} is used for the alpha channel as well.
  24265. *
  24266. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  24267. * @default null
  24268. */
  24269. this.blendSrcAlpha = null;
  24270. /**
  24271. * Defines the blending destination alpha factor.
  24272. *
  24273. * When set, this allows separate control of the alpha channel's destination blending factor.
  24274. * If `null`, {@link BlendMode#blendDst} is used for the alpha channel as well.
  24275. *
  24276. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  24277. * @default null
  24278. */
  24279. this.blendDstAlpha = null;
  24280. /**
  24281. * Defines the blending equation of the alpha channel.
  24282. *
  24283. * When set, this allows separate control of the alpha channel's blending equation.
  24284. * If `null`, {@link BlendMode#blendEquation} is used for the alpha channel as well.
  24285. *
  24286. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  24287. * @default null
  24288. */
  24289. this.blendEquationAlpha = null;
  24290. /**
  24291. * Defines whether to premultiply the alpha (transparency) value.
  24292. *
  24293. * If `true`, the RGB color of the texture or material is multiplied by its alpha value.
  24294. * This is useful for transparent textures/materials where the color data
  24295. * should already include the transparency information.
  24296. *
  24297. * @type {boolean}
  24298. * @default false
  24299. */
  24300. this.premultiplyAlpha = false;
  24301. }
  24302. /**
  24303. * Copies the blending properties from the given source to this instance.
  24304. *
  24305. * @param {BlendMode} source - The blending configuration to copy from.
  24306. * @return {BlendMode} A reference to this instance.
  24307. */
  24308. copy( source ) {
  24309. this.blending = source.blending;
  24310. this.blendSrc = source.blendSrc;
  24311. this.blendDst = source.blendDst;
  24312. this.blendEquation = source.blendEquation;
  24313. this.blendSrcAlpha = source.blendSrcAlpha;
  24314. this.blendDstAlpha = source.blendDstAlpha;
  24315. this.blendEquationAlpha = source.blendEquationAlpha;
  24316. this.premultiplyAlpha = source.premultiplyAlpha;
  24317. return this;
  24318. }
  24319. /**
  24320. * Returns a clone of this blending configuration.
  24321. *
  24322. * @return {BlendMode} A new Blending instance with the same properties.
  24323. */
  24324. clone() {
  24325. return new this.constructor().copy( this );
  24326. }
  24327. }
  24328. // Predefined blend modes for MRT nodes.
  24329. const _noBlending = /**@__PURE__*/ new BlendMode( NoBlending );
  24330. const _materialBlending = /**@__PURE__*/ new BlendMode( MaterialBlending );
  24331. /**
  24332. * Returns the MRT texture index for the given name.
  24333. *
  24334. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  24335. * @param {string} name - The name of the MRT texture which index is requested.
  24336. * @return {number} The texture index.
  24337. */
  24338. function getTextureIndex( textures, name ) {
  24339. for ( let i = 0; i < textures.length; i ++ ) {
  24340. if ( textures[ i ].name === name ) {
  24341. return i;
  24342. }
  24343. }
  24344. return -1;
  24345. }
  24346. /**
  24347. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  24348. * post-processing is shown below:
  24349. * ```js
  24350. * const mrtNode = mrt( {
  24351. * output: output,
  24352. * normal: normalView
  24353. * } ) ;
  24354. * ```
  24355. * The MRT output is defined as a dictionary.
  24356. *
  24357. * @augments OutputStructNode
  24358. */
  24359. class MRTNode extends OutputStructNode {
  24360. static get type() {
  24361. return 'MRTNode';
  24362. }
  24363. /**
  24364. * Constructs a new output struct node.
  24365. *
  24366. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  24367. */
  24368. constructor( outputNodes ) {
  24369. super();
  24370. /**
  24371. * A dictionary representing the MRT outputs. The key
  24372. * is the name of the output, the value the node which produces
  24373. * the output result.
  24374. *
  24375. * @type {Object<string, Node>}
  24376. */
  24377. this.outputNodes = outputNodes;
  24378. /**
  24379. * A dictionary storing the blend modes for each output.
  24380. *
  24381. * @type {Object<string, BlendMode>}
  24382. */
  24383. this.blendModes = {
  24384. output: _materialBlending
  24385. };
  24386. /**
  24387. * This flag can be used for type testing.
  24388. *
  24389. * @type {boolean}
  24390. * @readonly
  24391. * @default true
  24392. */
  24393. this.isMRTNode = true;
  24394. }
  24395. /**
  24396. * Sets the blend mode for the given output name.
  24397. *
  24398. * @param {string} name - The name of the output.
  24399. * @param {BlendMode} blend - The blending mode.
  24400. * @return {MRTNode} The current MRT node.
  24401. */
  24402. setBlendMode( name, blend ) {
  24403. this.blendModes[ name ] = blend;
  24404. return this;
  24405. }
  24406. /**
  24407. * Returns the blend mode for the given output name.
  24408. *
  24409. * @param {string} name - The name of the output.
  24410. * @return {BlendMode} The blend mode.
  24411. */
  24412. getBlendMode( name ) {
  24413. return this.blendModes[ name ] || _noBlending;
  24414. }
  24415. /**
  24416. * Returns `true` if the MRT node has an output with the given name.
  24417. *
  24418. * @param {string} name - The name of the output.
  24419. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  24420. */
  24421. has( name ) {
  24422. return this.outputNodes[ name ] !== undefined;
  24423. }
  24424. /**
  24425. * Returns the output node for the given name.
  24426. *
  24427. * @param {string} name - The name of the output.
  24428. * @return {Node} The output node.
  24429. */
  24430. get( name ) {
  24431. return this.outputNodes[ name ];
  24432. }
  24433. /**
  24434. * Merges the outputs of the given MRT node with the outputs of this node.
  24435. *
  24436. * @param {MRTNode} mrtNode - The MRT to merge.
  24437. * @return {MRTNode} A new MRT node with merged outputs..
  24438. */
  24439. merge( mrtNode ) {
  24440. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  24441. const blendings = { ...this.blendModes, ...mrtNode.blendModes };
  24442. const mrtTarget = mrt( outputs );
  24443. mrtTarget.blendings = blendings;
  24444. return mrtTarget;
  24445. }
  24446. setup( builder ) {
  24447. const outputNodes = this.outputNodes;
  24448. const mrt = builder.renderer.getRenderTarget();
  24449. const members = [];
  24450. const textures = mrt.textures;
  24451. for ( const name in outputNodes ) {
  24452. const index = getTextureIndex( textures, name );
  24453. members[ index ] = vec4( outputNodes[ name ] );
  24454. }
  24455. this.members = members;
  24456. return super.setup( builder );
  24457. }
  24458. }
  24459. /**
  24460. * TSL function for creating a MRT node.
  24461. *
  24462. * @tsl
  24463. * @function
  24464. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  24465. * @returns {MRTNode}
  24466. */
  24467. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  24468. /**
  24469. * This node represents an operation that reinterprets the bit representation of a value
  24470. * in one type as a value in another type.
  24471. *
  24472. * @augments TempNode
  24473. */
  24474. class BitcastNode extends TempNode {
  24475. static get type() {
  24476. return 'BitcastNode';
  24477. }
  24478. /**
  24479. * Constructs a new bitcast node.
  24480. *
  24481. * @param {Node} valueNode - The value to convert.
  24482. * @param {string} conversionType - The type to convert to.
  24483. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  24484. */
  24485. constructor( valueNode, conversionType, inputType = null ) {
  24486. super();
  24487. /**
  24488. * The data to bitcast to a new type.
  24489. *
  24490. * @type {Node}
  24491. */
  24492. this.valueNode = valueNode;
  24493. /**
  24494. * The type the value will be converted to.
  24495. *
  24496. * @type {string}
  24497. */
  24498. this.conversionType = conversionType;
  24499. /**
  24500. * The expected input data type of the bitcast operation.
  24501. *
  24502. *
  24503. * @type {string}
  24504. * @default null
  24505. */
  24506. this.inputType = inputType;
  24507. /**
  24508. * This flag can be used for type testing.
  24509. *
  24510. * @type {boolean}
  24511. * @readonly
  24512. * @default true
  24513. */
  24514. this.isBitcastNode = true;
  24515. }
  24516. getNodeType( builder ) {
  24517. // GLSL aliasing
  24518. if ( this.inputType !== null ) {
  24519. const valueType = this.valueNode.getNodeType( builder );
  24520. const valueLength = builder.getTypeLength( valueType );
  24521. return builder.getTypeFromLength( valueLength, this.conversionType );
  24522. }
  24523. return this.conversionType;
  24524. }
  24525. generate( builder ) {
  24526. const type = this.getNodeType( builder );
  24527. let inputType = '';
  24528. if ( this.inputType !== null ) {
  24529. const valueType = this.valueNode.getNodeType( builder );
  24530. const valueTypeLength = builder.getTypeLength( valueType );
  24531. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  24532. } else {
  24533. inputType = this.valueNode.getNodeType( builder );
  24534. }
  24535. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  24536. }
  24537. }
  24538. /**
  24539. * Reinterpret the bit representation of a value in one type as a value in another type.
  24540. *
  24541. * @tsl
  24542. * @function
  24543. * @param {Node | number} x - The parameter.
  24544. * @param {string} y - The new type.
  24545. * @returns {Node}
  24546. */
  24547. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  24548. /**
  24549. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  24550. *
  24551. * @tsl
  24552. * @function
  24553. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24554. * @returns {BitcastNode}
  24555. */
  24556. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  24557. /**
  24558. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  24559. *
  24560. * @tsl
  24561. * @function
  24562. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24563. * @returns {BitcastNode}
  24564. */
  24565. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  24566. /**
  24567. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  24568. *
  24569. * @tsl
  24570. * @function
  24571. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  24572. * @returns {BitcastNode}
  24573. */
  24574. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  24575. /**
  24576. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  24577. *
  24578. * @tsl
  24579. * @function
  24580. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  24581. * @returns {BitcastNode}
  24582. */
  24583. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  24584. const registeredBitcountFunctions = {};
  24585. /**
  24586. * This node represents an operation that counts the bits of a piece of shader data.
  24587. *
  24588. * @augments MathNode
  24589. */
  24590. class BitcountNode extends MathNode {
  24591. static get type() {
  24592. return 'BitcountNode';
  24593. }
  24594. /**
  24595. * Constructs a new math node.
  24596. *
  24597. * @param {'countTrailingZeros'|'countLeadingZeros'|'countOneBits'} method - The method name.
  24598. * @param {Node} aNode - The first input.
  24599. */
  24600. constructor( method, aNode ) {
  24601. super( method, aNode );
  24602. /**
  24603. * This flag can be used for type testing.
  24604. *
  24605. * @type {boolean}
  24606. * @readonly
  24607. * @default true
  24608. */
  24609. this.isBitcountNode = true;
  24610. }
  24611. /**
  24612. * Casts the input value of the function to an integer if necessary.
  24613. *
  24614. * @private
  24615. * @param {Node<uint>|Node<int>} inputNode - The input value.
  24616. * @param {Node<uint>} outputNode - The output value.
  24617. * @param {string} elementType - The type of the input value.
  24618. */
  24619. _resolveElementType( inputNode, outputNode, elementType ) {
  24620. if ( elementType === 'int' ) {
  24621. outputNode.assign( bitcast( inputNode, 'uint' ) );
  24622. } else {
  24623. outputNode.assign( inputNode );
  24624. }
  24625. }
  24626. _returnDataNode( inputType ) {
  24627. switch ( inputType ) {
  24628. case 'uint': {
  24629. return uint;
  24630. }
  24631. case 'int': {
  24632. return int;
  24633. }
  24634. case 'uvec2': {
  24635. return uvec2;
  24636. }
  24637. case 'uvec3': {
  24638. return uvec3;
  24639. }
  24640. case 'uvec4': {
  24641. return uvec4;
  24642. }
  24643. case 'ivec2': {
  24644. return ivec2;
  24645. }
  24646. case 'ivec3': {
  24647. return ivec3;
  24648. }
  24649. case 'ivec4': {
  24650. return ivec4;
  24651. }
  24652. }
  24653. }
  24654. /**
  24655. * Creates and registers a reusable GLSL function that emulates the behavior of countTrailingZeros.
  24656. *
  24657. * @private
  24658. * @param {string} method - The name of the function to create.
  24659. * @param {string} elementType - The type of the input value.
  24660. * @returns {Function} - The generated function
  24661. */
  24662. _createTrailingZerosBaseLayout( method, elementType ) {
  24663. const outputConvertNode = this._returnDataNode( elementType );
  24664. const fnDef = Fn( ( [ value ] ) => {
  24665. const v = uint( 0.0 );
  24666. this._resolveElementType( value, v, elementType );
  24667. const f = float( v.bitAnd( negate( v ) ) );
  24668. const uintBits = floatBitsToUint( f );
  24669. const numTrailingZeros = ( uintBits.shiftRight( 23 ) ).sub( 127 );
  24670. return outputConvertNode( numTrailingZeros );
  24671. } ).setLayout( {
  24672. name: method,
  24673. type: elementType,
  24674. inputs: [
  24675. { name: 'value', type: elementType }
  24676. ]
  24677. } );
  24678. return fnDef;
  24679. }
  24680. /**
  24681. * Creates and registers a reusable GLSL function that emulates the behavior of countLeadingZeros.
  24682. *
  24683. * @private
  24684. * @param {string} method - The name of the function to create.
  24685. * @param {string} elementType - The type of the input value.
  24686. * @returns {Function} - The generated function
  24687. */
  24688. _createLeadingZerosBaseLayout( method, elementType ) {
  24689. const outputConvertNode = this._returnDataNode( elementType );
  24690. const fnDef = Fn( ( [ value ] ) => {
  24691. If( value.equal( uint( 0 ) ), () => {
  24692. return uint( 32 );
  24693. } );
  24694. const v = uint( 0 );
  24695. const n = uint( 0 );
  24696. this._resolveElementType( value, v, elementType );
  24697. If( v.shiftRight( 16 ).equal( 0 ), () => {
  24698. n.addAssign( 16 );
  24699. v.shiftLeftAssign( 16 );
  24700. } );
  24701. If( v.shiftRight( 24 ).equal( 0 ), () => {
  24702. n.addAssign( 8 );
  24703. v.shiftLeftAssign( 8 );
  24704. } );
  24705. If( v.shiftRight( 28 ).equal( 0 ), () => {
  24706. n.addAssign( 4 );
  24707. v.shiftLeftAssign( 4 );
  24708. } );
  24709. If( v.shiftRight( 30 ).equal( 0 ), () => {
  24710. n.addAssign( 2 );
  24711. v.shiftLeftAssign( 2 );
  24712. } );
  24713. If( v.shiftRight( 31 ).equal( 0 ), () => {
  24714. n.addAssign( 1 );
  24715. } );
  24716. return outputConvertNode( n );
  24717. } ).setLayout( {
  24718. name: method,
  24719. type: elementType,
  24720. inputs: [
  24721. { name: 'value', type: elementType }
  24722. ]
  24723. } );
  24724. return fnDef;
  24725. }
  24726. /**
  24727. * Creates and registers a reusable GLSL function that emulates the behavior of countOneBits.
  24728. *
  24729. * @private
  24730. * @param {string} method - The name of the function to create.
  24731. * @param {string} elementType - The type of the input value.
  24732. * @returns {Function} - The generated function
  24733. */
  24734. _createOneBitsBaseLayout( method, elementType ) {
  24735. const outputConvertNode = this._returnDataNode( elementType );
  24736. const fnDef = Fn( ( [ value ] ) => {
  24737. const v = uint( 0.0 );
  24738. this._resolveElementType( value, v, elementType );
  24739. v.assign( v.sub( v.shiftRight( uint( 1 ) ).bitAnd( uint( 0x55555555 ) ) ) );
  24740. v.assign( v.bitAnd( uint( 0x33333333 ) ).add( v.shiftRight( uint( 2 ) ).bitAnd( uint( 0x33333333 ) ) ) );
  24741. const numBits = v.add( v.shiftRight( uint( 4 ) ) ).bitAnd( uint( 0xF0F0F0F ) ).mul( uint( 0x1010101 ) ).shiftRight( uint( 24 ) );
  24742. return outputConvertNode( numBits );
  24743. } ).setLayout( {
  24744. name: method,
  24745. type: elementType,
  24746. inputs: [
  24747. { name: 'value', type: elementType }
  24748. ]
  24749. } );
  24750. return fnDef;
  24751. }
  24752. /**
  24753. * Creates and registers a reusable GLSL function that emulates the behavior of the specified bitcount function.
  24754. * including considerations for component-wise bitcounts on vector type inputs.
  24755. *
  24756. * @private
  24757. * @param {string} method - The name of the function to create.
  24758. * @param {string} inputType - The type of the input value.
  24759. * @param {number} typeLength - The vec length of the input value.
  24760. * @param {Function} baseFn - The base function that operates on an individual component of the vector.
  24761. * @returns {Function} - The alias function for the specified bitcount method.
  24762. */
  24763. _createMainLayout( method, inputType, typeLength, baseFn ) {
  24764. const outputConvertNode = this._returnDataNode( inputType );
  24765. const fnDef = Fn( ( [ value ] ) => {
  24766. if ( typeLength === 1 ) {
  24767. return outputConvertNode( baseFn( value ) );
  24768. } else {
  24769. const vec = outputConvertNode( 0 );
  24770. const components = [ 'x', 'y', 'z', 'w' ];
  24771. for ( let i = 0; i < typeLength; i ++ ) {
  24772. const component = components[ i ];
  24773. vec[ component ].assign( baseFn( value[ component ] ) );
  24774. }
  24775. return vec;
  24776. }
  24777. } ).setLayout( {
  24778. name: method,
  24779. type: inputType,
  24780. inputs: [
  24781. { name: 'value', type: inputType }
  24782. ]
  24783. } );
  24784. return fnDef;
  24785. }
  24786. setup( builder ) {
  24787. const { method, aNode } = this;
  24788. const { renderer } = builder;
  24789. if ( renderer.backend.isWebGPUBackend ) {
  24790. // use built-in WGSL functions for WebGPU
  24791. return super.setup( builder );
  24792. }
  24793. const inputType = this.getInputType( builder );
  24794. const elementType = builder.getElementType( inputType );
  24795. const typeLength = builder.getTypeLength( inputType );
  24796. const baseMethod = `${method}_base_${elementType}`;
  24797. const newMethod = `${method}_${inputType}`;
  24798. let baseFn = registeredBitcountFunctions[ baseMethod ];
  24799. if ( baseFn === undefined ) {
  24800. switch ( method ) {
  24801. case BitcountNode.COUNT_LEADING_ZEROS: {
  24802. baseFn = this._createLeadingZerosBaseLayout( baseMethod, elementType );
  24803. break;
  24804. }
  24805. case BitcountNode.COUNT_TRAILING_ZEROS: {
  24806. baseFn = this._createTrailingZerosBaseLayout( baseMethod, elementType );
  24807. break;
  24808. }
  24809. case BitcountNode.COUNT_ONE_BITS: {
  24810. baseFn = this._createOneBitsBaseLayout( baseMethod, elementType );
  24811. break;
  24812. }
  24813. }
  24814. registeredBitcountFunctions[ baseMethod ] = baseFn;
  24815. }
  24816. let fn = registeredBitcountFunctions[ newMethod ];
  24817. if ( fn === undefined ) {
  24818. fn = this._createMainLayout( newMethod, inputType, typeLength, baseFn );
  24819. registeredBitcountFunctions[ newMethod ] = fn;
  24820. }
  24821. const output = Fn( () => {
  24822. return fn(
  24823. aNode,
  24824. );
  24825. } );
  24826. return output();
  24827. }
  24828. }
  24829. BitcountNode.COUNT_TRAILING_ZEROS = 'countTrailingZeros';
  24830. BitcountNode.COUNT_LEADING_ZEROS = 'countLeadingZeros';
  24831. BitcountNode.COUNT_ONE_BITS = 'countOneBits';
  24832. /**
  24833. * Finds the number of consecutive 0 bits from the least significant bit of the input value,
  24834. * which is also the index of the least significant bit of the input value.
  24835. *
  24836. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24837. *
  24838. * @tsl
  24839. * @function
  24840. * @param {Node | number} x - The input value.
  24841. * @returns {Node}
  24842. */
  24843. const countTrailingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_TRAILING_ZEROS ).setParameterLength( 1 );
  24844. /**
  24845. * Finds the number of consecutive 0 bits starting from the most significant bit of the input value.
  24846. *
  24847. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24848. *
  24849. * @tsl
  24850. * @function
  24851. * @param {Node | number} x - The input value.
  24852. * @returns {Node}
  24853. */
  24854. const countLeadingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_LEADING_ZEROS ).setParameterLength( 1 );
  24855. /**
  24856. * Finds the number of '1' bits set in the input value
  24857. *
  24858. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24859. *
  24860. * @tsl
  24861. * @function
  24862. * @returns {Node}
  24863. */
  24864. const countOneBits = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_ONE_BITS ).setParameterLength( 1 );
  24865. /**
  24866. * Generates a hash value in the range `[0, 1]` from the given seed.
  24867. *
  24868. * @tsl
  24869. * @function
  24870. * @param {Node<float>} seed - The seed.
  24871. * @return {Node<float>} The hash value.
  24872. */
  24873. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  24874. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  24875. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  24876. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  24877. const result = word.shiftRight( 22 ).bitXor( word );
  24878. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  24879. } );
  24880. /**
  24881. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24882. * The corners are mapped to `0` and the center to `1`.
  24883. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24884. *
  24885. * @tsl
  24886. * @function
  24887. * @param {Node<float>} x - The value to remap.
  24888. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  24889. * @return {Node<float>} The remapped value.
  24890. */
  24891. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  24892. /**
  24893. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24894. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  24895. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24896. *
  24897. * @tsl
  24898. * @function
  24899. * @param {Node<float>} x - The value to remap.
  24900. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  24901. * @return {Node<float>} The remapped value.
  24902. */
  24903. 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 ) );
  24904. /**
  24905. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24906. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  24907. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24908. *
  24909. * @tsl
  24910. * @function
  24911. * @param {Node<float>} x - The value to remap.
  24912. * @param {Node<float>} a - First control parameter.
  24913. * @param {Node<float>} b - Second control parameter.
  24914. * @return {Node<float>} The remapped value.
  24915. */
  24916. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  24917. /**
  24918. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  24919. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24920. *
  24921. * @tsl
  24922. * @function
  24923. * @param {Node<float>} x - The value to compute the sin for.
  24924. * @param {Node<float>} k - Controls the amount of bounces.
  24925. * @return {Node<float>} The result value.
  24926. */
  24927. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  24928. /**
  24929. * This node represents an operation that packs floating-point values of a vector into an unsigned 32-bit integer
  24930. *
  24931. * @augments TempNode
  24932. */
  24933. class PackFloatNode extends TempNode {
  24934. static get type() {
  24935. return 'PackFloatNode';
  24936. }
  24937. /**
  24938. *
  24939. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  24940. * @param {Node} vectorNode - The vector node to be packed
  24941. */
  24942. constructor( encoding, vectorNode ) {
  24943. super();
  24944. /**
  24945. * The vector to be packed.
  24946. *
  24947. * @type {Node}
  24948. */
  24949. this.vectorNode = vectorNode;
  24950. /**
  24951. * The numeric encoding.
  24952. *
  24953. * @type {string}
  24954. */
  24955. this.encoding = encoding;
  24956. /**
  24957. * This flag can be used for type testing.
  24958. *
  24959. * @type {boolean}
  24960. * @readonly
  24961. * @default true
  24962. */
  24963. this.isPackFloatNode = true;
  24964. }
  24965. getNodeType() {
  24966. return 'uint';
  24967. }
  24968. generate( builder ) {
  24969. const inputType = this.vectorNode.getNodeType( builder );
  24970. return `${ builder.getFloatPackingMethod( this.encoding ) }(${ this.vectorNode.build( builder, inputType )})`;
  24971. }
  24972. }
  24973. /**
  24974. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  24975. * round(clamp(c, -1, +1) * 32767.0)
  24976. *
  24977. * @tsl
  24978. * @function
  24979. * @param {Node<vec2>} value - The 2-component vector to be packed
  24980. * @returns {Node}
  24981. */
  24982. const packSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'snorm' ).setParameterLength( 1 );
  24983. /**
  24984. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  24985. * round(clamp(c, 0, +1) * 65535.0)
  24986. *
  24987. * @tsl
  24988. * @function
  24989. * @param {Node<vec2>} value - The 2-component vector to be packed
  24990. * @returns {Node}
  24991. */
  24992. const packUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'unorm' ).setParameterLength( 1 );
  24993. /**
  24994. * Converts each component of the vec2 to 16-bit floating-point values. The results are packed into a single unsigned integer.
  24995. *
  24996. * @tsl
  24997. * @function
  24998. * @param {Node<vec2>} value - The 2-component vector to be packed
  24999. * @returns {Node}
  25000. */
  25001. const packHalf2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'float16' ).setParameterLength( 1 );
  25002. /**
  25003. * This node represents an operation that unpacks values from a 32-bit unsigned integer, reinterpreting the results as a floating-point vector
  25004. *
  25005. * @augments TempNode
  25006. */
  25007. class UnpackFloatNode extends TempNode {
  25008. static get type() {
  25009. return 'UnpackFloatNode';
  25010. }
  25011. /**
  25012. *
  25013. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the integer values are mapped to the float range
  25014. * @param {Node} uintNode - The uint node to be unpacked
  25015. */
  25016. constructor( encoding, uintNode ) {
  25017. super();
  25018. /**
  25019. * The unsigned integer to be unpacked.
  25020. *
  25021. * @type {Node}
  25022. */
  25023. this.uintNode = uintNode;
  25024. /**
  25025. * The numeric encoding.
  25026. *
  25027. * @type {string}
  25028. */
  25029. this.encoding = encoding;
  25030. /**
  25031. * This flag can be used for type testing.
  25032. *
  25033. * @type {boolean}
  25034. * @readonly
  25035. * @default true
  25036. */
  25037. this.isUnpackFloatNode = true;
  25038. }
  25039. getNodeType() {
  25040. return 'vec2';
  25041. }
  25042. generate( builder ) {
  25043. const inputType = this.uintNode.getNodeType( builder );
  25044. return `${ builder.getFloatUnpackingMethod( this.encoding ) }(${ this.uintNode.build( builder, inputType )})`;
  25045. }
  25046. }
  25047. /**
  25048. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized signed integers. Returns a vec2 with both values.
  25049. *
  25050. * @tsl
  25051. * @function
  25052. * @param {Node<uint>} value - The unsigned integer to be unpacked
  25053. * @returns {Node}
  25054. */
  25055. const unpackSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'snorm' ).setParameterLength( 1 );
  25056. /**
  25057. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized unsigned integers. Returns a vec2 with both values.
  25058. *
  25059. * @tsl
  25060. * @function
  25061. * @param {Node<uint>} value - The unsigned integer to be unpacked
  25062. * @returns {Node}
  25063. */
  25064. const unpackUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'unorm' ).setParameterLength( 1 );
  25065. /**
  25066. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as 16-bit floating-point numbers. Returns a vec2 with both values.
  25067. *
  25068. * @tsl
  25069. * @function
  25070. * @param {Node<uint>} value - The unsigned integer to be unpacked
  25071. * @returns {Node}
  25072. */
  25073. const unpackHalf2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'float16' ).setParameterLength( 1 );
  25074. // https://github.com/cabbibo/glsl-tri-noise-3d
  25075. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  25076. return x.fract().sub( .5 ).abs();
  25077. } ).setLayout( {
  25078. name: 'tri',
  25079. type: 'float',
  25080. inputs: [
  25081. { name: 'x', type: 'float' }
  25082. ]
  25083. } );
  25084. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  25085. 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. ) ) ) ) );
  25086. } ).setLayout( {
  25087. name: 'tri3',
  25088. type: 'vec3',
  25089. inputs: [
  25090. { name: 'p', type: 'vec3' }
  25091. ]
  25092. } );
  25093. /**
  25094. * Generates a noise value from the given position, speed and time parameters.
  25095. *
  25096. * @tsl
  25097. * @function
  25098. * @param {Node<vec3>} position - The position.
  25099. * @param {Node<float>} speed - The speed.
  25100. * @param {Node<float>} time - The time.
  25101. * @return {Node<float>} The generated noise.
  25102. */
  25103. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  25104. const p = vec3( position ).toVar();
  25105. const z = float( 1.4 ).toVar();
  25106. const rz = float( 0.0 ).toVar();
  25107. const bp = vec3( p ).toVar();
  25108. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  25109. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  25110. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  25111. bp.mulAssign( 1.8 );
  25112. z.mulAssign( 1.5 );
  25113. p.mulAssign( 1.2 );
  25114. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  25115. rz.addAssign( t.div( z ) );
  25116. bp.addAssign( 0.14 );
  25117. } );
  25118. return rz;
  25119. } ).setLayout( {
  25120. name: 'triNoise3D',
  25121. type: 'float',
  25122. inputs: [
  25123. { name: 'position', type: 'vec3' },
  25124. { name: 'speed', type: 'float' },
  25125. { name: 'time', type: 'float' }
  25126. ]
  25127. } );
  25128. /**
  25129. * This class allows to define multiple overloaded versions
  25130. * of the same function. Depending on the parameters of the function
  25131. * call, the node picks the best-fit overloaded version.
  25132. *
  25133. * @augments Node
  25134. */
  25135. class FunctionOverloadingNode extends Node {
  25136. static get type() {
  25137. return 'FunctionOverloadingNode';
  25138. }
  25139. /**
  25140. * Constructs a new function overloading node.
  25141. *
  25142. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  25143. * @param {...Node} parametersNodes - A list of parameter nodes.
  25144. */
  25145. constructor( functionNodes = [], ...parametersNodes ) {
  25146. super();
  25147. /**
  25148. * Array of `Fn` function definitions.
  25149. *
  25150. * @type {Array<Function>}
  25151. */
  25152. this.functionNodes = functionNodes;
  25153. /**
  25154. * A list of parameter nodes.
  25155. *
  25156. * @type {Array<Node>}
  25157. */
  25158. this.parametersNodes = parametersNodes;
  25159. /**
  25160. * The selected overloaded function call.
  25161. *
  25162. * @private
  25163. * @type {ShaderCallNodeInternal}
  25164. */
  25165. this._candidateFn = null;
  25166. /**
  25167. * This node is marked as global.
  25168. *
  25169. * @type {boolean}
  25170. * @default true
  25171. */
  25172. this.global = true;
  25173. }
  25174. /**
  25175. * This method is overwritten since the node type is inferred from
  25176. * the function's return type.
  25177. *
  25178. * @param {NodeBuilder} builder - The current node builder.
  25179. * @return {string} The node type.
  25180. */
  25181. getNodeType( builder ) {
  25182. const candidateFn = this.getCandidateFn( builder );
  25183. return candidateFn.shaderNode.layout.type;
  25184. }
  25185. /**
  25186. * Returns the candidate function for the current parameters.
  25187. *
  25188. * @param {NodeBuilder} builder - The current node builder.
  25189. * @return {FunctionNode} The candidate function.
  25190. */
  25191. getCandidateFn( builder ) {
  25192. const params = this.parametersNodes;
  25193. let candidateFn = this._candidateFn;
  25194. if ( candidateFn === null ) {
  25195. let bestCandidateFn = null;
  25196. let bestScore = -1;
  25197. for ( const functionNode of this.functionNodes ) {
  25198. const shaderNode = functionNode.shaderNode;
  25199. const layout = shaderNode.layout;
  25200. if ( layout === null ) {
  25201. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  25202. }
  25203. const inputs = layout.inputs;
  25204. if ( params.length === inputs.length ) {
  25205. let currentScore = 0;
  25206. for ( let i = 0; i < params.length; i ++ ) {
  25207. const param = params[ i ];
  25208. const input = inputs[ i ];
  25209. if ( param.getNodeType( builder ) === input.type ) {
  25210. currentScore ++;
  25211. }
  25212. }
  25213. if ( currentScore > bestScore ) {
  25214. bestCandidateFn = functionNode;
  25215. bestScore = currentScore;
  25216. }
  25217. }
  25218. }
  25219. this._candidateFn = candidateFn = bestCandidateFn;
  25220. }
  25221. return candidateFn;
  25222. }
  25223. /**
  25224. * Sets up the node for the current parameters.
  25225. *
  25226. * @param {NodeBuilder} builder - The current node builder.
  25227. * @return {Node} The setup node.
  25228. */
  25229. setup( builder ) {
  25230. const candidateFn = this.getCandidateFn( builder );
  25231. return candidateFn( ...this.parametersNodes );
  25232. }
  25233. }
  25234. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  25235. /**
  25236. * TSL function for creating a function overloading node.
  25237. *
  25238. * @tsl
  25239. * @function
  25240. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  25241. * @returns {FunctionOverloadingNode}
  25242. */
  25243. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  25244. /**
  25245. * Represents the elapsed time in seconds.
  25246. *
  25247. * @tsl
  25248. * @type {UniformNode<float>}
  25249. */
  25250. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  25251. /**
  25252. * Represents the delta time in seconds.
  25253. *
  25254. * @tsl
  25255. * @type {UniformNode<float>}
  25256. */
  25257. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  25258. /**
  25259. * Represents the current frame ID.
  25260. *
  25261. * @tsl
  25262. * @type {UniformNode<uint>}
  25263. */
  25264. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  25265. /**
  25266. * Generates a sine wave oscillation based on a timer.
  25267. *
  25268. * @tsl
  25269. * @function
  25270. * @param {Node<float>} t - The timer to generate the oscillation with.
  25271. * @return {Node<float>} The oscillation node.
  25272. */
  25273. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  25274. /**
  25275. * Generates a square wave oscillation based on a timer.
  25276. *
  25277. * @tsl
  25278. * @function
  25279. * @param {Node<float>} t - The timer to generate the oscillation with.
  25280. * @return {Node<float>} The oscillation node.
  25281. */
  25282. const oscSquare = ( t = time ) => t.fract().round();
  25283. /**
  25284. * Generates a triangle wave oscillation based on a timer.
  25285. *
  25286. * @tsl
  25287. * @function
  25288. * @param {Node<float>} t - The timer to generate the oscillation with.
  25289. * @return {Node<float>} The oscillation node.
  25290. */
  25291. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  25292. /**
  25293. * Generates a sawtooth wave oscillation based on a timer.
  25294. *
  25295. * @tsl
  25296. * @function
  25297. * @param {Node<float>} t - The timer to generate the oscillation with.
  25298. * @return {Node<float>} The oscillation node.
  25299. */
  25300. const oscSawtooth = ( t = time ) => t.fract();
  25301. /**
  25302. * Replaces the default UV coordinates used in texture lookups.
  25303. *
  25304. * ```js
  25305. *material.contextNode = replaceDefaultUV( ( textureNode ) => {
  25306. *
  25307. * // ...
  25308. * return customUVCoordinates;
  25309. *
  25310. *} );
  25311. *```
  25312. *
  25313. * @tsl
  25314. * @function
  25315. * @param {function(Node):Node<vec2>|Node<vec2>} callback - A callback that receives the texture node
  25316. * and must return the new uv coordinates.
  25317. * @param {Node} [node=null] - An optional node to which the context will be applied.
  25318. * @return {ContextNode} A context node that replaces the default UV coordinates.
  25319. */
  25320. function replaceDefaultUV( callback, node = null ) {
  25321. const getUV = typeof callback === 'function' ? callback : () => callback;
  25322. return context( node, { getUV } );
  25323. }
  25324. /**
  25325. * Rotates the given uv coordinates around a center point
  25326. *
  25327. * @tsl
  25328. * @function
  25329. * @param {Node<vec2>} uv - The uv coordinates.
  25330. * @param {Node<float>} rotation - The rotation defined in radians.
  25331. * @param {Node<vec2>} center - The center of rotation
  25332. * @return {Node<vec2>} The rotated uv coordinates.
  25333. */
  25334. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  25335. return rotate( uv.sub( center ), rotation ).add( center );
  25336. } );
  25337. /**
  25338. * Applies a spherical warping effect to the given uv coordinates.
  25339. *
  25340. * @tsl
  25341. * @function
  25342. * @param {Node<vec2>} uv - The uv coordinates.
  25343. * @param {Node<float>} strength - The strength of the effect.
  25344. * @param {Node<vec2>} center - The center point
  25345. * @return {Node<vec2>} The updated uv coordinates.
  25346. */
  25347. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  25348. const delta = uv.sub( center );
  25349. const delta2 = delta.dot( delta );
  25350. const delta4 = delta2.mul( delta2 );
  25351. const deltaOffset = delta4.mul( strength );
  25352. return uv.add( delta.mul( deltaOffset ) );
  25353. } );
  25354. /**
  25355. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  25356. * oriented always towards the camera.
  25357. *
  25358. * ```js
  25359. * material.vertexNode = billboarding();
  25360. * ```
  25361. *
  25362. * @tsl
  25363. * @function
  25364. * @param {Object} config - The configuration object.
  25365. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  25366. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  25367. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  25368. * @return {Node<vec3>} The updated vertex position in clip space.
  25369. */
  25370. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  25371. let worldMatrix;
  25372. if ( position !== null ) {
  25373. worldMatrix = modelWorldMatrix.toVar();
  25374. worldMatrix[ 3 ][ 0 ] = position.x;
  25375. worldMatrix[ 3 ][ 1 ] = position.y;
  25376. worldMatrix[ 3 ][ 2 ] = position.z;
  25377. } else {
  25378. worldMatrix = modelWorldMatrix;
  25379. }
  25380. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  25381. if ( defined( horizontal ) ) {
  25382. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  25383. modelViewMatrix[ 0 ][ 1 ] = 0;
  25384. modelViewMatrix[ 0 ][ 2 ] = 0;
  25385. }
  25386. if ( defined( vertical ) ) {
  25387. modelViewMatrix[ 1 ][ 0 ] = 0;
  25388. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  25389. modelViewMatrix[ 1 ][ 2 ] = 0;
  25390. }
  25391. modelViewMatrix[ 2 ][ 0 ] = 0;
  25392. modelViewMatrix[ 2 ][ 1 ] = 0;
  25393. modelViewMatrix[ 2 ][ 2 ] = 1;
  25394. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  25395. } );
  25396. /**
  25397. * A special version of a screen uv function that involves a depth comparison
  25398. * when computing the final uvs. The function mitigates visual errors when
  25399. * using viewport texture nodes for refraction purposes. Without this function
  25400. * objects in front of a refractive surface might appear on the refractive surface
  25401. * which is incorrect.
  25402. *
  25403. * @tsl
  25404. * @function
  25405. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  25406. * @return {Node<vec2>} The update uv coordinates.
  25407. */
  25408. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  25409. const depth = linearDepth();
  25410. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  25411. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  25412. return finalUV;
  25413. } );
  25414. /**
  25415. * TSL function for computing texture coordinates for animated sprite sheets.
  25416. *
  25417. * ```js
  25418. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  25419. *
  25420. * material.colorNode = texture( spriteSheet, uvNode );
  25421. * ```
  25422. *
  25423. * @tsl
  25424. * @function
  25425. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  25426. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  25427. * @param {?Node<float>} [frameNode=float(0)] - The node that defines the current frame/sprite.
  25428. * @returns {Node<vec2>}
  25429. */
  25430. const spritesheetUV = /*@__PURE__*/ Fn( ( [ countNode, uvNode = uv$1(), frameNode = float( 0 ) ] ) => {
  25431. const width = countNode.x;
  25432. const height = countNode.y;
  25433. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  25434. const column = frameNum.mod( width );
  25435. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  25436. const scale = countNode.reciprocal();
  25437. const uvFrameOffset = vec2( column, row );
  25438. return uvNode.add( uvFrameOffset ).mul( scale );
  25439. } );
  25440. /**
  25441. * TSL function for creating a triplanar textures node.
  25442. *
  25443. * Can be used for triplanar texture mapping.
  25444. *
  25445. * ```js
  25446. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  25447. * ```
  25448. *
  25449. * @tsl
  25450. * @function
  25451. * @param {Node} textureXNode - First texture node.
  25452. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  25453. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  25454. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  25455. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  25456. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  25457. * @returns {Node<vec4>}
  25458. */
  25459. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  25460. // Reference: https://github.com/keijiro/StandardTriplanar
  25461. // Blending factor of triplanar mapping
  25462. let bf = normalNode.abs().normalize();
  25463. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  25464. // Triplanar mapping
  25465. const tx = positionNode.yz.mul( scaleNode );
  25466. const ty = positionNode.zx.mul( scaleNode );
  25467. const tz = positionNode.xy.mul( scaleNode );
  25468. // Base color
  25469. const textureX = textureXNode.value;
  25470. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  25471. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  25472. const cx = texture( textureX, tx ).mul( bf.x );
  25473. const cy = texture( textureY, ty ).mul( bf.y );
  25474. const cz = texture( textureZ, tz ).mul( bf.z );
  25475. return add( cx, cy, cz );
  25476. } );
  25477. /**
  25478. * TSL function for creating a triplanar textures node.
  25479. *
  25480. * @tsl
  25481. * @function
  25482. * @param {Node} textureXNode - First texture node.
  25483. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  25484. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  25485. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  25486. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  25487. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  25488. * @returns {Node<vec4>}
  25489. */
  25490. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  25491. const _reflectorPlane = new Plane();
  25492. const _normal = new Vector3();
  25493. const _reflectorWorldPosition = new Vector3();
  25494. const _cameraWorldPosition = new Vector3();
  25495. const _rotationMatrix = new Matrix4();
  25496. const _lookAtPosition = new Vector3( 0, 0, -1 );
  25497. const clipPlane = new Vector4();
  25498. const _view = new Vector3();
  25499. const _target = new Vector3();
  25500. const _q = new Vector4();
  25501. const _size$2 = new Vector2();
  25502. const _defaultRT = new RenderTarget();
  25503. const _defaultUV = screenUV.flipX();
  25504. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  25505. let _inReflector = false;
  25506. /**
  25507. * This node can be used to implement mirror-like flat reflective surfaces.
  25508. *
  25509. * ```js
  25510. * const groundReflector = reflector();
  25511. * material.colorNode = groundReflector;
  25512. *
  25513. * const plane = new Mesh( geometry, material );
  25514. * plane.add( groundReflector.target );
  25515. * ```
  25516. *
  25517. * @augments TextureNode
  25518. */
  25519. class ReflectorNode extends TextureNode {
  25520. static get type() {
  25521. return 'ReflectorNode';
  25522. }
  25523. /**
  25524. * Constructs a new reflector node.
  25525. *
  25526. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25527. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25528. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  25529. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25530. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25531. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25532. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25533. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  25534. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  25535. */
  25536. constructor( parameters = {} ) {
  25537. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  25538. /**
  25539. * A reference to the internal reflector base node which holds the actual implementation.
  25540. *
  25541. * @private
  25542. * @type {ReflectorBaseNode}
  25543. * @default ReflectorBaseNode
  25544. */
  25545. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  25546. /**
  25547. * A reference to the internal depth node.
  25548. *
  25549. * @private
  25550. * @type {?Node}
  25551. * @default null
  25552. */
  25553. this._depthNode = null;
  25554. this.setUpdateMatrix( false );
  25555. }
  25556. /**
  25557. * A reference to the internal reflector node.
  25558. *
  25559. * @type {ReflectorBaseNode}
  25560. */
  25561. get reflector() {
  25562. return this._reflectorBaseNode;
  25563. }
  25564. /**
  25565. * A reference to 3D object the reflector is linked to.
  25566. *
  25567. * @type {Object3D}
  25568. */
  25569. get target() {
  25570. return this._reflectorBaseNode.target;
  25571. }
  25572. /**
  25573. * Returns a node representing the mirror's depth. That can be used
  25574. * to implement more advanced reflection effects like distance attenuation.
  25575. *
  25576. * @return {Node} The depth node.
  25577. */
  25578. getDepthNode() {
  25579. if ( this._depthNode === null ) {
  25580. if ( this._reflectorBaseNode.depth !== true ) {
  25581. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  25582. }
  25583. this._depthNode = nodeObject( new ReflectorNode( {
  25584. defaultTexture: _defaultRT.depthTexture,
  25585. reflector: this._reflectorBaseNode
  25586. } ) );
  25587. }
  25588. return this._depthNode;
  25589. }
  25590. setup( builder ) {
  25591. // ignore if used in post-processing
  25592. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  25593. return super.setup( builder );
  25594. }
  25595. clone() {
  25596. const newNode = new this.constructor( this.reflectorNode );
  25597. newNode.uvNode = this.uvNode;
  25598. newNode.levelNode = this.levelNode;
  25599. newNode.biasNode = this.biasNode;
  25600. newNode.sampler = this.sampler;
  25601. newNode.depthNode = this.depthNode;
  25602. newNode.compareNode = this.compareNode;
  25603. newNode.gradNode = this.gradNode;
  25604. newNode.offsetNode = this.offsetNode;
  25605. newNode._reflectorBaseNode = this._reflectorBaseNode;
  25606. return newNode;
  25607. }
  25608. /**
  25609. * Frees internal resources. Should be called when the node is no longer in use.
  25610. */
  25611. dispose() {
  25612. super.dispose();
  25613. this._reflectorBaseNode.dispose();
  25614. }
  25615. }
  25616. /**
  25617. * Holds the actual implementation of the reflector.
  25618. *
  25619. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  25620. * in `ReflectorNode`, see #29619.
  25621. *
  25622. * @private
  25623. * @augments Node
  25624. */
  25625. class ReflectorBaseNode extends Node {
  25626. static get type() {
  25627. return 'ReflectorBaseNode';
  25628. }
  25629. /**
  25630. * Constructs a new reflector base node.
  25631. *
  25632. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  25633. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25634. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25635. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  25636. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25637. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25638. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25639. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25640. */
  25641. constructor( textureNode, parameters = {} ) {
  25642. super();
  25643. const {
  25644. target = new Object3D(),
  25645. resolutionScale = 1,
  25646. generateMipmaps = false,
  25647. bounces = true,
  25648. depth = false,
  25649. samples = 0
  25650. } = parameters;
  25651. /**
  25652. * Represents the rendered reflections as a texture node.
  25653. *
  25654. * @type {TextureNode}
  25655. */
  25656. this.textureNode = textureNode;
  25657. /**
  25658. * The 3D object the reflector is linked to.
  25659. *
  25660. * @type {Object3D}
  25661. * @default {new Object3D()}
  25662. */
  25663. this.target = target;
  25664. /**
  25665. * The resolution scale.
  25666. *
  25667. * @type {number}
  25668. * @default {1}
  25669. */
  25670. this.resolutionScale = resolutionScale;
  25671. if ( parameters.resolution !== undefined ) {
  25672. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  25673. this.resolutionScale = parameters.resolution;
  25674. }
  25675. /**
  25676. * Whether mipmaps should be generated or not.
  25677. *
  25678. * @type {boolean}
  25679. * @default {false}
  25680. */
  25681. this.generateMipmaps = generateMipmaps;
  25682. /**
  25683. * Whether reflectors can render other reflector nodes or not.
  25684. *
  25685. * @type {boolean}
  25686. * @default {true}
  25687. */
  25688. this.bounces = bounces;
  25689. /**
  25690. * Whether depth data should be generated or not.
  25691. *
  25692. * @type {boolean}
  25693. * @default {false}
  25694. */
  25695. this.depth = depth;
  25696. /**
  25697. * The number of anti-aliasing samples for the render-target
  25698. *
  25699. * @type {number}
  25700. * @default {0}
  25701. */
  25702. this.samples = samples;
  25703. /**
  25704. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  25705. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  25706. *
  25707. * @type {string}
  25708. * @default 'render'
  25709. */
  25710. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  25711. /**
  25712. * Weak map for managing virtual cameras.
  25713. *
  25714. * @type {WeakMap<Camera, Camera>}
  25715. */
  25716. this.virtualCameras = new WeakMap();
  25717. /**
  25718. * Weak map for managing render targets.
  25719. *
  25720. * @type {Map<Camera, RenderTarget>}
  25721. */
  25722. this.renderTargets = new Map();
  25723. /**
  25724. * Force render even if reflector is facing away from camera.
  25725. *
  25726. * @type {boolean}
  25727. * @default {false}
  25728. */
  25729. this.forceUpdate = false;
  25730. /**
  25731. * Whether the reflector has been rendered or not.
  25732. *
  25733. * When the reflector is facing away from the camera,
  25734. * this flag is set to `false` and the texture will be empty(black).
  25735. *
  25736. * @type {boolean}
  25737. * @default {false}
  25738. */
  25739. this.hasOutput = false;
  25740. }
  25741. /**
  25742. * Updates the resolution of the internal render target.
  25743. *
  25744. * @private
  25745. * @param {RenderTarget} renderTarget - The render target to resize.
  25746. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  25747. */
  25748. _updateResolution( renderTarget, renderer ) {
  25749. const resolution = this.resolutionScale;
  25750. renderer.getDrawingBufferSize( _size$2 );
  25751. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  25752. }
  25753. setup( builder ) {
  25754. this._updateResolution( _defaultRT, builder.renderer );
  25755. return super.setup( builder );
  25756. }
  25757. /**
  25758. * Frees internal resources. Should be called when the node is no longer in use.
  25759. */
  25760. dispose() {
  25761. super.dispose();
  25762. for ( const renderTarget of this.renderTargets.values() ) {
  25763. renderTarget.dispose();
  25764. }
  25765. }
  25766. /**
  25767. * Returns a virtual camera for the given camera. The virtual camera is used to
  25768. * render the scene from the reflector's view so correct reflections can be produced.
  25769. *
  25770. * @param {Camera} camera - The scene's camera.
  25771. * @return {Camera} The corresponding virtual camera.
  25772. */
  25773. getVirtualCamera( camera ) {
  25774. let virtualCamera = this.virtualCameras.get( camera );
  25775. if ( virtualCamera === undefined ) {
  25776. virtualCamera = camera.clone();
  25777. this.virtualCameras.set( camera, virtualCamera );
  25778. }
  25779. return virtualCamera;
  25780. }
  25781. /**
  25782. * Returns a render target for the given camera. The reflections are rendered
  25783. * into this render target.
  25784. *
  25785. * @param {Camera} camera - The scene's camera.
  25786. * @return {RenderTarget} The render target.
  25787. */
  25788. getRenderTarget( camera ) {
  25789. let renderTarget = this.renderTargets.get( camera );
  25790. if ( renderTarget === undefined ) {
  25791. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  25792. if ( this.generateMipmaps === true ) {
  25793. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  25794. renderTarget.texture.generateMipmaps = true;
  25795. }
  25796. if ( this.depth === true ) {
  25797. renderTarget.depthTexture = new DepthTexture();
  25798. }
  25799. this.renderTargets.set( camera, renderTarget );
  25800. }
  25801. return renderTarget;
  25802. }
  25803. updateBefore( frame ) {
  25804. if ( this.bounces === false && _inReflector ) return false;
  25805. _inReflector = true;
  25806. const { scene, camera, renderer, material } = frame;
  25807. const { target } = this;
  25808. const virtualCamera = this.getVirtualCamera( camera );
  25809. const renderTarget = this.getRenderTarget( virtualCamera );
  25810. renderer.getDrawingBufferSize( _size$2 );
  25811. this._updateResolution( renderTarget, renderer );
  25812. //
  25813. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  25814. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  25815. _rotationMatrix.extractRotation( target.matrixWorld );
  25816. _normal.set( 0, 0, 1 );
  25817. _normal.applyMatrix4( _rotationMatrix );
  25818. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  25819. // Avoid rendering when reflector is facing away unless forcing an update
  25820. const isFacingAway = _view.dot( _normal ) > 0;
  25821. let needsClear = false;
  25822. if ( isFacingAway === true && this.forceUpdate === false ) {
  25823. if ( this.hasOutput === false ) {
  25824. _inReflector = false;
  25825. return;
  25826. }
  25827. needsClear = true;
  25828. }
  25829. _view.reflect( _normal ).negate();
  25830. _view.add( _reflectorWorldPosition );
  25831. _rotationMatrix.extractRotation( camera.matrixWorld );
  25832. _lookAtPosition.set( 0, 0, -1 );
  25833. _lookAtPosition.applyMatrix4( _rotationMatrix );
  25834. _lookAtPosition.add( _cameraWorldPosition );
  25835. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  25836. _target.reflect( _normal ).negate();
  25837. _target.add( _reflectorWorldPosition );
  25838. //
  25839. virtualCamera.coordinateSystem = camera.coordinateSystem;
  25840. virtualCamera.position.copy( _view );
  25841. virtualCamera.up.set( 0, 1, 0 );
  25842. virtualCamera.up.applyMatrix4( _rotationMatrix );
  25843. virtualCamera.up.reflect( _normal );
  25844. virtualCamera.lookAt( _target );
  25845. virtualCamera.near = camera.near;
  25846. virtualCamera.far = camera.far;
  25847. virtualCamera.updateMatrixWorld();
  25848. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  25849. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  25850. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  25851. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  25852. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  25853. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  25854. const projectionMatrix = virtualCamera.projectionMatrix;
  25855. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  25856. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  25857. _q.z = -1;
  25858. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  25859. // Calculate the scaled plane vector
  25860. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  25861. const clipBias = 0;
  25862. // Replacing the third row of the projection matrix
  25863. projectionMatrix.elements[ 2 ] = clipPlane.x;
  25864. projectionMatrix.elements[ 6 ] = clipPlane.y;
  25865. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  25866. projectionMatrix.elements[ 14 ] = clipPlane.w;
  25867. //
  25868. this.textureNode.value = renderTarget.texture;
  25869. if ( this.depth === true ) {
  25870. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  25871. }
  25872. material.visible = false;
  25873. const currentRenderTarget = renderer.getRenderTarget();
  25874. const currentMRT = renderer.getMRT();
  25875. const currentAutoClear = renderer.autoClear;
  25876. renderer.setMRT( null );
  25877. renderer.setRenderTarget( renderTarget );
  25878. renderer.autoClear = true;
  25879. const previousName = scene.name;
  25880. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  25881. if ( needsClear ) {
  25882. renderer.clear();
  25883. this.hasOutput = false;
  25884. } else {
  25885. renderer.render( scene, virtualCamera );
  25886. this.hasOutput = true;
  25887. }
  25888. scene.name = previousName;
  25889. renderer.setMRT( currentMRT );
  25890. renderer.setRenderTarget( currentRenderTarget );
  25891. renderer.autoClear = currentAutoClear;
  25892. material.visible = true;
  25893. _inReflector = false;
  25894. this.forceUpdate = false;
  25895. }
  25896. /**
  25897. * The resolution scale.
  25898. *
  25899. * @deprecated
  25900. * @type {number}
  25901. * @default {1}
  25902. */
  25903. get resolution() {
  25904. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25905. return this.resolutionScale;
  25906. }
  25907. set resolution( value ) {
  25908. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25909. this.resolutionScale = value;
  25910. }
  25911. }
  25912. /**
  25913. * TSL function for creating a reflector node.
  25914. *
  25915. * @tsl
  25916. * @function
  25917. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25918. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25919. * @param {number} [parameters.resolution=1] - The resolution scale.
  25920. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25921. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25922. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25923. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25924. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  25925. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  25926. * @returns {ReflectorNode}
  25927. */
  25928. const reflector = ( parameters ) => new ReflectorNode( parameters );
  25929. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  25930. /**
  25931. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  25932. *
  25933. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  25934. *
  25935. * @private
  25936. * @augments BufferGeometry
  25937. */
  25938. class QuadGeometry extends BufferGeometry {
  25939. /**
  25940. * Constructs a new quad geometry.
  25941. *
  25942. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  25943. */
  25944. constructor( flipY = false ) {
  25945. super();
  25946. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  25947. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  25948. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  25949. }
  25950. }
  25951. const _geometry = /*@__PURE__*/ new QuadGeometry();
  25952. /**
  25953. * This module is a helper for passes which need to render a full
  25954. * screen effect which is quite common in context of post processing.
  25955. *
  25956. * The intended usage is to reuse a single quad mesh for rendering
  25957. * subsequent passes by just reassigning the `material` reference.
  25958. *
  25959. * Note: This module can only be used with `WebGPURenderer`.
  25960. *
  25961. * @augments Mesh
  25962. */
  25963. class QuadMesh extends Mesh {
  25964. /**
  25965. * Constructs a new quad mesh.
  25966. *
  25967. * @param {?Material} [material=null] - The material to render the quad mesh with.
  25968. */
  25969. constructor( material = null ) {
  25970. super( _geometry, material );
  25971. /**
  25972. * The camera to render the quad mesh with.
  25973. *
  25974. * @type {OrthographicCamera}
  25975. * @readonly
  25976. */
  25977. this.camera = _camera;
  25978. /**
  25979. * This flag can be used for type testing.
  25980. *
  25981. * @type {boolean}
  25982. * @readonly
  25983. * @default true
  25984. */
  25985. this.isQuadMesh = true;
  25986. }
  25987. /**
  25988. * Async version of `render()`.
  25989. *
  25990. * @async
  25991. * @deprecated
  25992. * @param {Renderer} renderer - The renderer.
  25993. * @return {Promise} A Promise that resolves when the render has been finished.
  25994. */
  25995. async renderAsync( renderer ) {
  25996. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  25997. await renderer.init();
  25998. renderer.render( this, _camera );
  25999. }
  26000. /**
  26001. * Renders the quad mesh
  26002. *
  26003. * @param {Renderer} renderer - The renderer.
  26004. */
  26005. render( renderer ) {
  26006. renderer.render( this, _camera );
  26007. }
  26008. }
  26009. const _size$1 = /*@__PURE__*/ new Vector2();
  26010. /**
  26011. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  26012. * This module is especially relevant in context of post processing where certain nodes require
  26013. * texture input for their effects. With the helper function `convertToTexture()` which is based
  26014. * on this module, the node system can automatically ensure texture input if required.
  26015. *
  26016. * @augments TextureNode
  26017. */
  26018. class RTTNode extends TextureNode {
  26019. static get type() {
  26020. return 'RTTNode';
  26021. }
  26022. /**
  26023. * Constructs a new RTT node.
  26024. *
  26025. * @param {Node} node - The node to render a texture with.
  26026. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  26027. * @param {?number} [height=null] - The height of the internal render target.
  26028. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  26029. */
  26030. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  26031. const renderTarget = new RenderTarget( width, height, options );
  26032. super( renderTarget.texture, uv$1() );
  26033. /**
  26034. * This flag can be used for type testing.
  26035. *
  26036. * @type {boolean}
  26037. * @readonly
  26038. * @default true
  26039. */
  26040. this.isRTTNode = true;
  26041. /**
  26042. * The node to render a texture with.
  26043. *
  26044. * @type {Node}
  26045. */
  26046. this.node = node;
  26047. /**
  26048. * The width of the internal render target.
  26049. * If not width is applied, the render target is automatically resized.
  26050. *
  26051. * @type {?number}
  26052. * @default null
  26053. */
  26054. this.width = width;
  26055. /**
  26056. * The height of the internal render target.
  26057. *
  26058. * @type {?number}
  26059. * @default null
  26060. */
  26061. this.height = height;
  26062. /**
  26063. * The pixel ratio
  26064. *
  26065. * @type {number}
  26066. * @default 1
  26067. */
  26068. this.pixelRatio = 1;
  26069. /**
  26070. * The render target
  26071. *
  26072. * @type {RenderTarget}
  26073. */
  26074. this.renderTarget = renderTarget;
  26075. /**
  26076. * Whether the texture requires an update or not.
  26077. *
  26078. * @type {boolean}
  26079. * @default true
  26080. */
  26081. this.textureNeedsUpdate = true;
  26082. /**
  26083. * Whether the texture should automatically be updated or not.
  26084. *
  26085. * @type {boolean}
  26086. * @default true
  26087. */
  26088. this.autoUpdate = true;
  26089. /**
  26090. * The node which is used with the quad mesh for RTT.
  26091. *
  26092. * @private
  26093. * @type {Node}
  26094. * @default null
  26095. */
  26096. this._rttNode = null;
  26097. /**
  26098. * The internal quad mesh for RTT.
  26099. *
  26100. * @private
  26101. * @type {QuadMesh}
  26102. */
  26103. this._quadMesh = new QuadMesh( new NodeMaterial() );
  26104. /**
  26105. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  26106. * the texture once per render in its {@link RTTNode#updateBefore} method.
  26107. *
  26108. * @type {string}
  26109. * @default 'render'
  26110. */
  26111. this.updateBeforeType = NodeUpdateType.RENDER;
  26112. }
  26113. /**
  26114. * Whether the internal render target should automatically be resized or not.
  26115. *
  26116. * @type {boolean}
  26117. * @readonly
  26118. * @default true
  26119. */
  26120. get autoResize() {
  26121. return this.width === null;
  26122. }
  26123. setup( builder ) {
  26124. this._rttNode = this.node.context( builder.getSharedContext() );
  26125. this._quadMesh.material.name = 'RTT';
  26126. this._quadMesh.material.needsUpdate = true;
  26127. return super.setup( builder );
  26128. }
  26129. /**
  26130. * Sets the size of the internal render target
  26131. *
  26132. * @param {number} width - The width to set.
  26133. * @param {number} height - The width to set.
  26134. */
  26135. setSize( width, height ) {
  26136. this.width = width;
  26137. this.height = height;
  26138. const effectiveWidth = width * this.pixelRatio;
  26139. const effectiveHeight = height * this.pixelRatio;
  26140. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  26141. this.textureNeedsUpdate = true;
  26142. }
  26143. /**
  26144. * Sets the pixel ratio. This will also resize the render target.
  26145. *
  26146. * @param {number} pixelRatio - The pixel ratio to set.
  26147. */
  26148. setPixelRatio( pixelRatio ) {
  26149. this.pixelRatio = pixelRatio;
  26150. this.setSize( this.width, this.height );
  26151. }
  26152. updateBefore( { renderer } ) {
  26153. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  26154. this.textureNeedsUpdate = false;
  26155. //
  26156. if ( this.autoResize === true ) {
  26157. const pixelRatio = renderer.getPixelRatio();
  26158. const size = renderer.getSize( _size$1 );
  26159. const effectiveWidth = Math.floor( size.width * pixelRatio );
  26160. const effectiveHeight = Math.floor( size.height * pixelRatio );
  26161. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  26162. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  26163. this.textureNeedsUpdate = true;
  26164. }
  26165. }
  26166. //
  26167. let name = 'RTT';
  26168. if ( this.node.name ) {
  26169. name = this.node.name + ' [ ' + name + ' ]';
  26170. }
  26171. this._quadMesh.material.fragmentNode = this._rttNode;
  26172. this._quadMesh.name = name;
  26173. //
  26174. const currentRenderTarget = renderer.getRenderTarget();
  26175. renderer.setRenderTarget( this.renderTarget );
  26176. this._quadMesh.render( renderer );
  26177. renderer.setRenderTarget( currentRenderTarget );
  26178. }
  26179. clone() {
  26180. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  26181. newNode.sampler = this.sampler;
  26182. newNode.referenceNode = this;
  26183. return newNode;
  26184. }
  26185. }
  26186. /**
  26187. * TSL function for creating a RTT node.
  26188. *
  26189. * @tsl
  26190. * @function
  26191. * @param {Node} node - The node to render a texture with.
  26192. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  26193. * @param {?number} [height=null] - The height of the internal render target.
  26194. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  26195. * @returns {RTTNode}
  26196. */
  26197. const rtt = ( node, ...params ) => new RTTNode( nodeObject( node ), ...params );
  26198. /**
  26199. * TSL function for converting nodes to textures nodes.
  26200. *
  26201. * @tsl
  26202. * @function
  26203. * @param {Node} node - The node to render a texture with.
  26204. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  26205. * @param {?number} [height=null] - The height of the internal render target.
  26206. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  26207. * @returns {RTTNode}
  26208. */
  26209. const convertToTexture = ( node, ...params ) => {
  26210. if ( node.isSampleNode || node.isTextureNode ) return node;
  26211. if ( node.isPassNode ) return node.getTextureNode();
  26212. return rtt( node, ...params );
  26213. };
  26214. /**
  26215. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  26216. * depth value and the camera's inverse projection matrix.
  26217. *
  26218. * @tsl
  26219. * @function
  26220. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  26221. * @param {Node<float>} depth - The fragment's depth value.
  26222. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  26223. * @return {Node<vec3>} The fragments position in view space.
  26224. */
  26225. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  26226. let clipSpacePosition;
  26227. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  26228. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  26229. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  26230. } else {
  26231. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  26232. }
  26233. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  26234. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  26235. } );
  26236. /**
  26237. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  26238. * and the camera's projection matrix
  26239. *
  26240. * @tsl
  26241. * @function
  26242. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  26243. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  26244. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  26245. */
  26246. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  26247. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  26248. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  26249. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  26250. } );
  26251. /**
  26252. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  26253. * target is available or if flat surface normals are required.
  26254. *
  26255. * @tsl
  26256. * @function
  26257. * @param {Node<vec2>} uv - The texture coordinate.
  26258. * @param {DepthTexture} depthTexture - The depth texture.
  26259. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  26260. * @return {Node<vec3>} The computed normal vector.
  26261. */
  26262. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  26263. const size = textureSize( textureLoad( depthTexture ) );
  26264. const p = ivec2( uv.mul( size ) ).toVar();
  26265. const c0 = textureLoad( depthTexture, p ).toVar();
  26266. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  26267. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  26268. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  26269. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  26270. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  26271. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  26272. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  26273. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  26274. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  26275. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  26276. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  26277. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  26278. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  26279. 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 ) ) );
  26280. 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 ) ) );
  26281. return normalize( cross( dpdx, dpdy ) );
  26282. } );
  26283. /**
  26284. * Interleaved Gradient Noise (IGN) from Jimenez 2014.
  26285. *
  26286. * IGN has "low discrepancy" resulting in evenly distributed samples. It's superior compared to
  26287. * default white noise, blue noise or Bayer.
  26288. *
  26289. * References:
  26290. * - {@link https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/}
  26291. * - {@link https://blog.demofox.org/2022/01/01/interleaved-gradient-noise-a-different-kind-of-low-discrepancy-sequence/}
  26292. *
  26293. * @tsl
  26294. * @function
  26295. * @param {Node<vec2>} position - The input position, usually screen coordinates.
  26296. * @return {Node<float>} The noise value.
  26297. */
  26298. const interleavedGradientNoise = Fn( ( [ position ] ) => {
  26299. return fract( float( 52.9829189 ).mul( fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ) );
  26300. } ).setLayout( {
  26301. name: 'interleavedGradientNoise',
  26302. type: 'float',
  26303. inputs: [
  26304. { name: 'position', type: 'vec2' }
  26305. ]
  26306. } );
  26307. /**
  26308. * Vogel disk sampling for uniform circular distribution.
  26309. *
  26310. * This function generates sample points distributed uniformly on a disk using the golden angle,
  26311. * resulting in an efficient low-discrepancy sequence for sampling. The rotation parameter (phi)
  26312. * allows randomizing the pattern per-pixel when combined with IGN.
  26313. *
  26314. * @tsl
  26315. * @function
  26316. * @param {Node<int>} sampleIndex - The index of the current sample (0-based).
  26317. * @param {Node<int>} samplesCount - The total number of samples.
  26318. * @param {Node<float>} phi - Rotation angle in radians (typically from IGN * 2π).
  26319. * @return {Node<vec2>} A 2D point on the unit disk.
  26320. */
  26321. const vogelDiskSample = Fn( ( [ sampleIndex, samplesCount, phi ] ) => {
  26322. const goldenAngle = float( 2.399963229728653 ); // 2π * (2 - φ) where φ is golden ratio
  26323. const r = sqrt( float( sampleIndex ).add( 0.5 ).div( float( samplesCount ) ) );
  26324. const theta = float( sampleIndex ).mul( goldenAngle ).add( phi );
  26325. return vec2( cos( theta ), sin( theta ) ).mul( r );
  26326. } ).setLayout( {
  26327. name: 'vogelDiskSample',
  26328. type: 'vec2',
  26329. inputs: [
  26330. { name: 'sampleIndex', type: 'int' },
  26331. { name: 'samplesCount', type: 'int' },
  26332. { name: 'phi', type: 'float' }
  26333. ]
  26334. } );
  26335. /**
  26336. * Class representing a node that samples a value using a provided callback function.
  26337. *
  26338. * @extends Node
  26339. */
  26340. class SampleNode extends Node {
  26341. /**
  26342. * Returns the type of the node.
  26343. *
  26344. * @type {string}
  26345. * @readonly
  26346. * @static
  26347. */
  26348. static get type() {
  26349. return 'SampleNode';
  26350. }
  26351. /**
  26352. * Creates an instance of SampleNode.
  26353. *
  26354. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  26355. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  26356. */
  26357. constructor( callback, uvNode = null ) {
  26358. super();
  26359. this.callback = callback;
  26360. /**
  26361. * Represents the texture coordinates.
  26362. *
  26363. * @type {?Node<vec2|vec3>}
  26364. * @default null
  26365. */
  26366. this.uvNode = uvNode;
  26367. /**
  26368. * This flag can be used for type testing.
  26369. *
  26370. * @type {boolean}
  26371. * @readonly
  26372. * @default true
  26373. */
  26374. this.isSampleNode = true;
  26375. }
  26376. /**
  26377. * Sets up the node by sampling with the default UV accessor.
  26378. *
  26379. * @returns {Node} The result of the callback function when called with the UV node.
  26380. */
  26381. setup() {
  26382. return this.sample( uv$1() );
  26383. }
  26384. /**
  26385. * Calls the callback function with the provided UV node.
  26386. *
  26387. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  26388. * @returns {Node} The result of the callback function.
  26389. */
  26390. sample( uv ) {
  26391. return this.callback( uv );
  26392. }
  26393. }
  26394. /**
  26395. * Helper function to create a SampleNode wrapped as a node object.
  26396. *
  26397. * @function
  26398. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  26399. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  26400. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  26401. */
  26402. const sample = ( callback, uv = null ) => new SampleNode( callback, nodeObject( uv ) );
  26403. /**
  26404. * EventNode is a node that executes a callback during specific update phases.
  26405. *
  26406. * @augments Node
  26407. */
  26408. class EventNode extends Node {
  26409. static get type() {
  26410. return 'EventNode';
  26411. }
  26412. /**
  26413. * Creates an EventNode.
  26414. *
  26415. * @param {string} eventType - The type of event
  26416. * @param {Function} callback - The callback to execute on update.
  26417. */
  26418. constructor( eventType, callback ) {
  26419. super( 'void' );
  26420. this.eventType = eventType;
  26421. this.callback = callback;
  26422. if ( eventType === EventNode.OBJECT ) {
  26423. this.updateType = NodeUpdateType.OBJECT;
  26424. } else if ( eventType === EventNode.MATERIAL ) {
  26425. this.updateType = NodeUpdateType.RENDER;
  26426. } else if ( eventType === EventNode.BEFORE_OBJECT ) {
  26427. this.updateBeforeType = NodeUpdateType.OBJECT;
  26428. } else if ( eventType === EventNode.BEFORE_MATERIAL ) {
  26429. this.updateBeforeType = NodeUpdateType.RENDER;
  26430. }
  26431. }
  26432. update( frame ) {
  26433. this.callback( frame );
  26434. }
  26435. updateBefore( frame ) {
  26436. this.callback( frame );
  26437. }
  26438. }
  26439. EventNode.OBJECT = 'object';
  26440. EventNode.MATERIAL = 'material';
  26441. EventNode.BEFORE_OBJECT = 'beforeObject';
  26442. EventNode.BEFORE_MATERIAL = 'beforeMaterial';
  26443. /**
  26444. * Helper to create an EventNode and add it to the stack.
  26445. *
  26446. * @param {string} type - The event type.
  26447. * @param {Function} callback - The callback function.
  26448. * @returns {EventNode}
  26449. */
  26450. const createEvent = ( type, callback ) => new EventNode( type, callback ).toStack();
  26451. /**
  26452. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  26453. *
  26454. * 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.
  26455. *
  26456. * @param {Function} callback - The callback function.
  26457. * @returns {EventNode}
  26458. */
  26459. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  26460. /**
  26461. * Creates an event that triggers a function when the first object that uses the material is rendered.
  26462. *
  26463. * 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.
  26464. *
  26465. * @param {Function} callback - The callback function.
  26466. * @returns {EventNode}
  26467. */
  26468. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  26469. /**
  26470. * Creates an event that triggers a function before an object (Mesh|Sprite) is updated.
  26471. *
  26472. * 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.
  26473. *
  26474. * @param {Function} callback - The callback function.
  26475. * @returns {EventNode}
  26476. */
  26477. const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJECT, callback );
  26478. /**
  26479. * Creates an event that triggers a function before the material is updated.
  26480. *
  26481. * 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.
  26482. *
  26483. * @param {Function} callback - The callback function.
  26484. * @returns {EventNode}
  26485. */
  26486. const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback );
  26487. /**
  26488. * This special type of instanced buffer attribute is intended for compute shaders.
  26489. * In earlier three.js versions it was only possible to update attribute data
  26490. * on the CPU via JavaScript and then upload the data to the GPU. With the
  26491. * new material system and renderer it is now possible to use compute shaders
  26492. * to compute the data for an attribute more efficiently on the GPU.
  26493. *
  26494. * The idea is to create an instance of this class and provide it as an input
  26495. * to {@link StorageBufferNode}.
  26496. *
  26497. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  26498. *
  26499. * @augments InstancedBufferAttribute
  26500. */
  26501. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  26502. /**
  26503. * Constructs a new storage instanced buffer attribute.
  26504. *
  26505. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  26506. * The subsequent parameters are then obsolete.
  26507. * @param {number} itemSize - The item size.
  26508. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  26509. */
  26510. constructor( count, itemSize, typeClass = Float32Array ) {
  26511. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  26512. super( array, itemSize );
  26513. /**
  26514. * This flag can be used for type testing.
  26515. *
  26516. * @type {boolean}
  26517. * @readonly
  26518. * @default true
  26519. */
  26520. this.isStorageInstancedBufferAttribute = true;
  26521. }
  26522. }
  26523. /**
  26524. * This special type of buffer attribute is intended for compute shaders.
  26525. * In earlier three.js versions it was only possible to update attribute data
  26526. * on the CPU via JavaScript and then upload the data to the GPU. With the
  26527. * new material system and renderer it is now possible to use compute shaders
  26528. * to compute the data for an attribute more efficiently on the GPU.
  26529. *
  26530. * The idea is to create an instance of this class and provide it as an input
  26531. * to {@link StorageBufferNode}.
  26532. *
  26533. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  26534. *
  26535. * @augments BufferAttribute
  26536. */
  26537. class StorageBufferAttribute extends BufferAttribute {
  26538. /**
  26539. * Constructs a new storage buffer attribute.
  26540. *
  26541. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  26542. * The subsequent parameters are then obsolete.
  26543. * @param {number} itemSize - The item size.
  26544. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  26545. */
  26546. constructor( count, itemSize, typeClass = Float32Array ) {
  26547. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  26548. super( array, itemSize );
  26549. /**
  26550. * This flag can be used for type testing.
  26551. *
  26552. * @type {boolean}
  26553. * @readonly
  26554. * @default true
  26555. */
  26556. this.isStorageBufferAttribute = true;
  26557. }
  26558. }
  26559. /**
  26560. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  26561. *
  26562. * @tsl
  26563. * @function
  26564. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  26565. * @param {string|Struct} [type='float'] - The data type.
  26566. * @returns {StorageBufferNode}
  26567. */
  26568. const attributeArray = ( count, type = 'float' ) => {
  26569. let itemSize, typedArray;
  26570. if ( type.isStruct === true ) {
  26571. itemSize = type.layout.getLength();
  26572. typedArray = getTypedArrayFromType( 'float' );
  26573. } else {
  26574. itemSize = getLengthFromType( type );
  26575. typedArray = getTypedArrayFromType( type );
  26576. }
  26577. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  26578. const node = storage( buffer, type, count );
  26579. return node;
  26580. };
  26581. /**
  26582. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  26583. *
  26584. * @tsl
  26585. * @function
  26586. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  26587. * @param {string|Struct} [type='float'] - The data type.
  26588. * @returns {StorageBufferNode}
  26589. */
  26590. const instancedArray = ( count, type = 'float' ) => {
  26591. let itemSize, typedArray;
  26592. if ( type.isStruct === true ) {
  26593. itemSize = type.layout.getLength();
  26594. typedArray = getTypedArrayFromType( 'float' );
  26595. } else {
  26596. itemSize = getLengthFromType( type );
  26597. typedArray = getTypedArrayFromType( type );
  26598. }
  26599. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  26600. const node = storage( buffer, type, buffer.count );
  26601. return node;
  26602. };
  26603. /**
  26604. * A node for representing the uv coordinates of points.
  26605. *
  26606. * Can only be used with a WebGL backend. In WebGPU, point
  26607. * primitives always have the size of one pixel and can thus
  26608. * can't be used as sprite-like objects that display textures.
  26609. *
  26610. * @augments Node
  26611. */
  26612. class PointUVNode extends Node {
  26613. static get type() {
  26614. return 'PointUVNode';
  26615. }
  26616. /**
  26617. * Constructs a new point uv node.
  26618. */
  26619. constructor() {
  26620. super( 'vec2' );
  26621. /**
  26622. * This flag can be used for type testing.
  26623. *
  26624. * @type {boolean}
  26625. * @readonly
  26626. * @default true
  26627. */
  26628. this.isPointUVNode = true;
  26629. }
  26630. generate( /*builder*/ ) {
  26631. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  26632. }
  26633. }
  26634. /**
  26635. * TSL object that represents the uv coordinates of points.
  26636. *
  26637. * @tsl
  26638. * @type {PointUVNode}
  26639. */
  26640. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  26641. const _e1 = /*@__PURE__*/ new Euler();
  26642. const _m1 = /*@__PURE__*/ new Matrix4();
  26643. /**
  26644. * TSL object that represents the scene's background blurriness.
  26645. *
  26646. * @tsl
  26647. * @type {Node<float>}
  26648. */
  26649. const backgroundBlurriness = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => scene.backgroundBlurriness );
  26650. /**
  26651. * TSL object that represents the scene's background intensity.
  26652. *
  26653. * @tsl
  26654. * @type {Node<float>}
  26655. */
  26656. const backgroundIntensity = /*@__PURE__*/ uniform( 1 ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => scene.backgroundIntensity );
  26657. /**
  26658. * TSL object that represents the scene's background rotation.
  26659. *
  26660. * @tsl
  26661. * @type {Node<mat4>}
  26662. */
  26663. const backgroundRotation = /*@__PURE__*/ uniform( new Matrix4() ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => {
  26664. const background = scene.background;
  26665. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  26666. _e1.copy( scene.backgroundRotation );
  26667. // accommodate left-handed frame
  26668. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  26669. _m1.makeRotationFromEuler( _e1 );
  26670. } else {
  26671. _m1.identity();
  26672. }
  26673. return _m1;
  26674. } );
  26675. /**
  26676. * This special version of a texture node can be used to
  26677. * write data into a storage texture with a compute shader.
  26678. *
  26679. * ```js
  26680. * const storageTexture = new THREE.StorageTexture( width, height );
  26681. *
  26682. * const computeTexture = Fn( ( { storageTexture } ) => {
  26683. *
  26684. * const posX = instanceIndex.mod( width );
  26685. * const posY = instanceIndex.div( width );
  26686. * const indexUV = uvec2( posX, posY );
  26687. *
  26688. * // generate RGB values
  26689. *
  26690. * const r = 1;
  26691. * const g = 1;
  26692. * const b = 1;
  26693. *
  26694. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  26695. *
  26696. * } );
  26697. *
  26698. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  26699. * renderer.computeAsync( computeNode );
  26700. * ```
  26701. *
  26702. * This node can only be used with a WebGPU backend.
  26703. *
  26704. * @augments TextureNode
  26705. */
  26706. class StorageTextureNode extends TextureNode {
  26707. static get type() {
  26708. return 'StorageTextureNode';
  26709. }
  26710. /**
  26711. * Constructs a new storage texture node.
  26712. *
  26713. * @param {StorageTexture} value - The storage texture.
  26714. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26715. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26716. */
  26717. constructor( value, uvNode, storeNode = null ) {
  26718. super( value, uvNode );
  26719. /**
  26720. * The value node that should be stored in the texture.
  26721. *
  26722. * @type {?Node}
  26723. * @default null
  26724. */
  26725. this.storeNode = storeNode;
  26726. /**
  26727. * The mip level to write to for storage textures.
  26728. *
  26729. * @type {number}
  26730. * @default 0
  26731. */
  26732. this.mipLevel = 0;
  26733. /**
  26734. * This flag can be used for type testing.
  26735. *
  26736. * @type {boolean}
  26737. * @readonly
  26738. * @default true
  26739. */
  26740. this.isStorageTextureNode = true;
  26741. /**
  26742. * The access type of the texture node.
  26743. *
  26744. * @type {string}
  26745. * @default 'writeOnly'
  26746. */
  26747. this.access = NodeAccess.WRITE_ONLY;
  26748. }
  26749. /**
  26750. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  26751. *
  26752. * @param {NodeBuilder} builder - The current node builder.
  26753. * @return {string} The input type.
  26754. */
  26755. getInputType( /*builder*/ ) {
  26756. return 'storageTexture';
  26757. }
  26758. setup( builder ) {
  26759. super.setup( builder );
  26760. const properties = builder.getNodeProperties( this );
  26761. properties.storeNode = this.storeNode;
  26762. return properties;
  26763. }
  26764. /**
  26765. * Defines the node access.
  26766. *
  26767. * @param {string} value - The node access.
  26768. * @return {StorageTextureNode} A reference to this node.
  26769. */
  26770. setAccess( value ) {
  26771. this.access = value;
  26772. return this;
  26773. }
  26774. /**
  26775. * Sets the mip level to write to.
  26776. *
  26777. * @param {number} level - The mip level.
  26778. * @return {StorageTextureNode} A reference to this node.
  26779. */
  26780. setMipLevel( level ) {
  26781. this.mipLevel = level;
  26782. return this;
  26783. }
  26784. /**
  26785. * Generates the code snippet of the storage node. If no `storeNode`
  26786. * is defined, the texture node is generated as normal texture.
  26787. *
  26788. * @param {NodeBuilder} builder - The current node builder.
  26789. * @param {string} output - The current output.
  26790. * @return {string} The generated code snippet.
  26791. */
  26792. generate( builder, output ) {
  26793. let snippet;
  26794. if ( this.storeNode !== null ) {
  26795. snippet = this.generateStore( builder );
  26796. } else {
  26797. snippet = super.generate( builder, output );
  26798. }
  26799. return snippet;
  26800. }
  26801. /**
  26802. * Convenience method for configuring a read/write node access.
  26803. *
  26804. * @return {StorageTextureNode} A reference to this node.
  26805. */
  26806. toReadWrite() {
  26807. return this.setAccess( NodeAccess.READ_WRITE );
  26808. }
  26809. /**
  26810. * Convenience method for configuring a read-only node access.
  26811. *
  26812. * @return {StorageTextureNode} A reference to this node.
  26813. */
  26814. toReadOnly() {
  26815. return this.setAccess( NodeAccess.READ_ONLY );
  26816. }
  26817. /**
  26818. * Convenience method for configuring a write-only node access.
  26819. *
  26820. * @return {StorageTextureNode} A reference to this node.
  26821. */
  26822. toWriteOnly() {
  26823. return this.setAccess( NodeAccess.WRITE_ONLY );
  26824. }
  26825. /**
  26826. * Generates the code snippet of the storage texture node.
  26827. *
  26828. * @param {NodeBuilder} builder - The current node builder.
  26829. */
  26830. generateStore( builder ) {
  26831. const properties = builder.getNodeProperties( this );
  26832. const { uvNode, storeNode, depthNode } = properties;
  26833. const textureProperty = super.generate( builder, 'property' );
  26834. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  26835. const storeSnippet = storeNode.build( builder, 'vec4' );
  26836. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  26837. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  26838. builder.addLineFlowCode( snippet, this );
  26839. }
  26840. clone() {
  26841. const newNode = super.clone();
  26842. newNode.storeNode = this.storeNode;
  26843. newNode.mipLevel = this.mipLevel;
  26844. newNode.access = this.access;
  26845. return newNode;
  26846. }
  26847. }
  26848. /**
  26849. * TSL function for creating a storage texture node.
  26850. *
  26851. * @tsl
  26852. * @function
  26853. * @param {StorageTexture} value - The storage texture.
  26854. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  26855. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26856. * @returns {StorageTextureNode}
  26857. */
  26858. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  26859. /**
  26860. * TODO: Explain difference to `storageTexture()`.
  26861. *
  26862. * @tsl
  26863. * @function
  26864. * @param {StorageTexture} value - The storage texture.
  26865. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26866. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26867. * @returns {StorageTextureNode}
  26868. */
  26869. const textureStore = ( value, uvNode, storeNode ) => {
  26870. let node;
  26871. if ( value.isStorageTextureNode === true ) {
  26872. // Derive new storage texture node from existing one
  26873. node = value.clone();
  26874. node.uvNode = uvNode;
  26875. node.storeNode = storeNode;
  26876. } else {
  26877. node = storageTexture( value, uvNode, storeNode );
  26878. }
  26879. if ( storeNode !== null ) node.toStack();
  26880. return node;
  26881. };
  26882. const normal = Fn( ( { texture, uv } ) => {
  26883. const epsilon = 0.0001;
  26884. const ret = vec3().toVar();
  26885. If( uv.x.lessThan( epsilon ), () => {
  26886. ret.assign( vec3( 1, 0, 0 ) );
  26887. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  26888. ret.assign( vec3( 0, 1, 0 ) );
  26889. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  26890. ret.assign( vec3( 0, 0, 1 ) );
  26891. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  26892. ret.assign( vec3( -1, 0, 0 ) );
  26893. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  26894. ret.assign( vec3( 0, -1, 0 ) );
  26895. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  26896. ret.assign( vec3( 0, 0, -1 ) );
  26897. } ).Else( () => {
  26898. const step = 0.01;
  26899. 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 );
  26900. 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 );
  26901. 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 );
  26902. ret.assign( vec3( x, y, z ) );
  26903. } );
  26904. return ret.normalize();
  26905. } );
  26906. /**
  26907. * This type of uniform node represents a 3D texture.
  26908. *
  26909. * @augments TextureNode
  26910. */
  26911. class Texture3DNode extends TextureNode {
  26912. static get type() {
  26913. return 'Texture3DNode';
  26914. }
  26915. /**
  26916. * Constructs a new 3D texture node.
  26917. *
  26918. * @param {Data3DTexture} value - The 3D texture.
  26919. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  26920. * @param {?Node<int>} [levelNode=null] - The level node.
  26921. */
  26922. constructor( value, uvNode = null, levelNode = null ) {
  26923. super( value, uvNode, levelNode );
  26924. /**
  26925. * This flag can be used for type testing.
  26926. *
  26927. * @type {boolean}
  26928. * @readonly
  26929. * @default true
  26930. */
  26931. this.isTexture3DNode = true;
  26932. }
  26933. /**
  26934. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  26935. *
  26936. * @param {NodeBuilder} builder - The current node builder.
  26937. * @return {string} The input type.
  26938. */
  26939. getInputType( /*builder*/ ) {
  26940. return 'texture3D';
  26941. }
  26942. /**
  26943. * Returns a default uv node which is in context of 3D textures a three-dimensional
  26944. * uv node.
  26945. *
  26946. * @return {Node<vec3>} The default uv node.
  26947. */
  26948. getDefaultUV() {
  26949. return vec3( 0.5, 0.5, 0.5 );
  26950. }
  26951. /**
  26952. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  26953. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  26954. *
  26955. * @param {boolean} value - The update toggle.
  26956. */
  26957. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  26958. /**
  26959. * Generates the uv code snippet.
  26960. *
  26961. * @param {NodeBuilder} builder - The current node builder.
  26962. * @param {Node} uvNode - The uv node to generate code for.
  26963. * @return {string} The generated code snippet.
  26964. */
  26965. generateUV( builder, uvNode ) {
  26966. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  26967. }
  26968. /**
  26969. * Generates the offset code snippet.
  26970. *
  26971. * @param {NodeBuilder} builder - The current node builder.
  26972. * @param {Node} offsetNode - The offset node to generate code for.
  26973. * @return {string} The generated code snippet.
  26974. */
  26975. generateOffset( builder, offsetNode ) {
  26976. return offsetNode.build( builder, 'ivec3' );
  26977. }
  26978. /**
  26979. * Computes the normal for the given uv. These texture coordiantes represent a
  26980. * position inside the 3D texture. Unlike geometric normals, this normal
  26981. * represents a slope or gradient of scalar data inside the 3D texture.
  26982. *
  26983. * @param {Node<vec3>} uvNode - The uv node that defines a position in the 3D texture.
  26984. * @return {Node<vec3>} The normal representing the slope/gradient in the data.
  26985. */
  26986. normal( uvNode ) {
  26987. return normal( { texture: this, uv: uvNode } );
  26988. }
  26989. }
  26990. /**
  26991. * TSL function for creating a 3D texture node.
  26992. *
  26993. * @tsl
  26994. * @function
  26995. * @param {Data3DTexture} value - The 3D texture.
  26996. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26997. * @param {?Node<int>} [levelNode=null] - The level node.
  26998. * @returns {Texture3DNode}
  26999. */
  27000. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  27001. /**
  27002. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  27003. *
  27004. * @tsl
  27005. * @function
  27006. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  27007. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  27008. * @param {?Node<int>} [levelNode=null] - The level node.
  27009. * @param {?Node<float>} [biasNode=null] - The bias node.
  27010. * @returns {TextureNode}
  27011. */
  27012. const texture3DLoad = ( ...params ) => texture3D( ...params ).setSampler( false );
  27013. /**
  27014. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  27015. *
  27016. * @tsl
  27017. * @function
  27018. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  27019. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  27020. * @param {?Node<int>} [levelNode=null] - The level node.
  27021. * @returns {TextureNode}
  27022. */
  27023. const texture3DLevel = ( value, uvNode, levelNode ) => texture3D( value, uvNode ).level( levelNode );
  27024. /**
  27025. * A special type of reference node that allows to link values in
  27026. * `userData` fields to node objects.
  27027. * ```js
  27028. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  27029. *
  27030. * const material = new THREE.SpriteNodeMaterial();
  27031. * material.rotationNode = userData( 'rotation', 'float' );
  27032. * ```
  27033. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  27034. * will automatically be updated when the `rotation` user data field changes.
  27035. *
  27036. * @augments ReferenceNode
  27037. */
  27038. class UserDataNode extends ReferenceNode {
  27039. static get type() {
  27040. return 'UserDataNode';
  27041. }
  27042. /**
  27043. * Constructs a new user data node.
  27044. *
  27045. * @param {string} property - The property name that should be referenced by the node.
  27046. * @param {string} inputType - The node data type of the reference.
  27047. * @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.
  27048. */
  27049. constructor( property, inputType, userData = null ) {
  27050. super( property, inputType, userData );
  27051. /**
  27052. * A reference to the `userData` object. If not provided, the `userData`
  27053. * property of the 3D object that uses the node material is evaluated.
  27054. *
  27055. * @type {?Object}
  27056. * @default null
  27057. */
  27058. this.userData = userData;
  27059. }
  27060. /**
  27061. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  27062. * `userData` field.
  27063. *
  27064. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  27065. * @return {Object} A reference to the `userData` field.
  27066. */
  27067. updateReference( state ) {
  27068. this.reference = this.userData !== null ? this.userData : state.object.userData;
  27069. return this.reference;
  27070. }
  27071. }
  27072. /**
  27073. * TSL function for creating a user data node.
  27074. *
  27075. * @tsl
  27076. * @function
  27077. * @param {string} name - The property name that should be referenced by the node.
  27078. * @param {string} inputType - The node data type of the reference.
  27079. * @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.
  27080. * @returns {UserDataNode}
  27081. */
  27082. const userData = ( name, inputType, userData ) => new UserDataNode( name, inputType, userData );
  27083. const _objectData = new WeakMap();
  27084. /**
  27085. * A node for representing motion or velocity vectors. Foundation
  27086. * for advanced post processing effects like motion blur or TRAA.
  27087. *
  27088. * The node keeps track of the model, view and projection matrices
  27089. * of the previous frame and uses them to compute offsets in NDC space.
  27090. * These offsets represent the final velocity.
  27091. *
  27092. * @augments TempNode
  27093. */
  27094. class VelocityNode extends TempNode {
  27095. static get type() {
  27096. return 'VelocityNode';
  27097. }
  27098. /**
  27099. * Constructs a new vertex color node.
  27100. */
  27101. constructor() {
  27102. super( 'vec2' );
  27103. /**
  27104. * The current projection matrix.
  27105. *
  27106. * @type {?Matrix4}
  27107. * @default null
  27108. */
  27109. this.projectionMatrix = null;
  27110. /**
  27111. * Overwritten since velocity nodes are updated per object.
  27112. *
  27113. * @type {string}
  27114. * @default 'object'
  27115. */
  27116. this.updateType = NodeUpdateType.OBJECT;
  27117. /**
  27118. * Overwritten since velocity nodes save data after the update.
  27119. *
  27120. * @type {string}
  27121. * @default 'object'
  27122. */
  27123. this.updateAfterType = NodeUpdateType.OBJECT;
  27124. /**
  27125. * Uniform node representing the previous model matrix in world space.
  27126. *
  27127. * @type {UniformNode<mat4>}
  27128. * @default null
  27129. */
  27130. this.previousModelWorldMatrix = uniform( new Matrix4() );
  27131. /**
  27132. * Uniform node representing the previous projection matrix.
  27133. *
  27134. * @type {UniformNode<mat4>}
  27135. * @default null
  27136. */
  27137. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  27138. /**
  27139. * Uniform node representing the previous view matrix.
  27140. *
  27141. * @type {UniformNode<mat4>}
  27142. * @default null
  27143. */
  27144. this.previousCameraViewMatrix = uniform( new Matrix4() );
  27145. }
  27146. /**
  27147. * Sets the given projection matrix.
  27148. *
  27149. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  27150. */
  27151. setProjectionMatrix( projectionMatrix ) {
  27152. this.projectionMatrix = projectionMatrix;
  27153. }
  27154. /**
  27155. * Updates velocity specific uniforms.
  27156. *
  27157. * @param {NodeFrame} frame - A reference to the current node frame.
  27158. */
  27159. update( { frameId, camera, object } ) {
  27160. const previousModelMatrix = getPreviousMatrix( object );
  27161. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  27162. //
  27163. const cameraData = getData( camera );
  27164. if ( cameraData.frameId !== frameId ) {
  27165. cameraData.frameId = frameId;
  27166. if ( cameraData.previousProjectionMatrix === undefined ) {
  27167. cameraData.previousProjectionMatrix = new Matrix4();
  27168. cameraData.previousCameraViewMatrix = new Matrix4();
  27169. cameraData.currentProjectionMatrix = new Matrix4();
  27170. cameraData.currentCameraViewMatrix = new Matrix4();
  27171. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  27172. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  27173. } else {
  27174. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  27175. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  27176. }
  27177. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  27178. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  27179. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  27180. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  27181. }
  27182. }
  27183. /**
  27184. * Overwritten to updated velocity specific uniforms.
  27185. *
  27186. * @param {NodeFrame} frame - A reference to the current node frame.
  27187. */
  27188. updateAfter( { object } ) {
  27189. getPreviousMatrix( object ).copy( object.matrixWorld );
  27190. }
  27191. /**
  27192. * Implements the velocity computation based on the previous and current vertex data.
  27193. *
  27194. * @param {NodeBuilder} builder - A reference to the current node builder.
  27195. * @return {Node<vec2>} The motion vector.
  27196. */
  27197. setup( /*builder*/ ) {
  27198. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  27199. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  27200. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  27201. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  27202. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  27203. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  27204. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  27205. return velocity;
  27206. }
  27207. }
  27208. function getData( object ) {
  27209. let objectData = _objectData.get( object );
  27210. if ( objectData === undefined ) {
  27211. objectData = {};
  27212. _objectData.set( object, objectData );
  27213. }
  27214. return objectData;
  27215. }
  27216. function getPreviousMatrix( object, index = 0 ) {
  27217. const objectData = getData( object );
  27218. let matrix = objectData[ index ];
  27219. if ( matrix === undefined ) {
  27220. objectData[ index ] = matrix = new Matrix4();
  27221. objectData[ index ].copy( object.matrixWorld );
  27222. }
  27223. return matrix;
  27224. }
  27225. /**
  27226. * TSL object that represents the velocity of a render pass.
  27227. *
  27228. * @tsl
  27229. * @type {VelocityNode}
  27230. */
  27231. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  27232. /**
  27233. * Computes a grayscale value for the given RGB color value.
  27234. *
  27235. * @tsl
  27236. * @function
  27237. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  27238. * @return {Node<vec3>} The grayscale color.
  27239. */
  27240. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  27241. return luminance( color.rgb );
  27242. } );
  27243. /**
  27244. * Super-saturates or desaturates the given RGB color.
  27245. *
  27246. * @tsl
  27247. * @function
  27248. * @param {Node<vec3>} color - The input color.
  27249. * @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.
  27250. * @return {Node<vec3>} The saturated color.
  27251. */
  27252. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  27253. return adjustment.mix( luminance( color.rgb ), color.rgb );
  27254. } );
  27255. /**
  27256. * Selectively enhance the intensity of less saturated RGB colors. Can result
  27257. * in a more natural and visually appealing image with enhanced color depth
  27258. * compared to {@link ColorAdjustment#saturation}.
  27259. *
  27260. * @tsl
  27261. * @function
  27262. * @param {Node<vec3>} color - The input color.
  27263. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  27264. * @return {Node<vec3>} The updated color.
  27265. */
  27266. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  27267. const average = add( color.r, color.g, color.b ).div( 3.0 );
  27268. const mx = color.r.max( color.g.max( color.b ) );
  27269. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  27270. return mix( color.rgb, mx, amt );
  27271. } );
  27272. /**
  27273. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  27274. *
  27275. * @tsl
  27276. * @function
  27277. * @param {Node<vec3>} color - The input color.
  27278. * @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.
  27279. * @return {Node<vec3>} The updated color.
  27280. */
  27281. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  27282. const k = vec3( 0.57735, 0.57735, 0.57735 );
  27283. const cosAngle = adjustment.cos();
  27284. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  27285. } );
  27286. /**
  27287. * Computes the luminance for the given RGB color value.
  27288. *
  27289. * @tsl
  27290. * @function
  27291. * @param {Node<vec3>} color - The color value to compute the luminance for.
  27292. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  27293. * @return {Node<float>} The luminance.
  27294. */
  27295. const luminance = (
  27296. color,
  27297. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  27298. ) => dot( color, luminanceCoefficients );
  27299. /**
  27300. * Color Decision List (CDL) v1.2
  27301. *
  27302. * Compact representation of color grading information, defined by slope, offset, power, and
  27303. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  27304. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  27305. *
  27306. * @tsl
  27307. * @function
  27308. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  27309. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  27310. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  27311. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  27312. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  27313. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  27314. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  27315. *
  27316. * References:
  27317. * - ASC CDL v1.2
  27318. * - {@link https://blender.stackexchange.com/a/55239/43930}
  27319. * - {@link https://docs.acescentral.com/specifications/acescc/}
  27320. */
  27321. const cdl = /*@__PURE__*/ Fn( ( [
  27322. color,
  27323. slope = vec3( 1 ),
  27324. offset = vec3( 0 ),
  27325. power = vec3( 1 ),
  27326. saturation = float( 1 ),
  27327. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  27328. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  27329. ] ) => {
  27330. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  27331. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  27332. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  27333. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  27334. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  27335. const pv = v.pow( power ).toVar();
  27336. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  27337. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  27338. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  27339. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  27340. return vec4( v.rgb, color.a );
  27341. } );
  27342. /**
  27343. * TSL function for creating a posterize effect which reduces the number of colors
  27344. * in an image, resulting in a more blocky and stylized appearance.
  27345. *
  27346. * @tsl
  27347. * @function
  27348. * @param {Node} sourceNode - The input color.
  27349. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  27350. * @returns {Node} The posterized color.
  27351. */
  27352. const posterize = Fn( ( [ source, steps ] ) => {
  27353. return source.mul( steps ).floor().div( steps );
  27354. } );
  27355. let _sharedFramebuffer = null;
  27356. /**
  27357. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  27358. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  27359. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  27360. *
  27361. * @augments ViewportTextureNode
  27362. */
  27363. class ViewportSharedTextureNode extends ViewportTextureNode {
  27364. static get type() {
  27365. return 'ViewportSharedTextureNode';
  27366. }
  27367. /**
  27368. * Constructs a new viewport shared texture node.
  27369. *
  27370. * @param {Node} [uvNode=screenUV] - The uv node.
  27371. * @param {?Node} [levelNode=null] - The level node.
  27372. */
  27373. constructor( uvNode = screenUV, levelNode = null ) {
  27374. if ( _sharedFramebuffer === null ) {
  27375. _sharedFramebuffer = new FramebufferTexture();
  27376. }
  27377. super( uvNode, levelNode, _sharedFramebuffer );
  27378. }
  27379. /**
  27380. * Overwritten so the method always returns the unique shared
  27381. * framebuffer texture.
  27382. *
  27383. * @return {FramebufferTexture} The shared framebuffer texture.
  27384. */
  27385. getTextureForReference() {
  27386. return _sharedFramebuffer;
  27387. }
  27388. updateReference() {
  27389. return this;
  27390. }
  27391. }
  27392. /**
  27393. * TSL function for creating a shared viewport texture node.
  27394. *
  27395. * @tsl
  27396. * @function
  27397. * @param {?Node} [uvNode=screenUV] - The uv node.
  27398. * @param {?Node} [levelNode=null] - The level node.
  27399. * @returns {ViewportSharedTextureNode}
  27400. */
  27401. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  27402. const _size = /*@__PURE__*/ new Vector2();
  27403. /**
  27404. * Represents the texture of a pass node.
  27405. *
  27406. * @augments TextureNode
  27407. */
  27408. class PassTextureNode extends TextureNode {
  27409. static get type() {
  27410. return 'PassTextureNode';
  27411. }
  27412. /**
  27413. * Constructs a new pass texture node.
  27414. *
  27415. * @param {PassNode} passNode - The pass node.
  27416. * @param {Texture} texture - The output texture.
  27417. */
  27418. constructor( passNode, texture ) {
  27419. super( texture );
  27420. /**
  27421. * A reference to the pass node.
  27422. *
  27423. * @type {PassNode}
  27424. */
  27425. this.passNode = passNode;
  27426. /**
  27427. * This flag can be used for type testing.
  27428. *
  27429. * @type {boolean}
  27430. * @default true
  27431. * @readonly
  27432. */
  27433. this.isPassTextureNode = true;
  27434. this.setUpdateMatrix( false );
  27435. }
  27436. setup( builder ) {
  27437. const properties = builder.getNodeProperties( this );
  27438. properties.passNode = this.passNode;
  27439. return super.setup( builder );
  27440. }
  27441. clone() {
  27442. return new this.constructor( this.passNode, this.value );
  27443. }
  27444. }
  27445. /**
  27446. * An extension of `PassTextureNode` which allows to manage more than one
  27447. * internal texture. Relevant for the `getPreviousTexture()` related API.
  27448. *
  27449. * @augments PassTextureNode
  27450. */
  27451. class PassMultipleTextureNode extends PassTextureNode {
  27452. static get type() {
  27453. return 'PassMultipleTextureNode';
  27454. }
  27455. /**
  27456. * Constructs a new pass texture node.
  27457. *
  27458. * @param {PassNode} passNode - The pass node.
  27459. * @param {string} textureName - The output texture name.
  27460. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  27461. */
  27462. constructor( passNode, textureName, previousTexture = false ) {
  27463. // null is passed to the super call since this class does not
  27464. // use an external texture for rendering pass data into. Instead
  27465. // the texture is managed by the pass node itself
  27466. super( passNode, null );
  27467. /**
  27468. * The output texture name.
  27469. *
  27470. * @type {string}
  27471. */
  27472. this.textureName = textureName;
  27473. /**
  27474. * Whether previous frame data should be used or not.
  27475. *
  27476. * @type {boolean}
  27477. */
  27478. this.previousTexture = previousTexture;
  27479. /**
  27480. * This flag can be used for type testing.
  27481. *
  27482. * @type {boolean}
  27483. * @default true
  27484. * @readonly
  27485. */
  27486. this.isPassMultipleTextureNode = true;
  27487. }
  27488. /**
  27489. * Updates the texture reference of this node.
  27490. */
  27491. updateTexture() {
  27492. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  27493. }
  27494. setup( builder ) {
  27495. this.updateTexture();
  27496. return super.setup( builder );
  27497. }
  27498. clone() {
  27499. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  27500. newNode.uvNode = this.uvNode;
  27501. newNode.levelNode = this.levelNode;
  27502. newNode.biasNode = this.biasNode;
  27503. newNode.sampler = this.sampler;
  27504. newNode.depthNode = this.depthNode;
  27505. newNode.compareNode = this.compareNode;
  27506. newNode.gradNode = this.gradNode;
  27507. newNode.offsetNode = this.offsetNode;
  27508. return newNode;
  27509. }
  27510. }
  27511. /**
  27512. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  27513. * This pass produces a render for the given scene and camera and can provide multiple outputs
  27514. * via MRT for further processing.
  27515. *
  27516. * ```js
  27517. * const postProcessing = new RenderPipeline( renderer );
  27518. *
  27519. * const scenePass = pass( scene, camera );
  27520. *
  27521. * postProcessing.outputNode = scenePass;
  27522. * ```
  27523. *
  27524. * @augments TempNode
  27525. */
  27526. class PassNode extends TempNode {
  27527. static get type() {
  27528. return 'PassNode';
  27529. }
  27530. /**
  27531. * Constructs a new pass node.
  27532. *
  27533. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  27534. * @param {Scene} scene - A reference to the scene.
  27535. * @param {Camera} camera - A reference to the camera.
  27536. * @param {Object} options - Options for the internal render target.
  27537. */
  27538. constructor( scope, scene, camera, options = {} ) {
  27539. super( 'vec4' );
  27540. /**
  27541. * The scope of the pass. The scope determines whether the node outputs color or depth.
  27542. *
  27543. * @type {('color'|'depth')}
  27544. */
  27545. this.scope = scope;
  27546. /**
  27547. * A reference to the scene.
  27548. *
  27549. * @type {Scene}
  27550. */
  27551. this.scene = scene;
  27552. /**
  27553. * A reference to the camera.
  27554. *
  27555. * @type {Camera}
  27556. */
  27557. this.camera = camera;
  27558. /**
  27559. * Options for the internal render target.
  27560. *
  27561. * @type {Object}
  27562. */
  27563. this.options = options;
  27564. /**
  27565. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  27566. *
  27567. * @private
  27568. * @type {number}
  27569. * @default 1
  27570. */
  27571. this._pixelRatio = 1;
  27572. /**
  27573. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  27574. * @private
  27575. * @type {number}
  27576. * @default 1
  27577. */
  27578. this._width = 1;
  27579. /**
  27580. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  27581. * @private
  27582. * @type {number}
  27583. * @default 1
  27584. */
  27585. this._height = 1;
  27586. const depthTexture = new DepthTexture();
  27587. depthTexture.isRenderTargetTexture = true;
  27588. //depthTexture.type = FloatType;
  27589. depthTexture.name = 'depth';
  27590. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  27591. renderTarget.texture.name = 'output';
  27592. renderTarget.depthTexture = depthTexture;
  27593. /**
  27594. * The pass's render target.
  27595. *
  27596. * @type {RenderTarget}
  27597. */
  27598. this.renderTarget = renderTarget;
  27599. /**
  27600. * An optional override material for the pass.
  27601. *
  27602. * @type {Material|null}
  27603. */
  27604. this.overrideMaterial = null;
  27605. /**
  27606. * Whether the pass is transparent.
  27607. *
  27608. * @type {boolean}
  27609. * @default false
  27610. */
  27611. this.transparent = true;
  27612. /**
  27613. * Whether the pass is opaque.
  27614. *
  27615. * @type {boolean}
  27616. * @default true
  27617. */
  27618. this.opaque = true;
  27619. /**
  27620. * An optional global context for the pass.
  27621. *
  27622. * @type {ContextNode|null}
  27623. */
  27624. this.contextNode = null;
  27625. /**
  27626. * A cache for the context node.
  27627. *
  27628. * @private
  27629. * @type {?Object}
  27630. * @default null
  27631. */
  27632. this._contextNodeCache = null;
  27633. /**
  27634. * A dictionary holding the internal result textures.
  27635. *
  27636. * @private
  27637. * @type {Object<string, Texture>}
  27638. */
  27639. this._textures = {
  27640. output: renderTarget.texture,
  27641. depth: depthTexture
  27642. };
  27643. /**
  27644. * A dictionary holding the internal texture nodes.
  27645. *
  27646. * @private
  27647. * @type {Object<string, TextureNode>}
  27648. */
  27649. this._textureNodes = {};
  27650. /**
  27651. * A dictionary holding the internal depth nodes.
  27652. *
  27653. * @private
  27654. * @type {Object}
  27655. */
  27656. this._linearDepthNodes = {};
  27657. /**
  27658. * A dictionary holding the internal viewZ nodes.
  27659. *
  27660. * @private
  27661. * @type {Object}
  27662. */
  27663. this._viewZNodes = {};
  27664. /**
  27665. * A dictionary holding the texture data of the previous frame.
  27666. * Used for computing velocity/motion vectors.
  27667. *
  27668. * @private
  27669. * @type {Object<string, Texture>}
  27670. */
  27671. this._previousTextures = {};
  27672. /**
  27673. * A dictionary holding the texture nodes of the previous frame.
  27674. * Used for computing velocity/motion vectors.
  27675. *
  27676. * @private
  27677. * @type {Object<string, TextureNode>}
  27678. */
  27679. this._previousTextureNodes = {};
  27680. /**
  27681. * The `near` property of the camera as a uniform.
  27682. *
  27683. * @private
  27684. * @type {UniformNode}
  27685. */
  27686. this._cameraNear = uniform( 0 );
  27687. /**
  27688. * The `far` property of the camera as a uniform.
  27689. *
  27690. * @private
  27691. * @type {UniformNode}
  27692. */
  27693. this._cameraFar = uniform( 0 );
  27694. /**
  27695. * A MRT node configuring the MRT settings.
  27696. *
  27697. * @private
  27698. * @type {?MRTNode}
  27699. * @default null
  27700. */
  27701. this._mrt = null;
  27702. /**
  27703. * Layer object for configuring the camera that is used
  27704. * to produce the pass.
  27705. *
  27706. * @private
  27707. * @type {?Layers}
  27708. * @default null
  27709. */
  27710. this._layers = null;
  27711. /**
  27712. * Scales the resolution of the internal render target.
  27713. *
  27714. * @private
  27715. * @type {number}
  27716. * @default 1
  27717. */
  27718. this._resolutionScale = 1;
  27719. /**
  27720. * Custom viewport definition.
  27721. *
  27722. * @private
  27723. * @type {?Vector4}
  27724. * @default null
  27725. */
  27726. this._viewport = null;
  27727. /**
  27728. * Custom scissor definition.
  27729. *
  27730. * @private
  27731. * @type {?Vector4}
  27732. * @default null
  27733. */
  27734. this._scissor = null;
  27735. /**
  27736. * This flag can be used for type testing.
  27737. *
  27738. * @type {boolean}
  27739. * @readonly
  27740. * @default true
  27741. */
  27742. this.isPassNode = true;
  27743. /**
  27744. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  27745. * scene once per frame in its {@link PassNode#updateBefore} method.
  27746. *
  27747. * @type {string}
  27748. * @default 'frame'
  27749. */
  27750. this.updateBeforeType = NodeUpdateType.FRAME;
  27751. /**
  27752. * This flag is used for global cache.
  27753. *
  27754. * @type {boolean}
  27755. * @default true
  27756. */
  27757. this.global = true;
  27758. }
  27759. /**
  27760. * Sets the resolution scale for the pass.
  27761. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  27762. *
  27763. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  27764. * @return {PassNode} A reference to this pass.
  27765. */
  27766. setResolutionScale( resolutionScale ) {
  27767. this._resolutionScale = resolutionScale;
  27768. return this;
  27769. }
  27770. /**
  27771. * Gets the current resolution scale of the pass.
  27772. *
  27773. * @return {number} The current resolution scale. A value of `1` means full resolution.
  27774. */
  27775. getResolutionScale() {
  27776. return this._resolutionScale;
  27777. }
  27778. /**
  27779. * Sets the resolution for the pass.
  27780. * The resolution is a factor that is multiplied with the renderer's width and height.
  27781. *
  27782. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  27783. * @return {PassNode} A reference to this pass.
  27784. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  27785. */
  27786. setResolution( resolution ) { // @deprecated, r181
  27787. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  27788. return this.setResolutionScale( resolution );
  27789. }
  27790. /**
  27791. * Gets the current resolution of the pass.
  27792. *
  27793. * @return {number} The current resolution. A value of `1` means full resolution.
  27794. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  27795. */
  27796. getResolution() { // @deprecated, r181
  27797. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  27798. return this.getResolutionScale();
  27799. }
  27800. /**
  27801. * Sets the layer configuration that should be used when rendering the pass.
  27802. *
  27803. * @param {Layers} layers - The layers object to set.
  27804. * @return {PassNode} A reference to this pass.
  27805. */
  27806. setLayers( layers ) {
  27807. this._layers = layers;
  27808. return this;
  27809. }
  27810. /**
  27811. * Gets the current layer configuration of the pass.
  27812. *
  27813. * @return {?Layers} .
  27814. */
  27815. getLayers() {
  27816. return this._layers;
  27817. }
  27818. /**
  27819. * Sets the given MRT node to setup MRT for this pass.
  27820. *
  27821. * @param {MRTNode} mrt - The MRT object.
  27822. * @return {PassNode} A reference to this pass.
  27823. */
  27824. setMRT( mrt ) {
  27825. this._mrt = mrt;
  27826. return this;
  27827. }
  27828. /**
  27829. * Returns the current MRT node.
  27830. *
  27831. * @return {MRTNode} The current MRT node.
  27832. */
  27833. getMRT() {
  27834. return this._mrt;
  27835. }
  27836. /**
  27837. * Returns the texture for the given output name.
  27838. *
  27839. * @param {string} name - The output name to get the texture for.
  27840. * @return {Texture} The texture.
  27841. */
  27842. getTexture( name ) {
  27843. let texture = this._textures[ name ];
  27844. if ( texture === undefined ) {
  27845. const refTexture = this.renderTarget.texture;
  27846. texture = refTexture.clone();
  27847. texture.name = name;
  27848. this._textures[ name ] = texture;
  27849. this.renderTarget.textures.push( texture );
  27850. }
  27851. return texture;
  27852. }
  27853. /**
  27854. * Returns the texture holding the data of the previous frame for the given output name.
  27855. *
  27856. * @param {string} name - The output name to get the texture for.
  27857. * @return {Texture} The texture holding the data of the previous frame.
  27858. */
  27859. getPreviousTexture( name ) {
  27860. let texture = this._previousTextures[ name ];
  27861. if ( texture === undefined ) {
  27862. texture = this.getTexture( name ).clone();
  27863. this._previousTextures[ name ] = texture;
  27864. }
  27865. return texture;
  27866. }
  27867. /**
  27868. * Switches current and previous textures for the given output name.
  27869. *
  27870. * @param {string} name - The output name.
  27871. */
  27872. toggleTexture( name ) {
  27873. const prevTexture = this._previousTextures[ name ];
  27874. if ( prevTexture !== undefined ) {
  27875. const texture = this._textures[ name ];
  27876. const index = this.renderTarget.textures.indexOf( texture );
  27877. this.renderTarget.textures[ index ] = prevTexture;
  27878. this._textures[ name ] = prevTexture;
  27879. this._previousTextures[ name ] = texture;
  27880. this._textureNodes[ name ].updateTexture();
  27881. this._previousTextureNodes[ name ].updateTexture();
  27882. }
  27883. }
  27884. /**
  27885. * Returns the texture node for the given output name.
  27886. *
  27887. * @param {string} [name='output'] - The output name to get the texture node for.
  27888. * @return {TextureNode} The texture node.
  27889. */
  27890. getTextureNode( name = 'output' ) {
  27891. let textureNode = this._textureNodes[ name ];
  27892. if ( textureNode === undefined ) {
  27893. textureNode = new PassMultipleTextureNode( this, name );
  27894. textureNode.updateTexture();
  27895. this._textureNodes[ name ] = textureNode;
  27896. }
  27897. return textureNode;
  27898. }
  27899. /**
  27900. * Returns the previous texture node for the given output name.
  27901. *
  27902. * @param {string} [name='output'] - The output name to get the previous texture node for.
  27903. * @return {TextureNode} The previous texture node.
  27904. */
  27905. getPreviousTextureNode( name = 'output' ) {
  27906. let textureNode = this._previousTextureNodes[ name ];
  27907. if ( textureNode === undefined ) {
  27908. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  27909. textureNode = new PassMultipleTextureNode( this, name, true );
  27910. textureNode.updateTexture();
  27911. this._previousTextureNodes[ name ] = textureNode;
  27912. }
  27913. return textureNode;
  27914. }
  27915. /**
  27916. * Returns a viewZ node of this pass.
  27917. *
  27918. * @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.
  27919. * @return {Node} The viewZ node.
  27920. */
  27921. getViewZNode( name = 'depth' ) {
  27922. let viewZNode = this._viewZNodes[ name ];
  27923. if ( viewZNode === undefined ) {
  27924. const cameraNear = this._cameraNear;
  27925. const cameraFar = this._cameraFar;
  27926. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  27927. }
  27928. return viewZNode;
  27929. }
  27930. /**
  27931. * Returns a linear depth node of this pass.
  27932. *
  27933. * @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.
  27934. * @return {Node} The linear depth node.
  27935. */
  27936. getLinearDepthNode( name = 'depth' ) {
  27937. let linearDepthNode = this._linearDepthNodes[ name ];
  27938. if ( linearDepthNode === undefined ) {
  27939. const cameraNear = this._cameraNear;
  27940. const cameraFar = this._cameraFar;
  27941. const viewZNode = this.getViewZNode( name );
  27942. // TODO: just if ( builder.camera.isPerspectiveCamera )
  27943. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  27944. }
  27945. return linearDepthNode;
  27946. }
  27947. /**
  27948. * Precompiles the pass.
  27949. *
  27950. * Note that this method must be called after the pass configuration is complete.
  27951. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  27952. *
  27953. * @async
  27954. * @param {Renderer} renderer - The renderer.
  27955. * @return {Promise} A Promise that resolves when the compile has been finished.
  27956. * @see {@link Renderer#compileAsync}
  27957. */
  27958. async compileAsync( renderer ) {
  27959. const currentRenderTarget = renderer.getRenderTarget();
  27960. const currentMRT = renderer.getMRT();
  27961. renderer.setRenderTarget( this.renderTarget );
  27962. renderer.setMRT( this._mrt );
  27963. await renderer.compileAsync( this.scene, this.camera );
  27964. renderer.setRenderTarget( currentRenderTarget );
  27965. renderer.setMRT( currentMRT );
  27966. }
  27967. setup( { renderer } ) {
  27968. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  27969. this.renderTarget.texture.type = renderer.getOutputBufferType();
  27970. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  27971. }
  27972. updateBefore( frame ) {
  27973. const { renderer } = frame;
  27974. const { scene } = this;
  27975. let camera;
  27976. let pixelRatio;
  27977. const outputRenderTarget = renderer.getOutputRenderTarget();
  27978. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  27979. pixelRatio = 1;
  27980. camera = renderer.xr.getCamera();
  27981. renderer.xr.updateCamera( camera );
  27982. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  27983. } else {
  27984. camera = this.camera;
  27985. pixelRatio = renderer.getPixelRatio();
  27986. renderer.getSize( _size );
  27987. }
  27988. this._pixelRatio = pixelRatio;
  27989. this.setSize( _size.width, _size.height );
  27990. const currentRenderTarget = renderer.getRenderTarget();
  27991. const currentMRT = renderer.getMRT();
  27992. const currentAutoClear = renderer.autoClear;
  27993. const currentTransparent = renderer.transparent;
  27994. const currentOpaque = renderer.opaque;
  27995. const currentMask = camera.layers.mask;
  27996. const currentContextNode = renderer.contextNode;
  27997. const currentOverrideMaterial = scene.overrideMaterial;
  27998. this._cameraNear.value = camera.near;
  27999. this._cameraFar.value = camera.far;
  28000. if ( this._layers !== null ) {
  28001. camera.layers.mask = this._layers.mask;
  28002. }
  28003. for ( const name in this._previousTextures ) {
  28004. this.toggleTexture( name );
  28005. }
  28006. if ( this.overrideMaterial !== null ) {
  28007. scene.overrideMaterial = this.overrideMaterial;
  28008. }
  28009. renderer.setRenderTarget( this.renderTarget );
  28010. renderer.setMRT( this._mrt );
  28011. renderer.autoClear = true;
  28012. renderer.transparent = this.transparent;
  28013. renderer.opaque = this.opaque;
  28014. if ( this.contextNode !== null ) {
  28015. if ( this._contextNodeCache === null || this._contextNodeCache.version !== this.version ) {
  28016. this._contextNodeCache = {
  28017. version: this.version,
  28018. context: context( { ...renderer.contextNode.getFlowContextData(), ...this.contextNode.getFlowContextData() } )
  28019. };
  28020. }
  28021. renderer.contextNode = this._contextNodeCache.context;
  28022. }
  28023. const currentSceneName = scene.name;
  28024. scene.name = this.name ? this.name : scene.name;
  28025. renderer.render( scene, camera );
  28026. scene.name = currentSceneName;
  28027. scene.overrideMaterial = currentOverrideMaterial;
  28028. renderer.setRenderTarget( currentRenderTarget );
  28029. renderer.setMRT( currentMRT );
  28030. renderer.autoClear = currentAutoClear;
  28031. renderer.transparent = currentTransparent;
  28032. renderer.opaque = currentOpaque;
  28033. renderer.contextNode = currentContextNode;
  28034. camera.layers.mask = currentMask;
  28035. }
  28036. /**
  28037. * Sets the size of the pass's render target. Honors the pixel ratio.
  28038. *
  28039. * @param {number} width - The width to set.
  28040. * @param {number} height - The height to set.
  28041. */
  28042. setSize( width, height ) {
  28043. this._width = width;
  28044. this._height = height;
  28045. const effectiveWidth = Math.floor( this._width * this._pixelRatio * this._resolutionScale );
  28046. const effectiveHeight = Math.floor( this._height * this._pixelRatio * this._resolutionScale );
  28047. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  28048. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  28049. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  28050. }
  28051. /**
  28052. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  28053. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  28054. * with `null` as the single argument.
  28055. *
  28056. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  28057. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  28058. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  28059. * @param {number} width - The width of the scissor box in logical pixel unit.
  28060. * @param {number} height - The height of the scissor box in logical pixel unit.
  28061. */
  28062. setScissor( x, y, width, height ) {
  28063. if ( x === null ) {
  28064. this._scissor = null;
  28065. } else {
  28066. if ( this._scissor === null ) this._scissor = new Vector4();
  28067. if ( x.isVector4 ) {
  28068. this._scissor.copy( x );
  28069. } else {
  28070. this._scissor.set( x, y, width, height );
  28071. }
  28072. this._scissor.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  28073. }
  28074. }
  28075. /**
  28076. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  28077. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  28078. * with `null` as the single argument.
  28079. *
  28080. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  28081. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  28082. * @param {number} width - The width of the viewport in logical pixel unit.
  28083. * @param {number} height - The height of the viewport in logical pixel unit.
  28084. */
  28085. setViewport( x, y, width, height ) {
  28086. if ( x === null ) {
  28087. this._viewport = null;
  28088. } else {
  28089. if ( this._viewport === null ) this._viewport = new Vector4();
  28090. if ( x.isVector4 ) {
  28091. this._viewport.copy( x );
  28092. } else {
  28093. this._viewport.set( x, y, width, height );
  28094. }
  28095. this._viewport.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  28096. }
  28097. }
  28098. /**
  28099. * Sets the pixel ratio the pass's render target and updates the size.
  28100. *
  28101. * @param {number} pixelRatio - The pixel ratio to set.
  28102. */
  28103. setPixelRatio( pixelRatio ) {
  28104. this._pixelRatio = pixelRatio;
  28105. this.setSize( this._width, this._height );
  28106. }
  28107. /**
  28108. * Frees internal resources. Should be called when the node is no longer in use.
  28109. */
  28110. dispose() {
  28111. this.renderTarget.dispose();
  28112. }
  28113. }
  28114. /**
  28115. * @static
  28116. * @type {'color'}
  28117. * @default 'color'
  28118. */
  28119. PassNode.COLOR = 'color';
  28120. /**
  28121. * @static
  28122. * @type {'depth'}
  28123. * @default 'depth'
  28124. */
  28125. PassNode.DEPTH = 'depth';
  28126. /**
  28127. * TSL function for creating a pass node.
  28128. *
  28129. * @tsl
  28130. * @function
  28131. * @param {Scene} scene - A reference to the scene.
  28132. * @param {Camera} camera - A reference to the camera.
  28133. * @param {Object} options - Options for the internal render target.
  28134. * @returns {PassNode}
  28135. */
  28136. const pass = ( scene, camera, options ) => new PassNode( PassNode.COLOR, scene, camera, options );
  28137. /**
  28138. * TSL function for creating a pass texture node.
  28139. *
  28140. * @tsl
  28141. * @function
  28142. * @param {PassNode} pass - The pass node.
  28143. * @param {Texture} texture - The output texture.
  28144. * @returns {PassTextureNode}
  28145. */
  28146. const passTexture = ( pass, texture ) => new PassTextureNode( pass, texture );
  28147. /**
  28148. * TSL function for creating a depth pass node.
  28149. *
  28150. * @tsl
  28151. * @function
  28152. * @param {Scene} scene - A reference to the scene.
  28153. * @param {Camera} camera - A reference to the camera.
  28154. * @param {Object} options - Options for the internal render target.
  28155. * @returns {PassNode}
  28156. */
  28157. const depthPass = ( scene, camera, options ) => new PassNode( PassNode.DEPTH, scene, camera, options );
  28158. /**
  28159. * Represents a render pass for producing a toon outline effect on compatible objects.
  28160. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  28161. * will receive the outline.
  28162. *
  28163. * ```js
  28164. * const postProcessing = new RenderPipeline( renderer );
  28165. *
  28166. * const scenePass = toonOutlinePass( scene, camera );
  28167. *
  28168. * postProcessing.outputNode = scenePass;
  28169. * ```
  28170. * @augments PassNode
  28171. */
  28172. class ToonOutlinePassNode extends PassNode {
  28173. static get type() {
  28174. return 'ToonOutlinePassNode';
  28175. }
  28176. /**
  28177. * Constructs a new outline pass node.
  28178. *
  28179. * @param {Scene} scene - A reference to the scene.
  28180. * @param {Camera} camera - A reference to the camera.
  28181. * @param {Node} colorNode - Defines the outline's color.
  28182. * @param {Node} thicknessNode - Defines the outline's thickness.
  28183. * @param {Node} alphaNode - Defines the outline's alpha.
  28184. */
  28185. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  28186. super( PassNode.COLOR, scene, camera );
  28187. /**
  28188. * Defines the outline's color.
  28189. *
  28190. * @type {Node}
  28191. */
  28192. this.colorNode = colorNode;
  28193. /**
  28194. * Defines the outline's thickness.
  28195. *
  28196. * @type {Node}
  28197. */
  28198. this.thicknessNode = thicknessNode;
  28199. /**
  28200. * Defines the outline's alpha.
  28201. *
  28202. * @type {Node}
  28203. */
  28204. this.alphaNode = alphaNode;
  28205. /**
  28206. * An internal material cache.
  28207. *
  28208. * @private
  28209. * @type {WeakMap<Material, NodeMaterial>}
  28210. */
  28211. this._materialCache = new WeakMap();
  28212. /**
  28213. * The name of this pass.
  28214. *
  28215. * @type {string}
  28216. * @default 'Outline Pass'
  28217. */
  28218. this.name = 'Outline Pass';
  28219. }
  28220. updateBefore( frame ) {
  28221. const { renderer } = frame;
  28222. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  28223. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  28224. // only render outline for supported materials
  28225. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  28226. if ( material.wireframe === false ) {
  28227. const outlineMaterial = this._getOutlineMaterial( material );
  28228. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  28229. }
  28230. }
  28231. // default
  28232. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  28233. } );
  28234. super.updateBefore( frame );
  28235. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  28236. }
  28237. /**
  28238. * Creates the material used for outline rendering.
  28239. *
  28240. * @private
  28241. * @return {NodeMaterial} The outline material.
  28242. */
  28243. _createMaterial() {
  28244. const material = new NodeMaterial();
  28245. material.isMeshToonOutlineMaterial = true;
  28246. material.name = 'Toon_Outline';
  28247. material.side = BackSide;
  28248. // vertex node
  28249. const outlineNormal = normalLocal.negate();
  28250. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  28251. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  28252. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  28253. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  28254. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  28255. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  28256. // color node
  28257. material.colorNode = vec4( this.colorNode, this.alphaNode );
  28258. return material;
  28259. }
  28260. /**
  28261. * For the given toon material, this method returns a corresponding
  28262. * outline material.
  28263. *
  28264. * @private
  28265. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  28266. * @return {NodeMaterial} The outline material.
  28267. */
  28268. _getOutlineMaterial( originalMaterial ) {
  28269. let outlineMaterial = this._materialCache.get( originalMaterial );
  28270. if ( outlineMaterial === undefined ) {
  28271. outlineMaterial = this._createMaterial();
  28272. this._materialCache.set( originalMaterial, outlineMaterial );
  28273. }
  28274. return outlineMaterial;
  28275. }
  28276. }
  28277. /**
  28278. * TSL function for creating a toon outline pass node.
  28279. *
  28280. * @tsl
  28281. * @function
  28282. * @param {Scene} scene - A reference to the scene.
  28283. * @param {Camera} camera - A reference to the camera.
  28284. * @param {Color} color - Defines the outline's color.
  28285. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  28286. * @param {number} [alpha=1] - Defines the outline's alpha.
  28287. * @returns {ToonOutlinePassNode}
  28288. */
  28289. const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) );
  28290. /**
  28291. * Linear tone mapping, exposure only.
  28292. *
  28293. * @tsl
  28294. * @function
  28295. * @param {Node<vec3>} color - The color that should be tone mapped.
  28296. * @param {Node<float>} exposure - The exposure.
  28297. * @return {Node<vec3>} The tone mapped color.
  28298. */
  28299. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28300. return color.mul( exposure ).clamp();
  28301. } ).setLayout( {
  28302. name: 'linearToneMapping',
  28303. type: 'vec3',
  28304. inputs: [
  28305. { name: 'color', type: 'vec3' },
  28306. { name: 'exposure', type: 'float' }
  28307. ]
  28308. } );
  28309. /**
  28310. * Reinhard tone mapping.
  28311. *
  28312. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  28313. *
  28314. * @tsl
  28315. * @function
  28316. * @param {Node<vec3>} color - The color that should be tone mapped.
  28317. * @param {Node<float>} exposure - The exposure.
  28318. * @return {Node<vec3>} The tone mapped color.
  28319. */
  28320. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28321. color = color.mul( exposure );
  28322. return color.div( color.add( 1.0 ) ).clamp();
  28323. } ).setLayout( {
  28324. name: 'reinhardToneMapping',
  28325. type: 'vec3',
  28326. inputs: [
  28327. { name: 'color', type: 'vec3' },
  28328. { name: 'exposure', type: 'float' }
  28329. ]
  28330. } );
  28331. /**
  28332. * Cineon tone mapping.
  28333. *
  28334. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  28335. *
  28336. * @tsl
  28337. * @function
  28338. * @param {Node<vec3>} color - The color that should be tone mapped.
  28339. * @param {Node<float>} exposure - The exposure.
  28340. * @return {Node<vec3>} The tone mapped color.
  28341. */
  28342. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28343. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  28344. color = color.mul( exposure );
  28345. color = color.sub( 0.004 ).max( 0.0 );
  28346. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  28347. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  28348. return a.div( b ).pow( 2.2 );
  28349. } ).setLayout( {
  28350. name: 'cineonToneMapping',
  28351. type: 'vec3',
  28352. inputs: [
  28353. { name: 'color', type: 'vec3' },
  28354. { name: 'exposure', type: 'float' }
  28355. ]
  28356. } );
  28357. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  28358. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  28359. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  28360. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  28361. return a.div( b );
  28362. } );
  28363. /**
  28364. * ACESFilmic tone mapping.
  28365. *
  28366. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  28367. *
  28368. * @tsl
  28369. * @function
  28370. * @param {Node<vec3>} color - The color that should be tone mapped.
  28371. * @param {Node<float>} exposure - The exposure.
  28372. * @return {Node<vec3>} The tone mapped color.
  28373. */
  28374. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28375. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  28376. const ACESInputMat = mat3(
  28377. 0.59719, 0.35458, 0.04823,
  28378. 0.07600, 0.90834, 0.01566,
  28379. 0.02840, 0.13383, 0.83777
  28380. );
  28381. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  28382. const ACESOutputMat = mat3(
  28383. 1.60475, -0.53108, -0.07367,
  28384. -0.10208, 1.10813, -605e-5,
  28385. -327e-5, -0.07276, 1.07602
  28386. );
  28387. color = color.mul( exposure ).div( 0.6 );
  28388. color = ACESInputMat.mul( color );
  28389. // Apply RRT and ODT
  28390. color = RRTAndODTFit( color );
  28391. color = ACESOutputMat.mul( color );
  28392. // Clamp to [0, 1]
  28393. return color.clamp();
  28394. } ).setLayout( {
  28395. name: 'acesFilmicToneMapping',
  28396. type: 'vec3',
  28397. inputs: [
  28398. { name: 'color', type: 'vec3' },
  28399. { name: 'exposure', type: 'float' }
  28400. ]
  28401. } );
  28402. 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 ) );
  28403. 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 ) );
  28404. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28405. const x = vec3( x_immutable ).toVar();
  28406. const x2 = vec3( x.mul( x ) ).toVar();
  28407. const x4 = vec3( x2.mul( x2 ) ).toVar();
  28408. 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 ) ) ) );
  28409. } );
  28410. /**
  28411. * AgX tone mapping.
  28412. *
  28413. * @tsl
  28414. * @function
  28415. * @param {Node<vec3>} color - The color that should be tone mapped.
  28416. * @param {Node<float>} exposure - The exposure.
  28417. * @return {Node<vec3>} The tone mapped color.
  28418. */
  28419. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28420. const colortone = vec3( color ).toVar();
  28421. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  28422. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  28423. const AgxMinEv = float( -12.47393 );
  28424. const AgxMaxEv = float( 4.026069 );
  28425. colortone.mulAssign( exposure );
  28426. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  28427. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  28428. colortone.assign( max$1( colortone, 1e-10 ) );
  28429. colortone.assign( log2( colortone ) );
  28430. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  28431. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  28432. colortone.assign( agxDefaultContrastApprox( colortone ) );
  28433. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  28434. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  28435. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  28436. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  28437. return colortone;
  28438. } ).setLayout( {
  28439. name: 'agxToneMapping',
  28440. type: 'vec3',
  28441. inputs: [
  28442. { name: 'color', type: 'vec3' },
  28443. { name: 'exposure', type: 'float' }
  28444. ]
  28445. } );
  28446. /**
  28447. * Neutral tone mapping.
  28448. *
  28449. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  28450. *
  28451. * @tsl
  28452. * @function
  28453. * @param {Node<vec3>} color - The color that should be tone mapped.
  28454. * @param {Node<float>} exposure - The exposure.
  28455. * @return {Node<vec3>} The tone mapped color.
  28456. */
  28457. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28458. const StartCompression = float( 0.8 - 0.04 );
  28459. const Desaturation = float( 0.15 );
  28460. color = color.mul( exposure );
  28461. const x = min$1( color.r, min$1( color.g, color.b ) );
  28462. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  28463. color.subAssign( offset );
  28464. const peak = max$1( color.r, max$1( color.g, color.b ) );
  28465. If( peak.lessThan( StartCompression ), () => {
  28466. return color;
  28467. } );
  28468. const d = sub( 1, StartCompression );
  28469. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  28470. color.mulAssign( newPeak.div( peak ) );
  28471. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  28472. return mix( color, vec3( newPeak ), g );
  28473. } ).setLayout( {
  28474. name: 'neutralToneMapping',
  28475. type: 'vec3',
  28476. inputs: [
  28477. { name: 'color', type: 'vec3' },
  28478. { name: 'exposure', type: 'float' }
  28479. ]
  28480. } );
  28481. /**
  28482. * This class represents native code sections. It is the base
  28483. * class for modules like {@link FunctionNode} which allows to implement
  28484. * functions with native shader languages.
  28485. *
  28486. * @augments Node
  28487. */
  28488. class CodeNode extends Node {
  28489. static get type() {
  28490. return 'CodeNode';
  28491. }
  28492. /**
  28493. * Constructs a new code node.
  28494. *
  28495. * @param {string} [code=''] - The native code.
  28496. * @param {Array<Node>} [includes=[]] - An array of includes.
  28497. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28498. */
  28499. constructor( code = '', includes = [], language = '' ) {
  28500. super( 'code' );
  28501. /**
  28502. * This flag can be used for type testing.
  28503. *
  28504. * @type {boolean}
  28505. * @readonly
  28506. * @default true
  28507. */
  28508. this.isCodeNode = true;
  28509. /**
  28510. * This flag is used for global cache.
  28511. *
  28512. * @type {boolean}
  28513. * @default true
  28514. */
  28515. this.global = true;
  28516. /**
  28517. * The native code.
  28518. *
  28519. * @type {string}
  28520. * @default ''
  28521. */
  28522. this.code = code;
  28523. /**
  28524. * An array of includes
  28525. *
  28526. * @type {Array<Node>}
  28527. * @default []
  28528. */
  28529. this.includes = includes;
  28530. /**
  28531. * The used language.
  28532. *
  28533. * @type {('js'|'wgsl'|'glsl')}
  28534. * @default ''
  28535. */
  28536. this.language = language;
  28537. }
  28538. /**
  28539. * Sets the includes of this code node.
  28540. *
  28541. * @param {Array<Node>} includes - The includes to set.
  28542. * @return {CodeNode} A reference to this node.
  28543. */
  28544. setIncludes( includes ) {
  28545. this.includes = includes;
  28546. return this;
  28547. }
  28548. /**
  28549. * Returns the includes of this code node.
  28550. *
  28551. * @param {NodeBuilder} builder - The current node builder.
  28552. * @return {Array<Node>} The includes.
  28553. */
  28554. getIncludes( /*builder*/ ) {
  28555. return this.includes;
  28556. }
  28557. generate( builder ) {
  28558. const includes = this.getIncludes( builder );
  28559. for ( const include of includes ) {
  28560. include.build( builder );
  28561. }
  28562. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  28563. nodeCode.code = this.code;
  28564. return nodeCode.code;
  28565. }
  28566. serialize( data ) {
  28567. super.serialize( data );
  28568. data.code = this.code;
  28569. data.language = this.language;
  28570. }
  28571. deserialize( data ) {
  28572. super.deserialize( data );
  28573. this.code = data.code;
  28574. this.language = data.language;
  28575. }
  28576. }
  28577. /**
  28578. * TSL function for creating a code node.
  28579. *
  28580. * @tsl
  28581. * @function
  28582. * @param {string} [code] - The native code.
  28583. * @param {?Array<Node>} [includes=[]] - An array of includes.
  28584. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28585. * @returns {CodeNode}
  28586. */
  28587. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  28588. /**
  28589. * TSL function for creating a JS code node.
  28590. *
  28591. * @tsl
  28592. * @function
  28593. * @param {string} src - The native code.
  28594. * @param {Array<Node>} includes - An array of includes.
  28595. * @returns {CodeNode}
  28596. */
  28597. const js = ( src, includes ) => code( src, includes, 'js' );
  28598. /**
  28599. * TSL function for creating a WGSL code node.
  28600. *
  28601. * @tsl
  28602. * @function
  28603. * @param {string} src - The native code.
  28604. * @param {Array<Node>} includes - An array of includes.
  28605. * @returns {CodeNode}
  28606. */
  28607. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  28608. /**
  28609. * TSL function for creating a GLSL code node.
  28610. *
  28611. * @tsl
  28612. * @function
  28613. * @param {string} src - The native code.
  28614. * @param {Array<Node>} includes - An array of includes.
  28615. * @returns {CodeNode}
  28616. */
  28617. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  28618. /**
  28619. * This class represents a native shader function. It can be used to implement
  28620. * certain aspects of a node material with native shader code. There are two predefined
  28621. * TSL functions for easier usage.
  28622. *
  28623. * - `wgslFn`: Creates a WGSL function node.
  28624. * - `glslFn`: Creates a GLSL function node.
  28625. *
  28626. * A basic example with one include looks like so:
  28627. *
  28628. * ```js
  28629. * const desaturateWGSLFn = wgslFn( `
  28630. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  28631. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  28632. * return vec3<f32>( dot( lum, color ) );
  28633. * }`
  28634. *);
  28635. * const someWGSLFn = wgslFn( `
  28636. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  28637. * return desaturate( color );
  28638. * }
  28639. * `, [ desaturateWGSLFn ] );
  28640. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  28641. *```
  28642. * @augments CodeNode
  28643. */
  28644. class FunctionNode extends CodeNode {
  28645. static get type() {
  28646. return 'FunctionNode';
  28647. }
  28648. /**
  28649. * Constructs a new function node.
  28650. *
  28651. * @param {string} [code=''] - The native code.
  28652. * @param {Array<Node>} [includes=[]] - An array of includes.
  28653. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28654. */
  28655. constructor( code = '', includes = [], language = '' ) {
  28656. super( code, includes, language );
  28657. }
  28658. /**
  28659. * Returns the type of this function node.
  28660. *
  28661. * @param {NodeBuilder} builder - The current node builder.
  28662. * @return {string} The type.
  28663. */
  28664. getNodeType( builder ) {
  28665. return this.getNodeFunction( builder ).type;
  28666. }
  28667. /**
  28668. * Returns the type of a member of this function node.
  28669. *
  28670. * @param {NodeBuilder} builder - The current node builder.
  28671. * @param {string} name - The name of the member.
  28672. * @return {string} The type of the member.
  28673. */
  28674. getMemberType( builder, name ) {
  28675. const type = this.getNodeType( builder );
  28676. const structType = builder.getStructTypeNode( type );
  28677. return structType.getMemberType( builder, name );
  28678. }
  28679. /**
  28680. * Returns the inputs of this function node.
  28681. *
  28682. * @param {NodeBuilder} builder - The current node builder.
  28683. * @return {Array<NodeFunctionInput>} The inputs.
  28684. */
  28685. getInputs( builder ) {
  28686. return this.getNodeFunction( builder ).inputs;
  28687. }
  28688. /**
  28689. * Returns the node function for this function node.
  28690. *
  28691. * @param {NodeBuilder} builder - The current node builder.
  28692. * @return {NodeFunction} The node function.
  28693. */
  28694. getNodeFunction( builder ) {
  28695. const nodeData = builder.getDataFromNode( this );
  28696. let nodeFunction = nodeData.nodeFunction;
  28697. if ( nodeFunction === undefined ) {
  28698. nodeFunction = builder.parser.parseFunction( this.code );
  28699. nodeData.nodeFunction = nodeFunction;
  28700. }
  28701. return nodeFunction;
  28702. }
  28703. generate( builder, output ) {
  28704. super.generate( builder );
  28705. const nodeFunction = this.getNodeFunction( builder );
  28706. const name = nodeFunction.name;
  28707. const type = nodeFunction.type;
  28708. const nodeCode = builder.getCodeFromNode( this, type );
  28709. if ( name !== '' ) {
  28710. // use a custom property name
  28711. nodeCode.name = name;
  28712. }
  28713. const propertyName = builder.getPropertyName( nodeCode );
  28714. const code = this.getNodeFunction( builder ).getCode( propertyName );
  28715. nodeCode.code = code + '\n';
  28716. if ( output === 'property' ) {
  28717. return propertyName;
  28718. } else {
  28719. return builder.format( `${ propertyName }()`, type, output );
  28720. }
  28721. }
  28722. }
  28723. const nativeFn = ( code, includes = [], language = '' ) => {
  28724. for ( let i = 0; i < includes.length; i ++ ) {
  28725. const include = includes[ i ];
  28726. // TSL Function: glslFn, wgslFn
  28727. if ( typeof include === 'function' ) {
  28728. includes[ i ] = include.functionNode;
  28729. }
  28730. }
  28731. const functionNode = new FunctionNode( code, includes, language );
  28732. const fn = ( ...params ) => functionNode.call( ...params );
  28733. fn.functionNode = functionNode;
  28734. return fn;
  28735. };
  28736. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  28737. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  28738. /**
  28739. * Returns a node that represents the `z` coordinate in view space
  28740. * for the current fragment. It's a different representation of the
  28741. * default depth value.
  28742. *
  28743. * This value can be part of a computation that defines how the fog
  28744. * density increases when moving away from the camera.
  28745. *
  28746. * @param {NodeBuilder} builder - The current node builder.
  28747. * @return {Node} The viewZ node.
  28748. */
  28749. function getViewZNode( builder ) {
  28750. let viewZ;
  28751. const getViewZ = builder.context.getViewZ;
  28752. if ( getViewZ !== undefined ) {
  28753. viewZ = getViewZ( this );
  28754. }
  28755. return ( viewZ || positionView.z ).negate();
  28756. }
  28757. /**
  28758. * Constructs a new range factor node.
  28759. *
  28760. * @tsl
  28761. * @function
  28762. * @param {Node} near - Defines the near value.
  28763. * @param {Node} far - Defines the far value.
  28764. */
  28765. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  28766. const viewZ = getViewZNode( builder );
  28767. return smoothstep( near, far, viewZ );
  28768. } );
  28769. /**
  28770. * Represents an exponential squared fog. This type of fog gives
  28771. * a clear view near the camera and a faster than exponentially
  28772. * densening fog farther from the camera.
  28773. *
  28774. * @tsl
  28775. * @function
  28776. * @param {Node} density - Defines the fog density.
  28777. */
  28778. const densityFogFactor = Fn( ( [ density ], builder ) => {
  28779. const viewZ = getViewZNode( builder );
  28780. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  28781. } );
  28782. /**
  28783. * Constructs a new height fog factor node. This fog factor requires a Y-up coordinate system.
  28784. *
  28785. * @tsl
  28786. * @function
  28787. * @param {Node} density - Defines the fog density.
  28788. * @param {Node} height - The height threshold in world space. Everything below this y-coordinate is affected by fog.
  28789. */
  28790. const exponentialHeightFogFactor = Fn( ( [ density, height ], builder ) => {
  28791. const viewZ = getViewZNode( builder );
  28792. const distance = height.sub( positionWorld.y ).max( 0 ).toConst();
  28793. const m = distance.mul( viewZ ).toConst();
  28794. return density.mul( density, m, m ).negate().exp().oneMinus();
  28795. } );
  28796. /**
  28797. * This class can be used to configure a fog for the scene.
  28798. * Nodes of this type are assigned to `Scene.fogNode`.
  28799. *
  28800. * @tsl
  28801. * @function
  28802. * @param {Node} color - Defines the color of the fog.
  28803. * @param {Node} factor - Defines how the fog is factored in the scene.
  28804. */
  28805. const fog = Fn( ( [ color, factor ] ) => {
  28806. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  28807. } );
  28808. let min = null;
  28809. let max = null;
  28810. /**
  28811. * `RangeNode` generates random instanced attribute data in a defined range.
  28812. * An exemplary use case for this utility node is to generate random per-instance
  28813. * colors:
  28814. * ```js
  28815. * const material = new MeshBasicNodeMaterial();
  28816. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  28817. * const mesh = new InstancedMesh( geometry, material, count );
  28818. * ```
  28819. * @augments Node
  28820. */
  28821. class RangeNode extends Node {
  28822. static get type() {
  28823. return 'RangeNode';
  28824. }
  28825. /**
  28826. * Constructs a new range node.
  28827. *
  28828. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  28829. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  28830. */
  28831. constructor( minNode = float(), maxNode = float() ) {
  28832. super();
  28833. /**
  28834. * A node defining the lower bound of the range.
  28835. *
  28836. * @type {Node<any>}
  28837. * @default float()
  28838. */
  28839. this.minNode = minNode;
  28840. /**
  28841. * A node defining the upper bound of the range.
  28842. *
  28843. * @type {Node<any>}
  28844. * @default float()
  28845. */
  28846. this.maxNode = maxNode;
  28847. }
  28848. /**
  28849. * Returns the vector length which is computed based on the range definition.
  28850. *
  28851. * @param {NodeBuilder} builder - The current node builder.
  28852. * @return {number} The vector length.
  28853. */
  28854. getVectorLength( builder ) {
  28855. const minNode = this.getConstNode( this.minNode );
  28856. const maxNode = this.getConstNode( this.maxNode );
  28857. const minLength = builder.getTypeLength( getValueType( minNode.value ) );
  28858. const maxLength = builder.getTypeLength( getValueType( maxNode.value ) );
  28859. return minLength > maxLength ? minLength : maxLength;
  28860. }
  28861. /**
  28862. * This method is overwritten since the node type is inferred from range definition.
  28863. *
  28864. * @param {NodeBuilder} builder - The current node builder.
  28865. * @return {string} The node type.
  28866. */
  28867. getNodeType( builder ) {
  28868. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  28869. }
  28870. /**
  28871. * Returns a constant node from the given node by traversing it.
  28872. *
  28873. * @param {Node} node - The node to traverse.
  28874. * @returns {Node} The constant node, if found.
  28875. */
  28876. getConstNode( node ) {
  28877. let output = null;
  28878. node.traverse( n => {
  28879. if ( n.isConstNode === true ) {
  28880. output = n;
  28881. }
  28882. } );
  28883. if ( output === null ) {
  28884. throw new NodeError( 'THREE.TSL: No "ConstNode" found in node graph.', this.stackTrace );
  28885. }
  28886. return output;
  28887. }
  28888. setup( builder ) {
  28889. const object = builder.object;
  28890. let output = null;
  28891. if ( object.count > 1 ) {
  28892. const minNode = this.getConstNode( this.minNode );
  28893. const maxNode = this.getConstNode( this.maxNode );
  28894. const minValue = minNode.value;
  28895. const maxValue = maxNode.value;
  28896. const minLength = builder.getTypeLength( getValueType( minValue ) );
  28897. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  28898. min = min || new Vector4();
  28899. max = max || new Vector4();
  28900. min.setScalar( 0 );
  28901. max.setScalar( 0 );
  28902. if ( minLength === 1 ) min.setScalar( minValue );
  28903. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  28904. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  28905. if ( maxLength === 1 ) max.setScalar( maxValue );
  28906. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  28907. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  28908. const stride = 4;
  28909. const length = stride * object.count;
  28910. const array = new Float32Array( length );
  28911. for ( let i = 0; i < length; i ++ ) {
  28912. const index = i % stride;
  28913. const minElementValue = min.getComponent( index );
  28914. const maxElementValue = max.getComponent( index );
  28915. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  28916. }
  28917. const nodeType = this.getNodeType( builder );
  28918. const uniformBufferSize = object.count * 4 * 4; // count * 4 components * 4 bytes (float)
  28919. if ( uniformBufferSize <= builder.getUniformBufferLimit() ) {
  28920. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  28921. } else {
  28922. // TODO: Improve anonymous buffer attribute creation removing this part
  28923. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  28924. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  28925. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  28926. }
  28927. } else {
  28928. output = float( 0 );
  28929. }
  28930. return output;
  28931. }
  28932. }
  28933. /**
  28934. * TSL function for creating a range node.
  28935. *
  28936. * @tsl
  28937. * @function
  28938. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  28939. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  28940. * @returns {RangeNode}
  28941. */
  28942. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  28943. /**
  28944. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  28945. * about the currently running dispatch and/or the device it is running on.
  28946. *
  28947. * This node can only be used with a WebGPU backend.
  28948. *
  28949. * @augments Node
  28950. */
  28951. class ComputeBuiltinNode extends Node {
  28952. static get type() {
  28953. return 'ComputeBuiltinNode';
  28954. }
  28955. /**
  28956. * Constructs a new compute builtin node.
  28957. *
  28958. * @param {string} builtinName - The built-in name.
  28959. * @param {string} nodeType - The node type.
  28960. */
  28961. constructor( builtinName, nodeType ) {
  28962. super( nodeType );
  28963. /**
  28964. * The built-in name.
  28965. *
  28966. * @private
  28967. * @type {string}
  28968. */
  28969. this._builtinName = builtinName;
  28970. }
  28971. /**
  28972. * This method is overwritten since hash is derived from the built-in name.
  28973. *
  28974. * @param {NodeBuilder} builder - The current node builder.
  28975. * @return {string} The hash.
  28976. */
  28977. getHash( builder ) {
  28978. return this.getBuiltinName( builder );
  28979. }
  28980. /**
  28981. * This method is overwritten since the node type is simply derived from `nodeType`..
  28982. *
  28983. * @param {NodeBuilder} builder - The current node builder.
  28984. * @return {string} The node type.
  28985. */
  28986. getNodeType( /*builder*/ ) {
  28987. return this.nodeType;
  28988. }
  28989. /**
  28990. * Sets the builtin name.
  28991. *
  28992. * @param {string} builtinName - The built-in name.
  28993. * @return {ComputeBuiltinNode} A reference to this node.
  28994. */
  28995. setBuiltinName( builtinName ) {
  28996. this._builtinName = builtinName;
  28997. return this;
  28998. }
  28999. /**
  29000. * Returns the builtin name.
  29001. *
  29002. * @param {NodeBuilder} builder - The current node builder.
  29003. * @return {string} The builtin name.
  29004. */
  29005. getBuiltinName( /*builder*/ ) {
  29006. return this._builtinName;
  29007. }
  29008. /**
  29009. * Whether the current node builder has the builtin or not.
  29010. *
  29011. * @param {NodeBuilder} builder - The current node builder.
  29012. * @return {boolean} Whether the builder has the builtin or not.
  29013. */
  29014. hasBuiltin( builder ) {
  29015. return builder.hasBuiltin( this._builtinName );
  29016. }
  29017. generate( builder, output ) {
  29018. const builtinName = this.getBuiltinName( builder );
  29019. const nodeType = this.getNodeType( builder );
  29020. if ( builder.shaderStage === 'compute' ) {
  29021. return builder.format( builtinName, nodeType, output );
  29022. } else {
  29023. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  29024. return builder.generateConst( nodeType );
  29025. }
  29026. }
  29027. serialize( data ) {
  29028. super.serialize( data );
  29029. data.global = this.global;
  29030. data._builtinName = this._builtinName;
  29031. }
  29032. deserialize( data ) {
  29033. super.deserialize( data );
  29034. this.global = data.global;
  29035. this._builtinName = data._builtinName;
  29036. }
  29037. }
  29038. /**
  29039. * TSL function for creating a compute builtin node.
  29040. *
  29041. * @tsl
  29042. * @function
  29043. * @param {string} name - The built-in name.
  29044. * @param {string} nodeType - The node type.
  29045. * @returns {ComputeBuiltinNode}
  29046. */
  29047. const computeBuiltin = ( name, nodeType ) => new ComputeBuiltinNode( name, nodeType );
  29048. /**
  29049. * Represents the number of workgroups dispatched by the compute shader.
  29050. * ```js
  29051. * // Run 512 invocations/threads with a workgroup size of 128.
  29052. * const computeFn = Fn(() => {
  29053. *
  29054. * // numWorkgroups.x = 4
  29055. * storageBuffer.element(0).assign(numWorkgroups.x)
  29056. *
  29057. * })().compute(512, [128]);
  29058. *
  29059. * // Run 512 invocations/threads with the default workgroup size of 64.
  29060. * const computeFn = Fn(() => {
  29061. *
  29062. * // numWorkgroups.x = 8
  29063. * storageBuffer.element(0).assign(numWorkgroups.x)
  29064. *
  29065. * })().compute(512);
  29066. * ```
  29067. *
  29068. * @tsl
  29069. * @type {ComputeBuiltinNode<uvec3>}
  29070. */
  29071. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  29072. /**
  29073. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  29074. * ```js
  29075. * // Execute 12 compute threads with a workgroup size of 3.
  29076. * const computeFn = Fn( () => {
  29077. *
  29078. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  29079. *
  29080. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  29081. *
  29082. * } ).Else( () => {
  29083. *
  29084. * storageBuffer.element( instanceIndex ).assign( 0 );
  29085. *
  29086. * } );
  29087. *
  29088. * } )().compute( 12, [ 3 ] );
  29089. *
  29090. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  29091. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  29092. * ```
  29093. *
  29094. * @tsl
  29095. * @type {ComputeBuiltinNode<uvec3>}
  29096. */
  29097. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  29098. /**
  29099. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  29100. *
  29101. * @tsl
  29102. * @type {ComputeBuiltinNode<uvec3>}
  29103. */
  29104. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  29105. /**
  29106. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  29107. *
  29108. * @tsl
  29109. * @type {ComputeBuiltinNode<uvec3>}
  29110. */
  29111. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  29112. /**
  29113. * A device dependent variable that exposes the size of the current invocation's subgroup.
  29114. *
  29115. * @tsl
  29116. * @type {ComputeBuiltinNode<uint>}
  29117. */
  29118. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  29119. /**
  29120. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  29121. *
  29122. * This node can only be used with a WebGPU backend.
  29123. *
  29124. * @augments Node
  29125. */
  29126. class BarrierNode extends Node {
  29127. /**
  29128. * Constructs a new barrier node.
  29129. *
  29130. * @param {string} scope - The scope defines the behavior of the node.
  29131. */
  29132. constructor( scope ) {
  29133. super();
  29134. this.scope = scope;
  29135. }
  29136. generate( builder ) {
  29137. const { scope } = this;
  29138. const { renderer } = builder;
  29139. if ( renderer.backend.isWebGLBackend === true ) {
  29140. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  29141. } else {
  29142. builder.addLineFlowCode( `${scope}Barrier()`, this );
  29143. }
  29144. }
  29145. }
  29146. /**
  29147. * TSL function for creating a barrier node.
  29148. *
  29149. * @tsl
  29150. * @function
  29151. * @param {string} scope - The scope defines the behavior of the node..
  29152. * @returns {BarrierNode}
  29153. */
  29154. const barrier = nodeProxy( BarrierNode );
  29155. /**
  29156. * TSL function for creating a workgroup barrier. All compute shader
  29157. * invocations must wait for each invocation within a workgroup to
  29158. * complete before the barrier can be surpassed.
  29159. *
  29160. * @tsl
  29161. * @function
  29162. * @returns {BarrierNode}
  29163. */
  29164. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  29165. /**
  29166. * TSL function for creating a storage barrier. All invocations must
  29167. * wait for each access to variables within the 'storage' address space
  29168. * to complete before the barrier can be passed.
  29169. *
  29170. * @tsl
  29171. * @function
  29172. * @returns {BarrierNode}
  29173. */
  29174. const storageBarrier = () => barrier( 'storage' ).toStack();
  29175. /**
  29176. * TSL function for creating a texture barrier. All invocations must
  29177. * wait for each access to variables within the 'texture' address space
  29178. * to complete before the barrier can be passed.
  29179. *
  29180. * @tsl
  29181. * @function
  29182. * @returns {BarrierNode}
  29183. */
  29184. const textureBarrier = () => barrier( 'texture' ).toStack();
  29185. /**
  29186. * Represents an element of a 'workgroup' scoped buffer.
  29187. *
  29188. * @augments ArrayElementNode
  29189. */
  29190. class WorkgroupInfoElementNode extends ArrayElementNode {
  29191. /**
  29192. * Constructs a new workgroup info element node.
  29193. *
  29194. * @param {Node} workgroupInfoNode - The workgroup info node.
  29195. * @param {Node} indexNode - The index node that defines the element access.
  29196. */
  29197. constructor( workgroupInfoNode, indexNode ) {
  29198. super( workgroupInfoNode, indexNode );
  29199. /**
  29200. * This flag can be used for type testing.
  29201. *
  29202. * @type {boolean}
  29203. * @readonly
  29204. * @default true
  29205. */
  29206. this.isWorkgroupInfoElementNode = true;
  29207. }
  29208. generate( builder, output ) {
  29209. let snippet;
  29210. const isAssignContext = builder.context.assign;
  29211. snippet = super.generate( builder );
  29212. if ( isAssignContext !== true ) {
  29213. const type = this.getNodeType( builder );
  29214. snippet = builder.format( snippet, type, output );
  29215. }
  29216. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  29217. return snippet;
  29218. }
  29219. }
  29220. /**
  29221. * A node allowing the user to create a 'workgroup' scoped buffer within the
  29222. * context of a compute shader. Typically, workgroup scoped buffers are
  29223. * created to hold data that is transferred from a global storage scope into
  29224. * a local workgroup scope. For invocations within a workgroup, data
  29225. * access speeds on 'workgroup' scoped buffers can be significantly faster
  29226. * than similar access operations on globally accessible storage buffers.
  29227. *
  29228. * This node can only be used with a WebGPU backend.
  29229. *
  29230. * @augments Node
  29231. */
  29232. class WorkgroupInfoNode extends Node {
  29233. /**
  29234. * Constructs a new buffer scoped to type scope.
  29235. *
  29236. * @param {string} scope - TODO.
  29237. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  29238. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  29239. */
  29240. constructor( scope, bufferType, bufferCount = 0 ) {
  29241. super( bufferType );
  29242. /**
  29243. * The buffer type.
  29244. *
  29245. * @type {string}
  29246. */
  29247. this.bufferType = bufferType;
  29248. /**
  29249. * The buffer count.
  29250. *
  29251. * @type {number}
  29252. * @default 0
  29253. */
  29254. this.bufferCount = bufferCount;
  29255. /**
  29256. * This flag can be used for type testing.
  29257. *
  29258. * @type {boolean}
  29259. * @readonly
  29260. * @default true
  29261. */
  29262. this.isWorkgroupInfoNode = true;
  29263. /**
  29264. * The data type of the array buffer.
  29265. *
  29266. * @type {string}
  29267. */
  29268. this.elementType = bufferType;
  29269. /**
  29270. * TODO.
  29271. *
  29272. * @type {string}
  29273. */
  29274. this.scope = scope;
  29275. /**
  29276. * The name of the workgroup scoped buffer.
  29277. *
  29278. * @type {string}
  29279. * @default ''
  29280. */
  29281. this.name = '';
  29282. }
  29283. /**
  29284. * Sets the name of this node.
  29285. *
  29286. * @param {string} name - The name to set.
  29287. * @return {WorkgroupInfoNode} A reference to this node.
  29288. */
  29289. setName( name ) {
  29290. this.name = name;
  29291. return this;
  29292. }
  29293. /**
  29294. * Sets the name/label of this node.
  29295. *
  29296. * @deprecated
  29297. * @param {string} name - The name to set.
  29298. * @return {WorkgroupInfoNode} A reference to this node.
  29299. */
  29300. label( name ) {
  29301. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.', new StackTrace() ); // @deprecated r179
  29302. return this.setName( name );
  29303. }
  29304. /**
  29305. * Sets the scope of this node.
  29306. *
  29307. * @param {string} scope - The scope to set.
  29308. * @return {WorkgroupInfoNode} A reference to this node.
  29309. */
  29310. setScope( scope ) {
  29311. this.scope = scope;
  29312. return this;
  29313. }
  29314. /**
  29315. * The data type of the array buffer.
  29316. *
  29317. * @return {string} The element type.
  29318. */
  29319. getElementType() {
  29320. return this.elementType;
  29321. }
  29322. /**
  29323. * Overwrites the default implementation since the input type
  29324. * is inferred from the scope.
  29325. *
  29326. * @param {NodeBuilder} builder - The current node builder.
  29327. * @return {string} The input type.
  29328. */
  29329. getInputType( /*builder*/ ) {
  29330. return `${this.scope}Array`;
  29331. }
  29332. /**
  29333. * This method can be used to access elements via an index node.
  29334. *
  29335. * @param {IndexNode} indexNode - indexNode.
  29336. * @return {WorkgroupInfoElementNode} A reference to an element.
  29337. */
  29338. element( indexNode ) {
  29339. return new WorkgroupInfoElementNode( this, indexNode );
  29340. }
  29341. generate( builder ) {
  29342. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  29343. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  29344. }
  29345. }
  29346. /**
  29347. * TSL function for creating a workgroup info node.
  29348. * Creates a new 'workgroup' scoped array buffer.
  29349. *
  29350. * @tsl
  29351. * @function
  29352. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  29353. * @param {number} [count=0] - The number of elements in the buffer.
  29354. * @returns {WorkgroupInfoNode}
  29355. */
  29356. const workgroupArray = ( type, count ) => new WorkgroupInfoNode( 'Workgroup', type, count );
  29357. /**
  29358. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  29359. * within a shader. In an atomic function, any modification to an atomic variable will
  29360. * occur as an indivisible step with a defined order relative to other modifications.
  29361. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  29362. * atomic operations will not interfere with each other.
  29363. *
  29364. * This node can only be used with a WebGPU backend.
  29365. *
  29366. * @augments Node
  29367. */
  29368. class AtomicFunctionNode extends Node {
  29369. static get type() {
  29370. return 'AtomicFunctionNode';
  29371. }
  29372. /**
  29373. * Constructs a new atomic function node.
  29374. *
  29375. * @param {string} method - The signature of the atomic function to construct.
  29376. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29377. * @param {Node} valueNode - The value that mutates the atomic variable.
  29378. */
  29379. constructor( method, pointerNode, valueNode ) {
  29380. super( 'uint' );
  29381. /**
  29382. * The signature of the atomic function to construct.
  29383. *
  29384. * @type {string}
  29385. */
  29386. this.method = method;
  29387. /**
  29388. * An atomic variable or element of an atomic buffer.
  29389. *
  29390. * @type {Node}
  29391. */
  29392. this.pointerNode = pointerNode;
  29393. /**
  29394. * A value that modifies the atomic variable.
  29395. *
  29396. * @type {Node}
  29397. */
  29398. this.valueNode = valueNode;
  29399. /**
  29400. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  29401. *
  29402. * @type {boolean}
  29403. * @default true
  29404. */
  29405. this.parents = true;
  29406. }
  29407. /**
  29408. * Overwrites the default implementation to return the type of
  29409. * the pointer node.
  29410. *
  29411. * @param {NodeBuilder} builder - The current node builder.
  29412. * @return {string} The input type.
  29413. */
  29414. getInputType( builder ) {
  29415. return this.pointerNode.getNodeType( builder );
  29416. }
  29417. /**
  29418. * Overwritten since the node type is inferred from the input type.
  29419. *
  29420. * @param {NodeBuilder} builder - The current node builder.
  29421. * @return {string} The node type.
  29422. */
  29423. getNodeType( builder ) {
  29424. return this.getInputType( builder );
  29425. }
  29426. generate( builder ) {
  29427. const properties = builder.getNodeProperties( this );
  29428. const parents = properties.parents;
  29429. const method = this.method;
  29430. const type = this.getNodeType( builder );
  29431. const inputType = this.getInputType( builder );
  29432. const a = this.pointerNode;
  29433. const b = this.valueNode;
  29434. const params = [];
  29435. params.push( `&${ a.build( builder, inputType ) }` );
  29436. if ( b !== null ) {
  29437. params.push( b.build( builder, inputType ) );
  29438. }
  29439. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  29440. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  29441. if ( isVoid ) {
  29442. builder.addLineFlowCode( methodSnippet, this );
  29443. } else {
  29444. if ( properties.constNode === undefined ) {
  29445. properties.constNode = expression( methodSnippet, type ).toConst();
  29446. }
  29447. return properties.constNode.build( builder );
  29448. }
  29449. }
  29450. }
  29451. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  29452. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  29453. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  29454. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  29455. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  29456. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  29457. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  29458. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  29459. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  29460. /**
  29461. * TSL function for creating an atomic function node.
  29462. *
  29463. * @tsl
  29464. * @function
  29465. * @param {string} method - The signature of the atomic function to construct.
  29466. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29467. * @param {Node} valueNode - The value that mutates the atomic variable.
  29468. * @returns {AtomicFunctionNode}
  29469. */
  29470. const atomicNode = nodeProxy( AtomicFunctionNode );
  29471. /**
  29472. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  29473. *
  29474. * @tsl
  29475. * @function
  29476. * @param {string} method - The signature of the atomic function to construct.
  29477. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29478. * @param {Node} valueNode - The value that mutates the atomic variable.
  29479. * @returns {AtomicFunctionNode}
  29480. */
  29481. const atomicFunc = ( method, pointerNode, valueNode ) => {
  29482. return atomicNode( method, pointerNode, valueNode ).toStack();
  29483. };
  29484. /**
  29485. * Loads the value stored in the atomic variable.
  29486. *
  29487. * @tsl
  29488. * @function
  29489. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29490. * @returns {AtomicFunctionNode}
  29491. */
  29492. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  29493. /**
  29494. * Stores a value in the atomic variable.
  29495. *
  29496. * @tsl
  29497. * @function
  29498. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29499. * @param {Node} valueNode - The value that mutates the atomic variable.
  29500. * @returns {AtomicFunctionNode}
  29501. */
  29502. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  29503. /**
  29504. * Increments the value stored in the atomic variable.
  29505. *
  29506. * @tsl
  29507. * @function
  29508. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29509. * @param {Node} valueNode - The value that mutates the atomic variable.
  29510. * @returns {AtomicFunctionNode}
  29511. */
  29512. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  29513. /**
  29514. * Decrements the value stored in the atomic variable.
  29515. *
  29516. * @tsl
  29517. * @function
  29518. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29519. * @param {Node} valueNode - The value that mutates the atomic variable.
  29520. * @returns {AtomicFunctionNode}
  29521. */
  29522. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  29523. /**
  29524. * Stores in an atomic variable the maximum between its current value and a parameter.
  29525. *
  29526. * @tsl
  29527. * @function
  29528. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29529. * @param {Node} valueNode - The value that mutates the atomic variable.
  29530. * @returns {AtomicFunctionNode}
  29531. */
  29532. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  29533. /**
  29534. * Stores in an atomic variable the minimum between its current value and a parameter.
  29535. *
  29536. * @tsl
  29537. * @function
  29538. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29539. * @param {Node} valueNode - The value that mutates the atomic variable.
  29540. * @returns {AtomicFunctionNode}
  29541. */
  29542. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  29543. /**
  29544. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  29545. *
  29546. * @tsl
  29547. * @function
  29548. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29549. * @param {Node} valueNode - The value that mutates the atomic variable.
  29550. * @returns {AtomicFunctionNode}
  29551. */
  29552. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  29553. /**
  29554. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  29555. *
  29556. * @tsl
  29557. * @function
  29558. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29559. * @param {Node} valueNode - The value that mutates the atomic variable.
  29560. * @returns {AtomicFunctionNode}
  29561. */
  29562. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  29563. /**
  29564. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  29565. *
  29566. * @tsl
  29567. * @function
  29568. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29569. * @param {Node} valueNode - The value that mutates the atomic variable.
  29570. * @returns {AtomicFunctionNode}
  29571. */
  29572. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  29573. /**
  29574. * This class represents a set of built in WGSL shader functions that sync
  29575. * synchronously execute an operation across a subgroup, or 'warp', of compute
  29576. * or fragment shader invocations within a workgroup. Typically, these functions
  29577. * will synchronously execute an operation using data from all active invocations
  29578. * within the subgroup, then broadcast that result to all active invocations. In
  29579. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  29580. * (DirectX/HLSL) or warp intrinsics (CUDA).
  29581. *
  29582. * @augments TempNode
  29583. */
  29584. class SubgroupFunctionNode extends TempNode {
  29585. static get type() {
  29586. return 'SubgroupFunctionNode';
  29587. }
  29588. /**
  29589. * Constructs a new function node.
  29590. *
  29591. * @param {string} method - The subgroup/wave intrinsic method to construct.
  29592. * @param {Node} [aNode=null] - The method's first argument.
  29593. * @param {Node} [bNode=null] - The method's second argument.
  29594. */
  29595. constructor( method, aNode = null, bNode = null ) {
  29596. super();
  29597. /**
  29598. * The subgroup/wave intrinsic method to construct.
  29599. *
  29600. * @type {string}
  29601. */
  29602. this.method = method;
  29603. /**
  29604. * The method's first argument.
  29605. *
  29606. * @type {Node}
  29607. */
  29608. this.aNode = aNode;
  29609. /**
  29610. * The method's second argument.
  29611. *
  29612. * @type {Node}
  29613. */
  29614. this.bNode = bNode;
  29615. }
  29616. getInputType( builder ) {
  29617. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  29618. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  29619. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  29620. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  29621. if ( aLen > bLen ) {
  29622. return aType;
  29623. } else {
  29624. return bType;
  29625. }
  29626. }
  29627. getNodeType( builder ) {
  29628. const method = this.method;
  29629. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  29630. return 'bool';
  29631. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  29632. return 'uvec4';
  29633. } else {
  29634. return this.getInputType( builder );
  29635. }
  29636. }
  29637. generate( builder, output ) {
  29638. const method = this.method;
  29639. const type = this.getNodeType( builder );
  29640. const inputType = this.getInputType( builder );
  29641. const a = this.aNode;
  29642. const b = this.bNode;
  29643. const params = [];
  29644. if (
  29645. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  29646. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  29647. method === SubgroupFunctionNode.QUAD_BROADCAST
  29648. ) {
  29649. const bType = b.getNodeType( builder );
  29650. params.push(
  29651. a.build( builder, type ),
  29652. b.build( builder, bType === 'float' ? 'int' : type )
  29653. );
  29654. } else if (
  29655. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  29656. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  29657. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  29658. ) {
  29659. params.push(
  29660. a.build( builder, type ),
  29661. b.build( builder, 'uint' )
  29662. );
  29663. } else {
  29664. if ( a !== null ) params.push( a.build( builder, inputType ) );
  29665. if ( b !== null ) params.push( b.build( builder, inputType ) );
  29666. }
  29667. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  29668. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  29669. }
  29670. serialize( data ) {
  29671. super.serialize( data );
  29672. data.method = this.method;
  29673. }
  29674. deserialize( data ) {
  29675. super.deserialize( data );
  29676. this.method = data.method;
  29677. }
  29678. }
  29679. // 0 inputs
  29680. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  29681. // 1 input
  29682. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  29683. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  29684. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  29685. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  29686. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  29687. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  29688. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  29689. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  29690. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  29691. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  29692. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  29693. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  29694. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  29695. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  29696. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  29697. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  29698. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  29699. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  29700. // 2 inputs
  29701. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  29702. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  29703. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  29704. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  29705. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  29706. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  29707. /**
  29708. * Returns true if this invocation has the lowest subgroup_invocation_id
  29709. * among active invocations in the subgroup.
  29710. *
  29711. * @tsl
  29712. * @method
  29713. * @return {bool} The result of the computation.
  29714. */
  29715. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  29716. /**
  29717. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  29718. * is 1 if pred is true for that active invocation and 0 otherwise.
  29719. *
  29720. * @tsl
  29721. * @method
  29722. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  29723. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  29724. */
  29725. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  29726. /**
  29727. * A reduction that adds e among all active invocations and returns that result.
  29728. *
  29729. * @tsl
  29730. * @method
  29731. * @param {number} e - The value provided to the reduction by the current invocation.
  29732. * @return {number} The accumulated result of the reduction operation.
  29733. */
  29734. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  29735. /**
  29736. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  29737. *
  29738. * @tsl
  29739. * @method
  29740. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  29741. * @return {number} The accumulated result of the inclusive scan operation.
  29742. */
  29743. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  29744. /**
  29745. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  29746. *
  29747. * @tsl
  29748. * @method
  29749. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  29750. * @return {number} The accumulated result of the exclusive scan operation.
  29751. */
  29752. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  29753. /**
  29754. * A reduction that multiplies e among all active invocations and returns that result.
  29755. *
  29756. * @tsl
  29757. * @method
  29758. * @param {number} e - The value provided to the reduction by the current invocation.
  29759. * @return {number} The accumulated result of the reduction operation.
  29760. */
  29761. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  29762. /**
  29763. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  29764. *
  29765. * @tsl
  29766. * @method
  29767. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  29768. * @return {number} The accumulated result of the inclusive scan operation.
  29769. */
  29770. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  29771. /**
  29772. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  29773. *
  29774. * @tsl
  29775. * @method
  29776. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  29777. * @return {number} The accumulated result of the exclusive scan operation.
  29778. */
  29779. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  29780. /**
  29781. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  29782. *
  29783. * @tsl
  29784. * @method
  29785. * @param {number} e - The value provided to the reduction by the current invocation.
  29786. * @return {number} The result of the reduction operation.
  29787. */
  29788. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  29789. /**
  29790. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  29791. *
  29792. * @tsl
  29793. * @method
  29794. * @param {number} e - The value provided to the reduction by the current invocation.
  29795. * @return {number} The result of the reduction operation.
  29796. */
  29797. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  29798. /**
  29799. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  29800. *
  29801. * @tsl
  29802. * @method
  29803. * @param {number} e - The value provided to the reduction by the current invocation.
  29804. * @return {number} The result of the reduction operation.
  29805. */
  29806. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  29807. /**
  29808. * A reduction that performs a min of e among all active invocations and returns that result.
  29809. *
  29810. * @tsl
  29811. * @method
  29812. * @param {number} e - The value provided to the reduction by the current invocation.
  29813. * @return {number} The result of the reduction operation.
  29814. */
  29815. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  29816. /**
  29817. * A reduction that performs a max of e among all active invocations and returns that result.
  29818. *
  29819. * @tsl
  29820. * @method
  29821. * @param {number} e - The value provided to the reduction by the current invocation.
  29822. * @return {number} The result of the reduction operation.
  29823. */
  29824. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  29825. /**
  29826. * Returns true if e is true for all active invocations in the subgroup.
  29827. *
  29828. * @tsl
  29829. * @method
  29830. * @return {bool} The result of the computation.
  29831. */
  29832. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  29833. /**
  29834. * Returns true if e is true for any active invocation in the subgroup
  29835. *
  29836. * @tsl
  29837. * @method
  29838. * @return {bool} The result of the computation.
  29839. */
  29840. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  29841. /**
  29842. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  29843. *
  29844. * @tsl
  29845. * @method
  29846. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  29847. * @param {number} id - The subgroup invocation to broadcast from.
  29848. * @return {number} The broadcast value.
  29849. */
  29850. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  29851. /**
  29852. * Swaps e between invocations in the quad in the X direction.
  29853. *
  29854. * @tsl
  29855. * @method
  29856. * @param {number} e - The value to swap from the current invocation.
  29857. * @return {number} The value received from the swap operation.
  29858. */
  29859. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  29860. /**
  29861. * Swaps e between invocations in the quad in the Y direction.
  29862. *
  29863. * @tsl
  29864. * @method
  29865. * @param {number} e - The value to swap from the current invocation.
  29866. * @return {number} The value received from the swap operation.
  29867. */
  29868. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  29869. /**
  29870. * Swaps e between invocations in the quad diagonally.
  29871. *
  29872. * @tsl
  29873. * @method
  29874. * @param {number} e - The value to swap from the current invocation.
  29875. * @return {number} The value received from the swap operation.
  29876. */
  29877. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  29878. /**
  29879. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  29880. *
  29881. * @tsl
  29882. * @method
  29883. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  29884. * @param {number} id - The subgroup invocation to broadcast from.
  29885. * @return {number} The broadcast value.
  29886. */
  29887. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  29888. /**
  29889. * Returns v from the active invocation whose subgroup_invocation_id matches id
  29890. *
  29891. * @tsl
  29892. * @method
  29893. * @param {number} v - The value to return from subgroup invocation id^mask.
  29894. * @param {number} id - The subgroup invocation which returns the value v.
  29895. * @return {number} The broadcast value.
  29896. */
  29897. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  29898. /**
  29899. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  29900. *
  29901. * @tsl
  29902. * @method
  29903. * @param {number} v - The value to return from subgroup invocation id^mask.
  29904. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  29905. * @return {number} The broadcast value.
  29906. */
  29907. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  29908. /**
  29909. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  29910. *
  29911. * @tsl
  29912. * @method
  29913. * @param {number} v - The value to return from subgroup invocation id^mask.
  29914. * @param {number} delta - A value that offsets the current in.
  29915. * @return {number} The broadcast value.
  29916. */
  29917. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  29918. /**
  29919. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  29920. *
  29921. * @tsl
  29922. * @method
  29923. * @param {number} v - The value to return from subgroup invocation id^mask.
  29924. * @param {number} delta - A value that offsets the current subgroup invocation.
  29925. * @return {number} The broadcast value.
  29926. */
  29927. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  29928. /**
  29929. * Broadcasts e from the quad invocation with id equal to id.
  29930. *
  29931. * @tsl
  29932. * @method
  29933. * @param {number} e - The value to broadcast.
  29934. * @return {number} The broadcast value.
  29935. */
  29936. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  29937. let uniformsLib;
  29938. function getLightData( light ) {
  29939. uniformsLib = uniformsLib || new WeakMap();
  29940. let uniforms = uniformsLib.get( light );
  29941. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  29942. return uniforms;
  29943. }
  29944. /**
  29945. * TSL function for getting a shadow matrix uniform node for the given light.
  29946. *
  29947. * @tsl
  29948. * @function
  29949. * @param {Light} light -The light source.
  29950. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  29951. */
  29952. function lightShadowMatrix( light ) {
  29953. const data = getLightData( light );
  29954. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  29955. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  29956. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  29957. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  29958. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  29959. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  29960. light.shadow.camera.updateProjectionMatrix();
  29961. }
  29962. light.shadow.updateMatrices( light );
  29963. }
  29964. return light.shadow.matrix;
  29965. } ) );
  29966. }
  29967. /**
  29968. * TSL function for getting projected uv coordinates for the given light.
  29969. * Relevant when using maps with spot lights.
  29970. *
  29971. * @tsl
  29972. * @function
  29973. * @param {Light} light -The light source.
  29974. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  29975. * @returns {Node<vec3>} The projected uvs.
  29976. */
  29977. function lightProjectionUV( light, position = positionWorld ) {
  29978. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  29979. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  29980. return projectionUV;
  29981. }
  29982. /**
  29983. * TSL function for getting the position in world space for the given light.
  29984. *
  29985. * @tsl
  29986. * @function
  29987. * @param {Light} light -The light source.
  29988. * @returns {UniformNode<vec3>} The light's position in world space.
  29989. */
  29990. function lightPosition( light ) {
  29991. const data = getLightData( light );
  29992. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  29993. }
  29994. /**
  29995. * TSL function for getting the light target position in world space for the given light.
  29996. *
  29997. * @tsl
  29998. * @function
  29999. * @param {Light} light -The light source.
  30000. * @returns {UniformNode<vec3>} The light target position in world space.
  30001. */
  30002. function lightTargetPosition( light ) {
  30003. const data = getLightData( light );
  30004. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  30005. }
  30006. /**
  30007. * TSL function for getting the position in view space for the given light.
  30008. *
  30009. * @tsl
  30010. * @function
  30011. * @param {Light} light - The light source.
  30012. * @returns {UniformNode<vec3>} The light's position in view space.
  30013. */
  30014. function lightViewPosition( light ) {
  30015. const data = getLightData( light );
  30016. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  30017. self.value = self.value || new Vector3();
  30018. self.value.setFromMatrixPosition( light.matrixWorld );
  30019. self.value.applyMatrix4( camera.matrixWorldInverse );
  30020. } ) );
  30021. }
  30022. /**
  30023. * TSL function for getting the light target direction for the given light.
  30024. *
  30025. * @tsl
  30026. * @function
  30027. * @param {Light} light -The light source.
  30028. * @returns {Node<vec3>} The light's target direction.
  30029. */
  30030. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  30031. const sortLights = ( lights ) => {
  30032. return lights.sort( ( a, b ) => a.id - b.id );
  30033. };
  30034. const getLightNodeById = ( id, lightNodes ) => {
  30035. for ( const lightNode of lightNodes ) {
  30036. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  30037. return lightNode;
  30038. }
  30039. }
  30040. return null;
  30041. };
  30042. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  30043. const _hashData = [];
  30044. /**
  30045. * This node represents the scene's lighting and manages the lighting model's life cycle
  30046. * for the current build 3D object. It is responsible for computing the total outgoing
  30047. * light in a given lighting context.
  30048. *
  30049. * @augments Node
  30050. */
  30051. class LightsNode extends Node {
  30052. static get type() {
  30053. return 'LightsNode';
  30054. }
  30055. /**
  30056. * Constructs a new lights node.
  30057. */
  30058. constructor() {
  30059. super( 'vec3' );
  30060. /**
  30061. * A node representing the total diffuse light.
  30062. *
  30063. * @type {Node<vec3>}
  30064. */
  30065. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  30066. /**
  30067. * A node representing the total specular light.
  30068. *
  30069. * @type {Node<vec3>}
  30070. */
  30071. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  30072. /**
  30073. * A node representing the outgoing light.
  30074. *
  30075. * @type {Node<vec3>}
  30076. */
  30077. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  30078. /**
  30079. * An array representing the lights in the scene.
  30080. *
  30081. * @private
  30082. * @type {Array<Light>}
  30083. */
  30084. this._lights = [];
  30085. /**
  30086. * For each light in the scene, this node will create a
  30087. * corresponding light node.
  30088. *
  30089. * @private
  30090. * @type {?Array<LightingNode>}
  30091. * @default null
  30092. */
  30093. this._lightNodes = null;
  30094. /**
  30095. * A hash for identifying the current light nodes setup.
  30096. *
  30097. * @private
  30098. * @type {?string}
  30099. * @default null
  30100. */
  30101. this._lightNodesHash = null;
  30102. /**
  30103. * `LightsNode` sets this property to `true` by default.
  30104. *
  30105. * @type {boolean}
  30106. * @default true
  30107. */
  30108. this.global = true;
  30109. }
  30110. /**
  30111. * Overwrites the default {@link Node#customCacheKey} implementation by including
  30112. * light data into the cache key.
  30113. *
  30114. * @return {number} The custom cache key.
  30115. */
  30116. customCacheKey() {
  30117. const lights = this._lights;
  30118. for ( let i = 0; i < lights.length; i ++ ) {
  30119. const light = lights[ i ];
  30120. _hashData.push( light.id );
  30121. _hashData.push( light.castShadow ? 1 : 0 );
  30122. if ( light.isSpotLight === true ) {
  30123. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  30124. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  30125. _hashData.push( hashMap, hashColorNode );
  30126. }
  30127. }
  30128. const cacheKey = hashArray( _hashData );
  30129. _hashData.length = 0;
  30130. return cacheKey;
  30131. }
  30132. /**
  30133. * Computes a hash value for identifying the current light nodes setup.
  30134. *
  30135. * @param {NodeBuilder} builder - A reference to the current node builder.
  30136. * @return {string} The computed hash.
  30137. */
  30138. getHash( builder ) {
  30139. if ( this._lightNodesHash === null ) {
  30140. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30141. const hash = [];
  30142. for ( const lightNode of this._lightNodes ) {
  30143. hash.push( lightNode.getHash() );
  30144. }
  30145. this._lightNodesHash = 'lights-' + hash.join( ',' );
  30146. }
  30147. return this._lightNodesHash;
  30148. }
  30149. analyze( builder ) {
  30150. const properties = builder.getNodeProperties( this );
  30151. for ( const node of properties.nodes ) {
  30152. node.build( builder );
  30153. }
  30154. properties.outputNode.build( builder );
  30155. }
  30156. /**
  30157. * Creates lighting nodes for each scene light. This makes it possible to further
  30158. * process lights in the node system.
  30159. *
  30160. * @param {NodeBuilder} builder - A reference to the current node builder.
  30161. */
  30162. setupLightsNode( builder ) {
  30163. const lightNodes = [];
  30164. const previousLightNodes = this._lightNodes;
  30165. const lights = sortLights( this._lights );
  30166. const nodeLibrary = builder.renderer.library;
  30167. for ( const light of lights ) {
  30168. if ( light.isNode ) {
  30169. lightNodes.push( nodeObject( light ) );
  30170. } else {
  30171. let lightNode = null;
  30172. if ( previousLightNodes !== null ) {
  30173. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  30174. }
  30175. if ( lightNode === null ) {
  30176. // find the corresponding node type for a given light
  30177. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  30178. if ( lightNodeClass === null ) {
  30179. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  30180. continue;
  30181. }
  30182. let lightNode = null;
  30183. if ( ! _lightsNodeRef.has( light ) ) {
  30184. lightNode = new lightNodeClass( light );
  30185. _lightsNodeRef.set( light, lightNode );
  30186. } else {
  30187. lightNode = _lightsNodeRef.get( light );
  30188. }
  30189. lightNodes.push( lightNode );
  30190. }
  30191. }
  30192. }
  30193. this._lightNodes = lightNodes;
  30194. }
  30195. /**
  30196. * Sets up a direct light in the lighting model.
  30197. *
  30198. * @param {Object} builder - The builder object containing the context and stack.
  30199. * @param {Object} lightNode - The light node.
  30200. * @param {Object} lightData - The light object containing color and direction properties.
  30201. */
  30202. setupDirectLight( builder, lightNode, lightData ) {
  30203. const { lightingModel, reflectedLight } = builder.context;
  30204. lightingModel.direct( {
  30205. ...lightData,
  30206. lightNode,
  30207. reflectedLight
  30208. }, builder );
  30209. }
  30210. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  30211. const { lightingModel, reflectedLight } = builder.context;
  30212. lightingModel.directRectArea( {
  30213. ...lightData,
  30214. lightNode,
  30215. reflectedLight
  30216. }, builder );
  30217. }
  30218. /**
  30219. * Setups the internal lights by building all respective
  30220. * light nodes.
  30221. *
  30222. * @param {NodeBuilder} builder - A reference to the current node builder.
  30223. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  30224. */
  30225. setupLights( builder, lightNodes ) {
  30226. for ( const lightNode of lightNodes ) {
  30227. lightNode.build( builder );
  30228. }
  30229. }
  30230. getLightNodes( builder ) {
  30231. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30232. return this._lightNodes;
  30233. }
  30234. /**
  30235. * The implementation makes sure that for each light in the scene
  30236. * there is a corresponding light node. By building the light nodes
  30237. * and evaluating the lighting model the outgoing light is computed.
  30238. *
  30239. * @param {NodeBuilder} builder - A reference to the current node builder.
  30240. * @return {Node<vec3>} A node representing the outgoing light.
  30241. */
  30242. setup( builder ) {
  30243. const currentLightsNode = builder.lightsNode;
  30244. builder.lightsNode = this;
  30245. //
  30246. let outgoingLightNode = this.outgoingLightNode;
  30247. const context = builder.context;
  30248. const lightingModel = context.lightingModel;
  30249. const properties = builder.getNodeProperties( this );
  30250. if ( lightingModel ) {
  30251. const { totalDiffuseNode, totalSpecularNode } = this;
  30252. context.outgoingLight = outgoingLightNode;
  30253. const stack = builder.addStack();
  30254. //
  30255. properties.nodes = stack.nodes;
  30256. //
  30257. lightingModel.start( builder );
  30258. //
  30259. const { backdrop, backdropAlpha } = context;
  30260. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  30261. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  30262. if ( backdrop !== null ) {
  30263. if ( backdropAlpha !== null ) {
  30264. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  30265. } else {
  30266. totalDiffuse = vec3( backdrop );
  30267. }
  30268. }
  30269. totalDiffuseNode.assign( totalDiffuse );
  30270. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  30271. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  30272. //
  30273. lightingModel.finish( builder );
  30274. //
  30275. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  30276. } else {
  30277. properties.nodes = [];
  30278. }
  30279. //
  30280. builder.lightsNode = currentLightsNode;
  30281. return outgoingLightNode;
  30282. }
  30283. /**
  30284. * Configures this node with an array of lights.
  30285. *
  30286. * @param {Array<Light>} lights - An array of lights.
  30287. * @return {LightsNode} A reference to this node.
  30288. */
  30289. setLights( lights ) {
  30290. this._lights = lights;
  30291. this._lightNodes = null;
  30292. this._lightNodesHash = null;
  30293. return this;
  30294. }
  30295. /**
  30296. * Returns an array of the scene's lights.
  30297. *
  30298. * @return {Array<Light>} The scene's lights.
  30299. */
  30300. getLights() {
  30301. return this._lights;
  30302. }
  30303. /**
  30304. * Whether the scene has lights or not.
  30305. *
  30306. * @type {boolean}
  30307. */
  30308. get hasLights() {
  30309. return this._lights.length > 0;
  30310. }
  30311. }
  30312. /**
  30313. * TSL function for creating an instance of `LightsNode` and configuring
  30314. * it with the given array of lights.
  30315. *
  30316. * @tsl
  30317. * @function
  30318. * @param {Array<Light>} lights - An array of lights.
  30319. * @return {LightsNode} The created lights node.
  30320. */
  30321. const lights = ( lights = [] ) => new LightsNode().setLights( lights );
  30322. /**
  30323. * Base class for all shadow nodes.
  30324. *
  30325. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  30326. * Lighting nodes might share the same shadow node type or use specific ones depending on
  30327. * their requirements.
  30328. *
  30329. * @augments Node
  30330. */
  30331. class ShadowBaseNode extends Node {
  30332. static get type() {
  30333. return 'ShadowBaseNode';
  30334. }
  30335. /**
  30336. * Constructs a new shadow base node.
  30337. *
  30338. * @param {Light} light - The shadow casting light.
  30339. */
  30340. constructor( light ) {
  30341. super();
  30342. /**
  30343. * The shadow casting light.
  30344. *
  30345. * @type {Light}
  30346. */
  30347. this.light = light;
  30348. /**
  30349. * Overwritten since shadows are updated by default per render.
  30350. *
  30351. * @type {string}
  30352. * @default 'render'
  30353. */
  30354. this.updateBeforeType = NodeUpdateType.RENDER;
  30355. /**
  30356. * This flag can be used for type testing.
  30357. *
  30358. * @type {boolean}
  30359. * @readonly
  30360. * @default true
  30361. */
  30362. this.isShadowBaseNode = true;
  30363. }
  30364. /**
  30365. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  30366. *
  30367. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  30368. */
  30369. setupShadowPosition( { context, material } ) {
  30370. // Use assign inside an Fn()
  30371. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  30372. }
  30373. }
  30374. /**
  30375. * TSL object that represents the vertex position in world space during the shadow pass.
  30376. *
  30377. * @tsl
  30378. * @type {Node<vec3>}
  30379. */
  30380. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  30381. /**
  30382. * Saves the state of the given renderer and stores it into the given state object.
  30383. *
  30384. * If not state object is provided, the function creates one.
  30385. *
  30386. * @private
  30387. * @function
  30388. * @param {Renderer} renderer - The renderer.
  30389. * @param {Object} [state={}] - The state.
  30390. * @return {Object} The state.
  30391. */
  30392. function saveRendererState( renderer, state = {} ) {
  30393. state.toneMapping = renderer.toneMapping;
  30394. state.toneMappingExposure = renderer.toneMappingExposure;
  30395. state.outputColorSpace = renderer.outputColorSpace;
  30396. state.renderTarget = renderer.getRenderTarget();
  30397. state.activeCubeFace = renderer.getActiveCubeFace();
  30398. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  30399. state.renderObjectFunction = renderer.getRenderObjectFunction();
  30400. state.pixelRatio = renderer.getPixelRatio();
  30401. state.mrt = renderer.getMRT();
  30402. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  30403. state.clearAlpha = renderer.getClearAlpha();
  30404. state.autoClear = renderer.autoClear;
  30405. state.scissorTest = renderer.getScissorTest();
  30406. return state;
  30407. }
  30408. /**
  30409. * Saves the state of the given renderer and stores it into the given state object.
  30410. * Besides, the function also resets the state of the renderer to its default values.
  30411. *
  30412. * If not state object is provided, the function creates one.
  30413. *
  30414. * @private
  30415. * @function
  30416. * @param {Renderer} renderer - The renderer.
  30417. * @param {Object} [state={}] - The state.
  30418. * @return {Object} The state.
  30419. */
  30420. function resetRendererState( renderer, state ) {
  30421. state = saveRendererState( renderer, state );
  30422. renderer.setMRT( null );
  30423. renderer.setRenderObjectFunction( null );
  30424. renderer.setClearColor( 0x000000, 1 );
  30425. renderer.autoClear = true;
  30426. return state;
  30427. }
  30428. /**
  30429. * Restores the state of the given renderer from the given state object.
  30430. *
  30431. * @private
  30432. * @function
  30433. * @param {Renderer} renderer - The renderer.
  30434. * @param {Object} state - The state to restore.
  30435. */
  30436. function restoreRendererState( renderer, state ) {
  30437. renderer.toneMapping = state.toneMapping;
  30438. renderer.toneMappingExposure = state.toneMappingExposure;
  30439. renderer.outputColorSpace = state.outputColorSpace;
  30440. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  30441. renderer.setRenderObjectFunction( state.renderObjectFunction );
  30442. renderer.setPixelRatio( state.pixelRatio );
  30443. renderer.setMRT( state.mrt );
  30444. renderer.setClearColor( state.clearColor, state.clearAlpha );
  30445. renderer.autoClear = state.autoClear;
  30446. renderer.setScissorTest( state.scissorTest );
  30447. }
  30448. /**
  30449. * Saves the state of the given scene and stores it into the given state object.
  30450. *
  30451. * If not state object is provided, the function creates one.
  30452. *
  30453. * @private
  30454. * @function
  30455. * @param {Scene} scene - The scene.
  30456. * @param {Object} [state={}] - The state.
  30457. * @return {Object} The state.
  30458. */
  30459. function saveSceneState( scene, state = {} ) {
  30460. state.background = scene.background;
  30461. state.backgroundNode = scene.backgroundNode;
  30462. state.overrideMaterial = scene.overrideMaterial;
  30463. return state;
  30464. }
  30465. /**
  30466. * Saves the state of the given scene and stores it into the given state object.
  30467. * Besides, the function also resets the state of the scene to its default values.
  30468. *
  30469. * If not state object is provided, the function creates one.
  30470. *
  30471. * @private
  30472. * @function
  30473. * @param {Scene} scene - The scene.
  30474. * @param {Object} [state={}] - The state.
  30475. * @return {Object} The state.
  30476. */
  30477. function resetSceneState( scene, state ) {
  30478. state = saveSceneState( scene, state );
  30479. scene.background = null;
  30480. scene.backgroundNode = null;
  30481. scene.overrideMaterial = null;
  30482. return state;
  30483. }
  30484. /**
  30485. * Restores the state of the given scene from the given state object.
  30486. *
  30487. * @private
  30488. * @function
  30489. * @param {Scene} scene - The scene.
  30490. * @param {Object} state - The state to restore.
  30491. */
  30492. function restoreSceneState( scene, state ) {
  30493. scene.background = state.background;
  30494. scene.backgroundNode = state.backgroundNode;
  30495. scene.overrideMaterial = state.overrideMaterial;
  30496. }
  30497. /**
  30498. * Saves the state of the given renderer and scene and stores it into the given state object.
  30499. *
  30500. * If not state object is provided, the function creates one.
  30501. *
  30502. * @private
  30503. * @function
  30504. * @param {Renderer} renderer - The renderer.
  30505. * @param {Scene} scene - The scene.
  30506. * @param {Object} [state={}] - The state.
  30507. * @return {Object} The state.
  30508. */
  30509. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  30510. state = saveRendererState( renderer, state );
  30511. state = saveSceneState( scene, state );
  30512. return state;
  30513. }
  30514. /**
  30515. * Saves the state of the given renderer and scene and stores it into the given state object.
  30516. * Besides, the function also resets the state of the renderer and scene to its default values.
  30517. *
  30518. * If not state object is provided, the function creates one.
  30519. *
  30520. * @private
  30521. * @function
  30522. * @param {Renderer} renderer - The renderer.
  30523. * @param {Scene} scene - The scene.
  30524. * @param {Object} [state={}] - The state.
  30525. * @return {Object} The state.
  30526. */
  30527. function resetRendererAndSceneState( renderer, scene, state ) {
  30528. state = resetRendererState( renderer, state );
  30529. state = resetSceneState( scene, state );
  30530. return state;
  30531. }
  30532. /**
  30533. * Restores the state of the given renderer and scene from the given state object.
  30534. *
  30535. * @private
  30536. * @function
  30537. * @param {Renderer} renderer - The renderer.
  30538. * @param {Scene} scene - The scene.
  30539. * @param {Object} state - The state to restore.
  30540. */
  30541. function restoreRendererAndSceneState( renderer, scene, state ) {
  30542. restoreRendererState( renderer, state );
  30543. restoreSceneState( scene, state );
  30544. }
  30545. var RendererUtils = /*#__PURE__*/Object.freeze({
  30546. __proto__: null,
  30547. resetRendererAndSceneState: resetRendererAndSceneState,
  30548. resetRendererState: resetRendererState,
  30549. resetSceneState: resetSceneState,
  30550. restoreRendererAndSceneState: restoreRendererAndSceneState,
  30551. restoreRendererState: restoreRendererState,
  30552. restoreSceneState: restoreSceneState,
  30553. saveRendererAndSceneState: saveRendererAndSceneState,
  30554. saveRendererState: saveRendererState,
  30555. saveSceneState: saveSceneState
  30556. });
  30557. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  30558. /**
  30559. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  30560. * with a binary `[0,1]` result.
  30561. *
  30562. * @method
  30563. * @param {Object} inputs - The input parameter object.
  30564. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30565. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30566. * @return {Node<float>} The filtering result.
  30567. */
  30568. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  30569. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  30570. if ( depthTexture.isArrayTexture ) {
  30571. basic = basic.depth( depthLayer );
  30572. }
  30573. return basic.compare( shadowCoord.z );
  30574. } );
  30575. /**
  30576. * A shadow filtering function performing PCF filtering with Vogel disk sampling and IGN.
  30577. *
  30578. * Uses 5 samples distributed via Vogel disk pattern, rotated per-pixel using Interleaved
  30579. * Gradient Noise (IGN) to break up banding artifacts. Combined with hardware PCF (4-tap
  30580. * filtering per sample), this effectively provides 20 filtered taps with better distribution.
  30581. *
  30582. * @method
  30583. * @param {Object} inputs - The input parameter object.
  30584. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30585. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30586. * @param {LightShadow} inputs.shadow - The light shadow.
  30587. * @return {Node<float>} The filtering result.
  30588. */
  30589. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30590. const depthCompare = ( uv, compare ) => {
  30591. let depth = texture( depthTexture, uv );
  30592. if ( depthTexture.isArrayTexture ) {
  30593. depth = depth.depth( depthLayer );
  30594. }
  30595. return depth.compare( compare );
  30596. };
  30597. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30598. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30599. const texelSize = vec2( 1 ).div( mapSize );
  30600. const radiusScaled = radius.mul( texelSize.x );
  30601. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  30602. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  30603. // 5 samples using Vogel disk distribution
  30604. return add(
  30605. depthCompare( shadowCoord.xy.add( vogelDiskSample( 0, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30606. depthCompare( shadowCoord.xy.add( vogelDiskSample( 1, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30607. depthCompare( shadowCoord.xy.add( vogelDiskSample( 2, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30608. depthCompare( shadowCoord.xy.add( vogelDiskSample( 3, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30609. depthCompare( shadowCoord.xy.add( vogelDiskSample( 4, 5, phi ).mul( radiusScaled ) ), shadowCoord.z )
  30610. ).mul( 1 / 5 );
  30611. } );
  30612. /**
  30613. * A shadow filtering function performing PCF soft filtering.
  30614. *
  30615. * @method
  30616. * @param {Object} inputs - The input parameter object.
  30617. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30618. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30619. * @param {LightShadow} inputs.shadow - The light shadow.
  30620. * @return {Node<float>} The filtering result.
  30621. */
  30622. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30623. const depthCompare = ( uv, compare ) => {
  30624. let depth = texture( depthTexture, uv );
  30625. if ( depthTexture.isArrayTexture ) {
  30626. depth = depth.depth( depthLayer );
  30627. }
  30628. return depth.compare( compare );
  30629. };
  30630. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30631. const texelSize = vec2( 1 ).div( mapSize );
  30632. const dx = texelSize.x;
  30633. const dy = texelSize.y;
  30634. const uv = shadowCoord.xy;
  30635. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  30636. uv.subAssign( f.mul( texelSize ) );
  30637. return add(
  30638. depthCompare( uv, shadowCoord.z ),
  30639. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  30640. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  30641. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  30642. mix(
  30643. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  30644. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  30645. f.x
  30646. ),
  30647. mix(
  30648. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  30649. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  30650. f.x
  30651. ),
  30652. mix(
  30653. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  30654. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  30655. f.y
  30656. ),
  30657. mix(
  30658. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  30659. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  30660. f.y
  30661. ),
  30662. mix(
  30663. mix(
  30664. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  30665. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  30666. f.x
  30667. ),
  30668. mix(
  30669. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  30670. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  30671. f.x
  30672. ),
  30673. f.y
  30674. )
  30675. ).mul( 1 / 9 );
  30676. } );
  30677. /**
  30678. * A shadow filtering function performing VSM filtering.
  30679. *
  30680. * @method
  30681. * @param {Object} inputs - The input parameter object.
  30682. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30683. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30684. * @return {Node<float>} The filtering result.
  30685. */
  30686. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer }, builder ) => {
  30687. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  30688. if ( depthTexture.isArrayTexture ) {
  30689. distribution = distribution.depth( depthLayer );
  30690. }
  30691. distribution = distribution.rg;
  30692. const mean = distribution.x;
  30693. const variance = max$1( 0.0000001, distribution.y.mul( distribution.y ) );
  30694. const hardShadow = ( builder.renderer.reversedDepthBuffer ) ? step( mean, shadowCoord.z ) : step( shadowCoord.z, mean );
  30695. const output = float( 1 ).toVar(); // default, fully lit
  30696. If( hardShadow.notEqual( 1.0 ), () => {
  30697. // Distance from mean
  30698. const d = shadowCoord.z.sub( mean );
  30699. // Chebyshev's inequality for upper bound on probability
  30700. let p_max = variance.div( variance.add( d.mul( d ) ) );
  30701. // Reduce light bleeding by remapping [amount, 1] to [0, 1]
  30702. p_max = clamp( sub( p_max, 0.3 ).div( 0.65 ) );
  30703. output.assign( max$1( hardShadow, p_max ) );
  30704. } );
  30705. return output;
  30706. } );
  30707. /**
  30708. * Retrieves or creates a shadow material for the given light source.
  30709. *
  30710. * This function checks if a shadow material already exists for the provided light.
  30711. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  30712. * in the `shadowMaterialLib` for future use.
  30713. *
  30714. * @tsl
  30715. * @function
  30716. * @param {Light} light - The light source for which the shadow material is needed.
  30717. * If the light is a point light, a depth node is calculated
  30718. * using the linear shadow distance.
  30719. * @returns {NodeMaterial} The shadow material associated with the given light.
  30720. */
  30721. const getShadowMaterial = ( light ) => {
  30722. let material = shadowMaterialLib.get( light );
  30723. if ( material === undefined ) {
  30724. material = new NodeMaterial();
  30725. material.colorNode = vec4( 0, 0, 0, 1 );
  30726. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  30727. material.name = 'ShadowMaterial';
  30728. material.blending = NoBlending;
  30729. material.fog = false;
  30730. shadowMaterialLib.set( light, material );
  30731. }
  30732. return material;
  30733. };
  30734. /**
  30735. * Disposes the shadow material for the given light source.
  30736. *
  30737. * @param {Light} light - The light source.
  30738. */
  30739. const disposeShadowMaterial = ( light ) => {
  30740. const material = shadowMaterialLib.get( light );
  30741. if ( material !== undefined ) {
  30742. material.dispose();
  30743. shadowMaterialLib.delete( light );
  30744. }
  30745. };
  30746. //
  30747. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  30748. const _shadowRenderObjectKeys = [];
  30749. /**
  30750. * Creates a function to render shadow objects in a scene.
  30751. *
  30752. * @tsl
  30753. * @function
  30754. * @param {Renderer} renderer - The renderer.
  30755. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  30756. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  30757. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  30758. * @return {shadowRenderObjectFunction} A function that renders shadow objects.
  30759. */
  30760. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  30761. _shadowRenderObjectKeys[ 0 ] = renderer;
  30762. _shadowRenderObjectKeys[ 1 ] = shadow;
  30763. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  30764. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  30765. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  30766. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  30767. if ( useVelocity ) {
  30768. getDataFromObject( object ).useVelocity = true;
  30769. }
  30770. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  30771. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  30772. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  30773. }
  30774. };
  30775. renderObjectFunction.shadowType = shadowType;
  30776. renderObjectFunction.useVelocity = useVelocity;
  30777. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  30778. }
  30779. _shadowRenderObjectKeys[ 0 ] = null;
  30780. _shadowRenderObjectKeys[ 1 ] = null;
  30781. return renderObjectFunction;
  30782. };
  30783. /**
  30784. * Represents the shader code for the first VSM render pass.
  30785. *
  30786. * @private
  30787. * @method
  30788. * @param {Object} inputs - The input parameter object.
  30789. * @param {Node<float>} inputs.samples - The number of samples
  30790. * @param {Node<float>} inputs.radius - The radius.
  30791. * @param {Node<float>} inputs.size - The size.
  30792. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  30793. * @return {Node<vec2>} The VSM output.
  30794. */
  30795. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  30796. const mean = float( 0 ).toVar( 'meanVertical' );
  30797. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  30798. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  30799. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  30800. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  30801. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  30802. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  30803. if ( shadowPass.value.isArrayTexture ) {
  30804. depth = depth.depth( depthLayer );
  30805. }
  30806. depth = depth.x;
  30807. mean.addAssign( depth );
  30808. squaredMean.addAssign( depth.mul( depth ) );
  30809. } );
  30810. mean.divAssign( samples );
  30811. squaredMean.divAssign( samples );
  30812. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  30813. return vec2( mean, std_dev );
  30814. } );
  30815. /**
  30816. * Represents the shader code for the second VSM render pass.
  30817. *
  30818. * @private
  30819. * @method
  30820. * @param {Object} inputs - The input parameter object.
  30821. * @param {Node<float>} inputs.samples - The number of samples
  30822. * @param {Node<float>} inputs.radius - The radius.
  30823. * @param {Node<float>} inputs.size - The size.
  30824. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  30825. * @return {Node<vec2>} The VSM output.
  30826. */
  30827. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  30828. const mean = float( 0 ).toVar( 'meanHorizontal' );
  30829. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  30830. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  30831. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  30832. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  30833. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  30834. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  30835. if ( shadowPass.value.isArrayTexture ) {
  30836. distribution = distribution.depth( depthLayer );
  30837. }
  30838. mean.addAssign( distribution.x );
  30839. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  30840. } );
  30841. mean.divAssign( samples );
  30842. squaredMean.divAssign( samples );
  30843. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  30844. return vec2( mean, std_dev );
  30845. } );
  30846. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  30847. //
  30848. let _rendererState;
  30849. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  30850. /**
  30851. * Represents the default shadow implementation for lighting nodes.
  30852. *
  30853. * @augments ShadowBaseNode
  30854. */
  30855. class ShadowNode extends ShadowBaseNode {
  30856. static get type() {
  30857. return 'ShadowNode';
  30858. }
  30859. /**
  30860. * Constructs a new shadow node.
  30861. *
  30862. * @param {Light} light - The shadow casting light.
  30863. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  30864. */
  30865. constructor( light, shadow = null ) {
  30866. super( light );
  30867. /**
  30868. * The light shadow which defines the properties light's
  30869. * shadow.
  30870. *
  30871. * @type {?LightShadow}
  30872. * @default null
  30873. */
  30874. this.shadow = shadow || light.shadow;
  30875. /**
  30876. * A reference to the shadow map which is a render target.
  30877. *
  30878. * @type {?RenderTarget}
  30879. * @default null
  30880. */
  30881. this.shadowMap = null;
  30882. /**
  30883. * Only relevant for VSM shadows. Render target for the
  30884. * first VSM render pass.
  30885. *
  30886. * @type {?RenderTarget}
  30887. * @default null
  30888. */
  30889. this.vsmShadowMapVertical = null;
  30890. /**
  30891. * Only relevant for VSM shadows. Render target for the
  30892. * second VSM render pass.
  30893. *
  30894. * @type {?RenderTarget}
  30895. * @default null
  30896. */
  30897. this.vsmShadowMapHorizontal = null;
  30898. /**
  30899. * Only relevant for VSM shadows. Node material which
  30900. * is used to render the first VSM pass.
  30901. *
  30902. * @type {?NodeMaterial}
  30903. * @default null
  30904. */
  30905. this.vsmMaterialVertical = null;
  30906. /**
  30907. * Only relevant for VSM shadows. Node material which
  30908. * is used to render the second VSM pass.
  30909. *
  30910. * @type {?NodeMaterial}
  30911. * @default null
  30912. */
  30913. this.vsmMaterialHorizontal = null;
  30914. /**
  30915. * A reference to the output node which defines the
  30916. * final result of this shadow node.
  30917. *
  30918. * @type {?Node}
  30919. * @private
  30920. * @default null
  30921. */
  30922. this._node = null;
  30923. /**
  30924. * The current shadow map type of this shadow node.
  30925. *
  30926. * @type {?number}
  30927. * @private
  30928. * @default null
  30929. */
  30930. this._currentShadowType = null;
  30931. /**
  30932. * A Weak Map holding the current frame ID per camera. Used
  30933. * to control the update of shadow maps.
  30934. *
  30935. * @type {WeakMap<Camera,number>}
  30936. * @private
  30937. */
  30938. this._cameraFrameId = new WeakMap();
  30939. /**
  30940. * This flag can be used for type testing.
  30941. *
  30942. * @type {boolean}
  30943. * @readonly
  30944. * @default true
  30945. */
  30946. this.isShadowNode = true;
  30947. /**
  30948. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  30949. *
  30950. * @type {number}
  30951. * @readonly
  30952. * @default true
  30953. */
  30954. this.depthLayer = 0;
  30955. }
  30956. /**
  30957. * Setups the shadow filtering.
  30958. *
  30959. * @param {NodeBuilder} builder - A reference to the current node builder.
  30960. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  30961. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  30962. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30963. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  30964. * @param {LightShadow} inputs.shadow - The light shadow.
  30965. * @return {Node<float>} The result node of the shadow filtering.
  30966. */
  30967. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  30968. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  30969. .and( shadowCoord.x.lessThanEqual( 1 ) )
  30970. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  30971. .and( shadowCoord.y.lessThanEqual( 1 ) )
  30972. .and( shadowCoord.z.lessThanEqual( 1 ) );
  30973. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  30974. return frustumTest.select( shadowNode, float( 1 ) );
  30975. }
  30976. /**
  30977. * Setups the shadow coordinates.
  30978. *
  30979. * @param {NodeBuilder} builder - A reference to the current node builder.
  30980. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  30981. * @return {Node<vec3>} The shadow coordinates.
  30982. */
  30983. setupShadowCoord( builder, shadowPosition ) {
  30984. const { shadow } = this;
  30985. const { renderer } = builder;
  30986. const bias = shadow.biasNode || reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  30987. let shadowCoord = shadowPosition;
  30988. let coordZ;
  30989. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  30990. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  30991. coordZ = shadowCoord.z;
  30992. } else {
  30993. const w = shadowCoord.w;
  30994. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  30995. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  30996. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  30997. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  30998. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  30999. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  31000. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  31001. }
  31002. shadowCoord = vec3(
  31003. shadowCoord.x,
  31004. shadowCoord.y.oneMinus(), // follow webgpu standards
  31005. renderer.reversedDepthBuffer ? coordZ.sub( bias ) : coordZ.add( bias )
  31006. );
  31007. return shadowCoord;
  31008. }
  31009. /**
  31010. * Returns the shadow filtering function for the given shadow type.
  31011. *
  31012. * @param {number} type - The shadow type.
  31013. * @return {Function} The filtering function.
  31014. */
  31015. getShadowFilterFn( type ) {
  31016. return _shadowFilterLib[ type ];
  31017. }
  31018. setupRenderTarget( shadow, builder ) {
  31019. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  31020. depthTexture.name = 'ShadowDepthTexture';
  31021. depthTexture.compareFunction = builder.renderer.reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  31022. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  31023. shadowMap.texture.name = 'ShadowMap';
  31024. shadowMap.texture.type = shadow.mapType;
  31025. shadowMap.depthTexture = depthTexture;
  31026. return { shadowMap, depthTexture };
  31027. }
  31028. /**
  31029. * Setups the shadow output node.
  31030. *
  31031. * @param {NodeBuilder} builder - A reference to the current node builder.
  31032. * @return {Node<vec3>} The shadow output node.
  31033. */
  31034. setupShadow( builder ) {
  31035. const { renderer, camera } = builder;
  31036. const { light, shadow } = this;
  31037. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  31038. const shadowMapType = renderer.shadowMap.type;
  31039. if ( shadowMapType === PCFShadowMap || shadowMapType === PCFSoftShadowMap ) {
  31040. depthTexture.minFilter = LinearFilter;
  31041. depthTexture.magFilter = LinearFilter;
  31042. } else {
  31043. depthTexture.minFilter = NearestFilter;
  31044. depthTexture.magFilter = NearestFilter;
  31045. }
  31046. shadow.camera.coordinateSystem = camera.coordinateSystem;
  31047. shadow.camera.updateProjectionMatrix();
  31048. // VSM
  31049. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31050. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  31051. if ( shadowMap.depth > 1 ) {
  31052. if ( ! shadowMap._vsmShadowMapVertical ) {
  31053. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31054. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  31055. }
  31056. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  31057. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  31058. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31059. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  31060. }
  31061. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  31062. } else {
  31063. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31064. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31065. }
  31066. let shadowPassVertical = texture( depthTexture );
  31067. if ( depthTexture.isArrayTexture ) {
  31068. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  31069. }
  31070. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  31071. if ( depthTexture.isArrayTexture ) {
  31072. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  31073. }
  31074. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  31075. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31076. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31077. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  31078. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31079. material.name = 'VSMVertical';
  31080. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  31081. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31082. material.name = 'VSMHorizontal';
  31083. }
  31084. //
  31085. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  31086. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  31087. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  31088. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  31089. //
  31090. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  31091. if ( filterFn === null ) {
  31092. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  31093. }
  31094. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  31095. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  31096. let shadowColor;
  31097. if ( renderer.shadowMap.transmitted === true ) {
  31098. if ( shadowMap.texture.isCubeTexture ) {
  31099. // For cube shadow maps (point lights), use cubeTexture with vec3 coordinates
  31100. shadowColor = cubeTexture( shadowMap.texture, shadowCoord.xyz );
  31101. } else {
  31102. shadowColor = texture( shadowMap.texture, shadowCoord );
  31103. if ( depthTexture.isArrayTexture ) {
  31104. shadowColor = shadowColor.depth( this.depthLayer );
  31105. }
  31106. }
  31107. }
  31108. //
  31109. let shadowOutput;
  31110. if ( shadowColor ) {
  31111. shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  31112. } else {
  31113. shadowOutput = mix( 1, shadowNode, shadowIntensity ).toVar();
  31114. }
  31115. this.shadowMap = shadowMap;
  31116. this.shadow.map = shadowMap;
  31117. // Shadow Output + Inspector
  31118. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  31119. if ( shadowColor ) {
  31120. shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  31121. if ( this.shadowMap.texture.isCubeTexture ) {
  31122. return cubeTexture( this.shadowMap.texture );
  31123. }
  31124. return texture( this.shadowMap.texture );
  31125. } );
  31126. }
  31127. return shadowOutput.toInspector( `${ inspectName } / Depth`, () => {
  31128. // TODO: Use linear depth
  31129. if ( this.shadowMap.texture.isCubeTexture ) {
  31130. return cubeTexture( this.shadowMap.texture ).r.oneMinus();
  31131. }
  31132. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).r.oneMinus();
  31133. } );
  31134. }
  31135. /**
  31136. * The implementation performs the setup of the output node. An output is only
  31137. * produces if shadow mapping is globally enabled in the renderer.
  31138. *
  31139. * @param {NodeBuilder} builder - A reference to the current node builder.
  31140. * @return {ShaderCallNodeInternal} The output node.
  31141. */
  31142. setup( builder ) {
  31143. if ( builder.renderer.shadowMap.enabled === false ) return;
  31144. return Fn( () => {
  31145. const currentShadowType = builder.renderer.shadowMap.type;
  31146. if ( this._currentShadowType !== currentShadowType ) {
  31147. this._reset();
  31148. this._node = null;
  31149. }
  31150. let node = this._node;
  31151. this.setupShadowPosition( builder );
  31152. if ( node === null ) {
  31153. this._node = node = this.setupShadow( builder );
  31154. this._currentShadowType = currentShadowType;
  31155. }
  31156. if ( builder.material.receivedShadowNode ) {
  31157. node = builder.material.receivedShadowNode( node );
  31158. }
  31159. return node;
  31160. } )();
  31161. }
  31162. /**
  31163. * Renders the shadow. The logic of this function could be included
  31164. * into {@link ShadowNode#updateShadow} however more specialized shadow
  31165. * nodes might require a custom shadow map rendering. By having a
  31166. * dedicated method, it's easier to overwrite the default behavior.
  31167. *
  31168. * @param {NodeFrame} frame - A reference to the current node frame.
  31169. */
  31170. renderShadow( frame ) {
  31171. const { shadow, shadowMap, light } = this;
  31172. const { renderer, scene } = frame;
  31173. shadow.updateMatrices( light );
  31174. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  31175. const currentSceneName = scene.name;
  31176. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  31177. renderer.render( scene, shadow.camera );
  31178. scene.name = currentSceneName;
  31179. }
  31180. /**
  31181. * Updates the shadow.
  31182. *
  31183. * @param {NodeFrame} frame - A reference to the current node frame.
  31184. */
  31185. updateShadow( frame ) {
  31186. const { shadowMap, light, shadow } = this;
  31187. const { renderer, scene, camera } = frame;
  31188. const shadowType = renderer.shadowMap.type;
  31189. const depthVersion = shadowMap.depthTexture.version;
  31190. this._depthVersionCached = depthVersion;
  31191. const _shadowCameraLayer = shadow.camera.layers.mask;
  31192. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  31193. shadow.camera.layers.mask = camera.layers.mask;
  31194. }
  31195. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  31196. const currentMRT = renderer.getMRT();
  31197. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  31198. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  31199. scene.overrideMaterial = getShadowMaterial( light );
  31200. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  31201. renderer.setClearColor( 0x000000, 0 );
  31202. renderer.setRenderTarget( shadowMap );
  31203. this.renderShadow( frame );
  31204. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  31205. // vsm blur pass
  31206. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31207. this.vsmPass( renderer );
  31208. }
  31209. shadow.camera.layers.mask = _shadowCameraLayer;
  31210. restoreRendererAndSceneState( renderer, scene, _rendererState );
  31211. }
  31212. /**
  31213. * For VSM additional render passes are required.
  31214. *
  31215. * @param {Renderer} renderer - A reference to the current renderer.
  31216. */
  31217. vsmPass( renderer ) {
  31218. const { shadow } = this;
  31219. const depth = this.shadowMap.depth;
  31220. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31221. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31222. renderer.setRenderTarget( this.vsmShadowMapVertical );
  31223. _quadMesh.material = this.vsmMaterialVertical;
  31224. _quadMesh.render( renderer );
  31225. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  31226. _quadMesh.material = this.vsmMaterialHorizontal;
  31227. _quadMesh.render( renderer );
  31228. }
  31229. /**
  31230. * Frees the internal resources of this shadow node.
  31231. */
  31232. dispose() {
  31233. this._reset();
  31234. super.dispose();
  31235. }
  31236. /**
  31237. * Resets the resouce state of this shadow node.
  31238. *
  31239. * @private
  31240. */
  31241. _reset() {
  31242. this._currentShadowType = null;
  31243. disposeShadowMaterial( this.light );
  31244. if ( this.shadowMap ) {
  31245. this.shadowMap.dispose();
  31246. this.shadowMap = null;
  31247. }
  31248. if ( this.vsmShadowMapVertical !== null ) {
  31249. this.vsmShadowMapVertical.dispose();
  31250. this.vsmShadowMapVertical = null;
  31251. this.vsmMaterialVertical.dispose();
  31252. this.vsmMaterialVertical = null;
  31253. }
  31254. if ( this.vsmShadowMapHorizontal !== null ) {
  31255. this.vsmShadowMapHorizontal.dispose();
  31256. this.vsmShadowMapHorizontal = null;
  31257. this.vsmMaterialHorizontal.dispose();
  31258. this.vsmMaterialHorizontal = null;
  31259. }
  31260. }
  31261. /**
  31262. * The implementation performs the update of the shadow map if necessary.
  31263. *
  31264. * @param {NodeFrame} frame - A reference to the current node frame.
  31265. */
  31266. updateBefore( frame ) {
  31267. const { shadow } = this;
  31268. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  31269. if ( needsUpdate ) {
  31270. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  31271. needsUpdate = false;
  31272. }
  31273. this._cameraFrameId[ frame.camera ] = frame.frameId;
  31274. }
  31275. if ( needsUpdate ) {
  31276. this.updateShadow( frame );
  31277. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  31278. shadow.needsUpdate = false;
  31279. }
  31280. }
  31281. }
  31282. }
  31283. /**
  31284. * Shadow Render Object Function.
  31285. *
  31286. * @function shadowRenderObjectFunction
  31287. * @param {Object3D} object - The 3D object to render.
  31288. * @param {Scene} scene - The scene containing the object.
  31289. * @param {Camera} _camera - The camera used for rendering.
  31290. * @param {BufferGeometry} geometry - The geometry of the object.
  31291. * @param {Material} material - The material of the object.
  31292. * @param {Group} group - The group the object belongs to.
  31293. * @param {...any} params - Additional parameters for rendering.
  31294. */
  31295. /**
  31296. * TSL function for creating an instance of `ShadowNode`.
  31297. *
  31298. * @tsl
  31299. * @function
  31300. * @param {Light} light - The shadow casting light.
  31301. * @param {?LightShadow} [shadow] - The light shadow.
  31302. * @return {ShadowNode} The created shadow node.
  31303. */
  31304. const shadow = ( light, shadow ) => new ShadowNode( light, shadow );
  31305. const _clearColor$1 = /*@__PURE__*/ new Color();
  31306. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  31307. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  31308. const _lookTarget = /*@__PURE__*/ new Vector3();
  31309. // Cube map face directions and up vectors for point light shadows
  31310. // Face order: +X, -X, +Y, -Y, +Z, -Z
  31311. // WebGPU coordinate system - Y faces swapped to match texture sampling convention
  31312. const _cubeDirectionsWebGPU = [
  31313. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ),
  31314. /*@__PURE__*/ new Vector3( 0, 1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  31315. ];
  31316. const _cubeUpsWebGPU = [
  31317. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, -1 ),
  31318. /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  31319. ];
  31320. // WebGL coordinate system - standard OpenGL convention
  31321. const _cubeDirectionsWebGL = [
  31322. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  31323. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  31324. ];
  31325. const _cubeUpsWebGL = [
  31326. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  31327. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  31328. ];
  31329. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp } ) => {
  31330. return cubeTexture( depthTexture, bd3D ).compare( dp );
  31331. } );
  31332. /**
  31333. * A shadow filtering function for point lights using Vogel disk sampling and IGN.
  31334. *
  31335. * Uses 5 samples distributed via Vogel disk pattern in tangent space around the
  31336. * sample direction, rotated per-pixel using Interleaved Gradient Noise (IGN).
  31337. *
  31338. * @method
  31339. * @param {Object} inputs - The input parameter object.
  31340. * @param {CubeDepthTexture} inputs.depthTexture - A reference to the shadow cube map.
  31341. * @param {Node<vec3>} inputs.bd3D - The normalized direction from light to fragment.
  31342. * @param {Node<float>} inputs.dp - The depth value to compare against.
  31343. * @param {LightShadow} inputs.shadow - The light shadow.
  31344. * @return {Node<float>} The filtering result.
  31345. */
  31346. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, shadow } ) => {
  31347. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31348. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31349. const texelSize = radius.div( mapSize.x );
  31350. // Build a tangent-space coordinate system for applying offsets
  31351. const absDir = abs( bd3D );
  31352. const tangent = normalize( cross( bd3D, absDir.x.greaterThan( absDir.z ).select( vec3( 0, 1, 0 ), vec3( 1, 0, 0 ) ) ) );
  31353. const bitangent = cross( bd3D, tangent );
  31354. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  31355. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  31356. // 5 samples using Vogel disk distribution in tangent space
  31357. const sample0 = vogelDiskSample( 0, 5, phi );
  31358. const sample1 = vogelDiskSample( 1, 5, phi );
  31359. const sample2 = vogelDiskSample( 2, 5, phi );
  31360. const sample3 = vogelDiskSample( 3, 5, phi );
  31361. const sample4 = vogelDiskSample( 4, 5, phi );
  31362. return cubeTexture( depthTexture, bd3D.add( tangent.mul( sample0.x ).add( bitangent.mul( sample0.y ) ).mul( texelSize ) ) ).compare( dp )
  31363. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample1.x ).add( bitangent.mul( sample1.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31364. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample2.x ).add( bitangent.mul( sample2.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31365. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample3.x ).add( bitangent.mul( sample3.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31366. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample4.x ).add( bitangent.mul( sample4.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31367. .mul( 1.0 / 5.0 );
  31368. } );
  31369. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow }, builder ) => {
  31370. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  31371. // the vector from the light to the world-space position of the fragment.
  31372. const shadowPosition = shadowCoord.xyz.toConst();
  31373. const shadowPositionAbs = shadowPosition.abs().toConst();
  31374. const viewZ = shadowPositionAbs.x.max( shadowPositionAbs.y ).max( shadowPositionAbs.z );
  31375. const shadowCameraNear = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  31376. const shadowCameraFar = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  31377. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31378. const result = float( 1.0 ).toVar();
  31379. If( viewZ.sub( shadowCameraFar ).lessThanEqual( 0.0 ).and( viewZ.sub( shadowCameraNear ).greaterThanEqual( 0.0 ) ), () => {
  31380. let dp;
  31381. if ( builder.renderer.reversedDepthBuffer ) {
  31382. dp = viewZToReversedPerspectiveDepth( viewZ.negate(), shadowCameraNear, shadowCameraFar );
  31383. dp.subAssign( bias );
  31384. } else {
  31385. dp = viewZToPerspectiveDepth( viewZ.negate(), shadowCameraNear, shadowCameraFar );
  31386. dp.addAssign( bias );
  31387. }
  31388. // bd3D = base direction 3D (direction from light to fragment)
  31389. const bd3D = shadowPosition.normalize();
  31390. // percentage-closer filtering using cube texture sampling
  31391. result.assign( filterFn( { depthTexture, bd3D, dp, shadow } ) );
  31392. } );
  31393. return result;
  31394. } );
  31395. /**
  31396. * Represents the shadow implementation for point light nodes.
  31397. *
  31398. * @augments ShadowNode
  31399. */
  31400. class PointShadowNode extends ShadowNode {
  31401. static get type() {
  31402. return 'PointShadowNode';
  31403. }
  31404. /**
  31405. * Constructs a new point shadow node.
  31406. *
  31407. * @param {PointLight} light - The shadow casting point light.
  31408. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31409. */
  31410. constructor( light, shadow = null ) {
  31411. super( light, shadow );
  31412. }
  31413. /**
  31414. * Overwrites the default implementation to return point light shadow specific
  31415. * filtering functions.
  31416. *
  31417. * @param {number} type - The shadow type.
  31418. * @return {Function} The filtering function.
  31419. */
  31420. getShadowFilterFn( type ) {
  31421. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  31422. }
  31423. /**
  31424. * Overwrites the default implementation so the unaltered shadow position is used.
  31425. *
  31426. * @param {NodeBuilder} builder - A reference to the current node builder.
  31427. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31428. * @return {Node<vec3>} The shadow coordinates.
  31429. */
  31430. setupShadowCoord( builder, shadowPosition ) {
  31431. return shadowPosition;
  31432. }
  31433. /**
  31434. * Overwrites the default implementation to only use point light specific
  31435. * shadow filter functions.
  31436. *
  31437. * @param {NodeBuilder} builder - A reference to the current node builder.
  31438. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31439. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31440. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's depth texture.
  31441. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31442. * @param {LightShadow} inputs.shadow - The light shadow.
  31443. * @return {Node<float>} The result node of the shadow filtering.
  31444. */
  31445. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  31446. return pointShadowFilter( { filterFn, depthTexture, shadowCoord, shadow } );
  31447. }
  31448. /**
  31449. * Overwrites the default implementation to create a CubeRenderTarget with CubeDepthTexture.
  31450. *
  31451. * @param {LightShadow} shadow - The light shadow object.
  31452. * @param {NodeBuilder} builder - A reference to the current node builder.
  31453. * @return {Object} An object containing the shadow map and depth texture.
  31454. */
  31455. setupRenderTarget( shadow, builder ) {
  31456. const depthTexture = new CubeDepthTexture( shadow.mapSize.width );
  31457. depthTexture.name = 'PointShadowDepthTexture';
  31458. depthTexture.compareFunction = builder.renderer.reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  31459. const shadowMap = builder.createCubeRenderTarget( shadow.mapSize.width );
  31460. shadowMap.texture.name = 'PointShadowMap';
  31461. shadowMap.depthTexture = depthTexture;
  31462. return { shadowMap, depthTexture };
  31463. }
  31464. /**
  31465. * Overwrites the default implementation with point light specific
  31466. * rendering code.
  31467. *
  31468. * @param {NodeFrame} frame - A reference to the current node frame.
  31469. */
  31470. renderShadow( frame ) {
  31471. const { shadow, shadowMap, light } = this;
  31472. const { renderer, scene } = frame;
  31473. const camera = shadow.camera;
  31474. const shadowMatrix = shadow.matrix;
  31475. // Select cube directions/ups based on coordinate system
  31476. const isWebGPU = renderer.coordinateSystem === WebGPUCoordinateSystem;
  31477. const cubeDirections = isWebGPU ? _cubeDirectionsWebGPU : _cubeDirectionsWebGL;
  31478. const cubeUps = isWebGPU ? _cubeUpsWebGPU : _cubeUpsWebGL;
  31479. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.width );
  31480. //
  31481. const previousAutoClear = renderer.autoClear;
  31482. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  31483. const previousClearAlpha = renderer.getClearAlpha();
  31484. renderer.autoClear = false;
  31485. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  31486. // Render each cube face
  31487. for ( let face = 0; face < 6; face ++ ) {
  31488. // Set render target to the specific cube face
  31489. renderer.setRenderTarget( shadowMap, face );
  31490. renderer.clear();
  31491. // Update shadow camera matrices for this face
  31492. const far = light.distance || camera.far;
  31493. if ( far !== camera.far ) {
  31494. camera.far = far;
  31495. camera.updateProjectionMatrix();
  31496. }
  31497. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  31498. camera.position.copy( _lightPositionWorld );
  31499. _lookTarget.copy( camera.position );
  31500. _lookTarget.add( cubeDirections[ face ] );
  31501. camera.up.copy( cubeUps[ face ] );
  31502. camera.lookAt( _lookTarget );
  31503. camera.updateMatrixWorld();
  31504. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  31505. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  31506. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix$1, camera.coordinateSystem, camera.reversedDepth );
  31507. //
  31508. const currentSceneName = scene.name;
  31509. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ face + 1 }`;
  31510. renderer.render( scene, camera );
  31511. scene.name = currentSceneName;
  31512. }
  31513. //
  31514. renderer.autoClear = previousAutoClear;
  31515. renderer.setClearColor( previousClearColor, previousClearAlpha );
  31516. }
  31517. }
  31518. /**
  31519. * TSL function for creating an instance of `PointShadowNode`.
  31520. *
  31521. * @tsl
  31522. * @function
  31523. * @param {PointLight} light - The shadow casting point light.
  31524. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31525. * @return {PointShadowNode} The created point shadow node.
  31526. */
  31527. const pointShadow = ( light, shadow ) => new PointShadowNode( light, shadow );
  31528. /**
  31529. * Base class for analytic light nodes.
  31530. *
  31531. * @augments LightingNode
  31532. */
  31533. class AnalyticLightNode extends LightingNode {
  31534. static get type() {
  31535. return 'AnalyticLightNode';
  31536. }
  31537. /**
  31538. * Constructs a new analytic light node.
  31539. *
  31540. * @param {?Light} [light=null] - The light source.
  31541. */
  31542. constructor( light = null ) {
  31543. super();
  31544. /**
  31545. * The light source.
  31546. *
  31547. * @type {?Light}
  31548. * @default null
  31549. */
  31550. this.light = light;
  31551. /**
  31552. * The light's color value.
  31553. *
  31554. * @type {Color}
  31555. */
  31556. this.color = new Color();
  31557. /**
  31558. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  31559. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  31560. *
  31561. * @type {Node}
  31562. */
  31563. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  31564. /**
  31565. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  31566. * The final color node is represented by a different node when using shadows.
  31567. *
  31568. * @type {?Node}
  31569. * @default null
  31570. */
  31571. this.baseColorNode = null;
  31572. /**
  31573. * Represents the light's shadow.
  31574. *
  31575. * @type {?ShadowNode}
  31576. * @default null
  31577. */
  31578. this.shadowNode = null;
  31579. /**
  31580. * Represents the light's shadow color.
  31581. *
  31582. * @type {?Node}
  31583. * @default null
  31584. */
  31585. this.shadowColorNode = null;
  31586. /**
  31587. * This flag can be used for type testing.
  31588. *
  31589. * @type {boolean}
  31590. * @readonly
  31591. * @default true
  31592. */
  31593. this.isAnalyticLightNode = true;
  31594. /**
  31595. * Overwritten since analytic light nodes are updated
  31596. * once per frame.
  31597. *
  31598. * @type {string}
  31599. * @default 'frame'
  31600. */
  31601. this.updateType = NodeUpdateType.FRAME;
  31602. if ( light && light.shadow ) {
  31603. this._shadowDisposeListener = () => {
  31604. this.disposeShadow();
  31605. };
  31606. light.addEventListener( 'dispose', this._shadowDisposeListener );
  31607. }
  31608. }
  31609. dispose() {
  31610. if ( this._shadowDisposeListener ) {
  31611. this.light.removeEventListener( 'dispose', this._shadowDisposeListener );
  31612. }
  31613. super.dispose();
  31614. }
  31615. /**
  31616. * Frees internal resources related to shadows.
  31617. */
  31618. disposeShadow() {
  31619. if ( this.shadowNode !== null ) {
  31620. this.shadowNode.dispose();
  31621. this.shadowNode = null;
  31622. }
  31623. this.shadowColorNode = null;
  31624. if ( this.baseColorNode !== null ) {
  31625. this.colorNode = this.baseColorNode;
  31626. this.baseColorNode = null;
  31627. }
  31628. }
  31629. getHash() {
  31630. return this.light.uuid;
  31631. }
  31632. /**
  31633. * Returns a node representing a direction vector which points from the current
  31634. * position in view space to the light's position in view space.
  31635. *
  31636. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31637. * @return {Node<vec3>} The light vector node.
  31638. */
  31639. getLightVector( builder ) {
  31640. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  31641. }
  31642. /**
  31643. * Sets up the direct lighting for the analytic light node.
  31644. *
  31645. * @abstract
  31646. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31647. * @return {Object|undefined} The direct light data (color and direction).
  31648. */
  31649. setupDirect( /*builder*/ ) { }
  31650. /**
  31651. * Sets up the direct rect area lighting for the analytic light node.
  31652. *
  31653. * @abstract
  31654. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31655. * @return {Object|undefined} The direct rect area light data.
  31656. */
  31657. setupDirectRectArea( /*builder*/ ) { }
  31658. /**
  31659. * Setups the shadow node for this light. The method exists so concrete light classes
  31660. * can setup different types of shadow nodes.
  31661. *
  31662. * @return {ShadowNode} The created shadow node.
  31663. */
  31664. setupShadowNode() {
  31665. return shadow( this.light );
  31666. }
  31667. /**
  31668. * Setups the shadow for this light. This method is only executed if the light
  31669. * cast shadows and the current build object receives shadows. It incorporates
  31670. * shadows into the lighting computation.
  31671. *
  31672. * @param {NodeBuilder} builder - The current node builder.
  31673. */
  31674. setupShadow( builder ) {
  31675. const { renderer } = builder;
  31676. if ( renderer.shadowMap.enabled === false ) return;
  31677. let shadowColorNode = this.shadowColorNode;
  31678. if ( shadowColorNode === null ) {
  31679. const customShadowNode = this.light.shadow.shadowNode;
  31680. let shadowNode;
  31681. if ( customShadowNode !== undefined ) {
  31682. shadowNode = nodeObject( customShadowNode );
  31683. } else {
  31684. shadowNode = this.setupShadowNode();
  31685. }
  31686. this.shadowNode = shadowNode;
  31687. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  31688. this.baseColorNode = this.colorNode;
  31689. }
  31690. //
  31691. if ( builder.context.getShadow ) {
  31692. shadowColorNode = builder.context.getShadow( this, builder );
  31693. }
  31694. this.colorNode = shadowColorNode;
  31695. }
  31696. /**
  31697. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  31698. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  31699. * invocate the respective interface methods.
  31700. *
  31701. * @param {NodeBuilder} builder - The current node builder.
  31702. */
  31703. setup( builder ) {
  31704. this.colorNode = this.baseColorNode || this.colorNode;
  31705. if ( this.light.castShadow ) {
  31706. if ( builder.object.receiveShadow ) {
  31707. this.setupShadow( builder );
  31708. }
  31709. } else if ( this.shadowNode !== null ) {
  31710. this.shadowNode.dispose();
  31711. this.shadowNode = null;
  31712. this.shadowColorNode = null;
  31713. }
  31714. const directLightData = this.setupDirect( builder );
  31715. const directRectAreaLightData = this.setupDirectRectArea( builder );
  31716. if ( directLightData ) {
  31717. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  31718. }
  31719. if ( directRectAreaLightData ) {
  31720. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  31721. }
  31722. }
  31723. /**
  31724. * The update method is used to update light uniforms per frame.
  31725. * Potentially overwritten in concrete light nodes to update light
  31726. * specific uniforms.
  31727. *
  31728. * @param {NodeFrame} frame - A reference to the current node frame.
  31729. */
  31730. update( /*frame*/ ) {
  31731. const { light } = this;
  31732. this.color.copy( light.color ).multiplyScalar( light.intensity );
  31733. }
  31734. }
  31735. /**
  31736. * Represents a `discard` shader operation in TSL.
  31737. *
  31738. * @method
  31739. * @param {Object} inputs - The input parameter object.
  31740. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  31741. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  31742. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  31743. * @return {Node<float>} The distance falloff.
  31744. */
  31745. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  31746. // based upon Frostbite 3 Moving to Physically-based Rendering
  31747. // page 32, equation 26: E[window1]
  31748. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  31749. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  31750. return cutoffDistance.greaterThan( 0 ).select(
  31751. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  31752. distanceFalloff
  31753. );
  31754. } ); // validated
  31755. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  31756. const lightDirection = lightVector.normalize();
  31757. const lightDistance = lightVector.length();
  31758. const attenuation = getDistanceAttenuation( {
  31759. lightDistance,
  31760. cutoffDistance,
  31761. decayExponent
  31762. } );
  31763. const lightColor = color.mul( attenuation );
  31764. return { lightDirection, lightColor };
  31765. };
  31766. /**
  31767. * Module for representing point lights as nodes.
  31768. *
  31769. * @augments AnalyticLightNode
  31770. */
  31771. class PointLightNode extends AnalyticLightNode {
  31772. static get type() {
  31773. return 'PointLightNode';
  31774. }
  31775. /**
  31776. * Constructs a new point light node.
  31777. *
  31778. * @param {?PointLight} [light=null] - The point light source.
  31779. */
  31780. constructor( light = null ) {
  31781. super( light );
  31782. /**
  31783. * Uniform node representing the cutoff distance.
  31784. *
  31785. * @type {UniformNode<float>}
  31786. */
  31787. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  31788. /**
  31789. * Uniform node representing the decay exponent.
  31790. *
  31791. * @type {UniformNode<float>}
  31792. */
  31793. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  31794. }
  31795. /**
  31796. * Overwritten to updated point light specific uniforms.
  31797. *
  31798. * @param {NodeFrame} frame - A reference to the current node frame.
  31799. */
  31800. update( frame ) {
  31801. const { light } = this;
  31802. super.update( frame );
  31803. this.cutoffDistanceNode.value = light.distance;
  31804. this.decayExponentNode.value = light.decay;
  31805. }
  31806. /**
  31807. * Overwritten to setup point light specific shadow.
  31808. *
  31809. * @return {PointShadowNode}
  31810. */
  31811. setupShadowNode() {
  31812. return pointShadow( this.light );
  31813. }
  31814. setupDirect( builder ) {
  31815. return directPointLight( {
  31816. color: this.colorNode,
  31817. lightVector: this.getLightVector( builder ),
  31818. cutoffDistance: this.cutoffDistanceNode,
  31819. decayExponent: this.decayExponentNode
  31820. } );
  31821. }
  31822. }
  31823. /**
  31824. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  31825. *
  31826. * @tsl
  31827. * @function
  31828. * @param {Node<vec2>} coord - The uv coordinates.
  31829. * @return {Node<float>} The result data.
  31830. */
  31831. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  31832. const uv = coord.mul( 2.0 );
  31833. const cx = uv.x.floor();
  31834. const cy = uv.y.floor();
  31835. const result = cx.add( cy ).mod( 2.0 );
  31836. return result.sign();
  31837. } );
  31838. /**
  31839. * Generates a circle based on the uv coordinates.
  31840. *
  31841. * @tsl
  31842. * @function
  31843. * @param {Node<vec2>} coord - The uv to generate the circle.
  31844. * @return {Node<float>} The circle shape.
  31845. */
  31846. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  31847. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  31848. let alpha;
  31849. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  31850. const dlen = float( len2.fwidth() ).toVar();
  31851. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  31852. } else {
  31853. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  31854. }
  31855. return alpha;
  31856. } );
  31857. // Three.js Transpiler
  31858. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  31859. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  31860. const f = float( f_immutable ).toVar();
  31861. const t = float( t_immutable ).toVar();
  31862. const b = bool( b_immutable ).toVar();
  31863. return select( b, t, f );
  31864. } ).setLayout( {
  31865. name: 'mx_select',
  31866. type: 'float',
  31867. inputs: [
  31868. { name: 'b', type: 'bool' },
  31869. { name: 't', type: 'float' },
  31870. { name: 'f', type: 'float' }
  31871. ]
  31872. } );
  31873. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  31874. const b = bool( b_immutable ).toVar();
  31875. const val = float( val_immutable ).toVar();
  31876. return select( b, val.negate(), val );
  31877. } ).setLayout( {
  31878. name: 'mx_negate_if',
  31879. type: 'float',
  31880. inputs: [
  31881. { name: 'val', type: 'float' },
  31882. { name: 'b', type: 'bool' }
  31883. ]
  31884. } );
  31885. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  31886. const x = float( x_immutable ).toVar();
  31887. return int( floor( x ) );
  31888. } ).setLayout( {
  31889. name: 'mx_floor',
  31890. type: 'int',
  31891. inputs: [
  31892. { name: 'x', type: 'float' }
  31893. ]
  31894. } );
  31895. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  31896. const x = float( x_immutable ).toVar();
  31897. i.assign( mx_floor( x ) );
  31898. return x.sub( float( i ) );
  31899. } );
  31900. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  31901. const t = float( t_immutable ).toVar();
  31902. const s = float( s_immutable ).toVar();
  31903. const v3 = float( v3_immutable ).toVar();
  31904. const v2 = float( v2_immutable ).toVar();
  31905. const v1 = float( v1_immutable ).toVar();
  31906. const v0 = float( v0_immutable ).toVar();
  31907. const s1 = float( sub( 1.0, s ) ).toVar();
  31908. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  31909. } ).setLayout( {
  31910. name: 'mx_bilerp_0',
  31911. type: 'float',
  31912. inputs: [
  31913. { name: 'v0', type: 'float' },
  31914. { name: 'v1', type: 'float' },
  31915. { name: 'v2', type: 'float' },
  31916. { name: 'v3', type: 'float' },
  31917. { name: 's', type: 'float' },
  31918. { name: 't', type: 'float' }
  31919. ]
  31920. } );
  31921. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  31922. const t = float( t_immutable ).toVar();
  31923. const s = float( s_immutable ).toVar();
  31924. const v3 = vec3( v3_immutable ).toVar();
  31925. const v2 = vec3( v2_immutable ).toVar();
  31926. const v1 = vec3( v1_immutable ).toVar();
  31927. const v0 = vec3( v0_immutable ).toVar();
  31928. const s1 = float( sub( 1.0, s ) ).toVar();
  31929. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  31930. } ).setLayout( {
  31931. name: 'mx_bilerp_1',
  31932. type: 'vec3',
  31933. inputs: [
  31934. { name: 'v0', type: 'vec3' },
  31935. { name: 'v1', type: 'vec3' },
  31936. { name: 'v2', type: 'vec3' },
  31937. { name: 'v3', type: 'vec3' },
  31938. { name: 's', type: 'float' },
  31939. { name: 't', type: 'float' }
  31940. ]
  31941. } );
  31942. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  31943. 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 ] ) => {
  31944. const r = float( r_immutable ).toVar();
  31945. const t = float( t_immutable ).toVar();
  31946. const s = float( s_immutable ).toVar();
  31947. const v7 = float( v7_immutable ).toVar();
  31948. const v6 = float( v6_immutable ).toVar();
  31949. const v5 = float( v5_immutable ).toVar();
  31950. const v4 = float( v4_immutable ).toVar();
  31951. const v3 = float( v3_immutable ).toVar();
  31952. const v2 = float( v2_immutable ).toVar();
  31953. const v1 = float( v1_immutable ).toVar();
  31954. const v0 = float( v0_immutable ).toVar();
  31955. const s1 = float( sub( 1.0, s ) ).toVar();
  31956. const t1 = float( sub( 1.0, t ) ).toVar();
  31957. const r1 = float( sub( 1.0, r ) ).toVar();
  31958. 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 ) ) ) ) ) );
  31959. } ).setLayout( {
  31960. name: 'mx_trilerp_0',
  31961. type: 'float',
  31962. inputs: [
  31963. { name: 'v0', type: 'float' },
  31964. { name: 'v1', type: 'float' },
  31965. { name: 'v2', type: 'float' },
  31966. { name: 'v3', type: 'float' },
  31967. { name: 'v4', type: 'float' },
  31968. { name: 'v5', type: 'float' },
  31969. { name: 'v6', type: 'float' },
  31970. { name: 'v7', type: 'float' },
  31971. { name: 's', type: 'float' },
  31972. { name: 't', type: 'float' },
  31973. { name: 'r', type: 'float' }
  31974. ]
  31975. } );
  31976. 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 ] ) => {
  31977. const r = float( r_immutable ).toVar();
  31978. const t = float( t_immutable ).toVar();
  31979. const s = float( s_immutable ).toVar();
  31980. const v7 = vec3( v7_immutable ).toVar();
  31981. const v6 = vec3( v6_immutable ).toVar();
  31982. const v5 = vec3( v5_immutable ).toVar();
  31983. const v4 = vec3( v4_immutable ).toVar();
  31984. const v3 = vec3( v3_immutable ).toVar();
  31985. const v2 = vec3( v2_immutable ).toVar();
  31986. const v1 = vec3( v1_immutable ).toVar();
  31987. const v0 = vec3( v0_immutable ).toVar();
  31988. const s1 = float( sub( 1.0, s ) ).toVar();
  31989. const t1 = float( sub( 1.0, t ) ).toVar();
  31990. const r1 = float( sub( 1.0, r ) ).toVar();
  31991. 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 ) ) ) ) ) );
  31992. } ).setLayout( {
  31993. name: 'mx_trilerp_1',
  31994. type: 'vec3',
  31995. inputs: [
  31996. { name: 'v0', type: 'vec3' },
  31997. { name: 'v1', type: 'vec3' },
  31998. { name: 'v2', type: 'vec3' },
  31999. { name: 'v3', type: 'vec3' },
  32000. { name: 'v4', type: 'vec3' },
  32001. { name: 'v5', type: 'vec3' },
  32002. { name: 'v6', type: 'vec3' },
  32003. { name: 'v7', type: 'vec3' },
  32004. { name: 's', type: 'float' },
  32005. { name: 't', type: 'float' },
  32006. { name: 'r', type: 'float' }
  32007. ]
  32008. } );
  32009. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  32010. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32011. const y = float( y_immutable ).toVar();
  32012. const x = float( x_immutable ).toVar();
  32013. const hash = uint( hash_immutable ).toVar();
  32014. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  32015. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  32016. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  32017. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32018. } ).setLayout( {
  32019. name: 'mx_gradient_float_0',
  32020. type: 'float',
  32021. inputs: [
  32022. { name: 'hash', type: 'uint' },
  32023. { name: 'x', type: 'float' },
  32024. { name: 'y', type: 'float' }
  32025. ]
  32026. } );
  32027. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32028. const z = float( z_immutable ).toVar();
  32029. const y = float( y_immutable ).toVar();
  32030. const x = float( x_immutable ).toVar();
  32031. const hash = uint( hash_immutable ).toVar();
  32032. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  32033. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  32034. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  32035. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32036. } ).setLayout( {
  32037. name: 'mx_gradient_float_1',
  32038. type: 'float',
  32039. inputs: [
  32040. { name: 'hash', type: 'uint' },
  32041. { name: 'x', type: 'float' },
  32042. { name: 'y', type: 'float' },
  32043. { name: 'z', type: 'float' }
  32044. ]
  32045. } );
  32046. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  32047. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32048. const y = float( y_immutable ).toVar();
  32049. const x = float( x_immutable ).toVar();
  32050. const hash = uvec3( hash_immutable ).toVar();
  32051. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  32052. } ).setLayout( {
  32053. name: 'mx_gradient_vec3_0',
  32054. type: 'vec3',
  32055. inputs: [
  32056. { name: 'hash', type: 'uvec3' },
  32057. { name: 'x', type: 'float' },
  32058. { name: 'y', type: 'float' }
  32059. ]
  32060. } );
  32061. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32062. const z = float( z_immutable ).toVar();
  32063. const y = float( y_immutable ).toVar();
  32064. const x = float( x_immutable ).toVar();
  32065. const hash = uvec3( hash_immutable ).toVar();
  32066. 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 ) );
  32067. } ).setLayout( {
  32068. name: 'mx_gradient_vec3_1',
  32069. type: 'vec3',
  32070. inputs: [
  32071. { name: 'hash', type: 'uvec3' },
  32072. { name: 'x', type: 'float' },
  32073. { name: 'y', type: 'float' },
  32074. { name: 'z', type: 'float' }
  32075. ]
  32076. } );
  32077. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  32078. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32079. const v = float( v_immutable ).toVar();
  32080. return mul( 0.6616, v );
  32081. } ).setLayout( {
  32082. name: 'mx_gradient_scale2d_0',
  32083. type: 'float',
  32084. inputs: [
  32085. { name: 'v', type: 'float' }
  32086. ]
  32087. } );
  32088. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32089. const v = float( v_immutable ).toVar();
  32090. return mul( 0.9820, v );
  32091. } ).setLayout( {
  32092. name: 'mx_gradient_scale3d_0',
  32093. type: 'float',
  32094. inputs: [
  32095. { name: 'v', type: 'float' }
  32096. ]
  32097. } );
  32098. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32099. const v = vec3( v_immutable ).toVar();
  32100. return mul( 0.6616, v );
  32101. } ).setLayout( {
  32102. name: 'mx_gradient_scale2d_1',
  32103. type: 'vec3',
  32104. inputs: [
  32105. { name: 'v', type: 'vec3' }
  32106. ]
  32107. } );
  32108. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  32109. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32110. const v = vec3( v_immutable ).toVar();
  32111. return mul( 0.9820, v );
  32112. } ).setLayout( {
  32113. name: 'mx_gradient_scale3d_1',
  32114. type: 'vec3',
  32115. inputs: [
  32116. { name: 'v', type: 'vec3' }
  32117. ]
  32118. } );
  32119. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  32120. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  32121. const k = int( k_immutable ).toVar();
  32122. const x = uint( x_immutable ).toVar();
  32123. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  32124. } ).setLayout( {
  32125. name: 'mx_rotl32',
  32126. type: 'uint',
  32127. inputs: [
  32128. { name: 'x', type: 'uint' },
  32129. { name: 'k', type: 'int' }
  32130. ]
  32131. } );
  32132. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  32133. a.subAssign( c );
  32134. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  32135. c.addAssign( b );
  32136. b.subAssign( a );
  32137. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  32138. a.addAssign( c );
  32139. c.subAssign( b );
  32140. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  32141. b.addAssign( a );
  32142. a.subAssign( c );
  32143. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  32144. c.addAssign( b );
  32145. b.subAssign( a );
  32146. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  32147. a.addAssign( c );
  32148. c.subAssign( b );
  32149. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  32150. b.addAssign( a );
  32151. } );
  32152. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  32153. const c = uint( c_immutable ).toVar();
  32154. const b = uint( b_immutable ).toVar();
  32155. const a = uint( a_immutable ).toVar();
  32156. c.bitXorAssign( b );
  32157. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  32158. a.bitXorAssign( c );
  32159. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  32160. b.bitXorAssign( a );
  32161. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  32162. c.bitXorAssign( b );
  32163. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  32164. a.bitXorAssign( c );
  32165. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  32166. b.bitXorAssign( a );
  32167. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  32168. c.bitXorAssign( b );
  32169. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  32170. return c;
  32171. } ).setLayout( {
  32172. name: 'mx_bjfinal',
  32173. type: 'uint',
  32174. inputs: [
  32175. { name: 'a', type: 'uint' },
  32176. { name: 'b', type: 'uint' },
  32177. { name: 'c', type: 'uint' }
  32178. ]
  32179. } );
  32180. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  32181. const bits = uint( bits_immutable ).toVar();
  32182. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  32183. } ).setLayout( {
  32184. name: 'mx_bits_to_01',
  32185. type: 'float',
  32186. inputs: [
  32187. { name: 'bits', type: 'uint' }
  32188. ]
  32189. } );
  32190. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  32191. const t = float( t_immutable ).toVar();
  32192. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  32193. } ).setLayout( {
  32194. name: 'mx_fade',
  32195. type: 'float',
  32196. inputs: [
  32197. { name: 't', type: 'float' }
  32198. ]
  32199. } );
  32200. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32201. const x = int( x_immutable ).toVar();
  32202. const len = uint( uint( 1 ) ).toVar();
  32203. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  32204. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  32205. } ).setLayout( {
  32206. name: 'mx_hash_int_0',
  32207. type: 'uint',
  32208. inputs: [
  32209. { name: 'x', type: 'int' }
  32210. ]
  32211. } );
  32212. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32213. const y = int( y_immutable ).toVar();
  32214. const x = int( x_immutable ).toVar();
  32215. const len = uint( uint( 2 ) ).toVar();
  32216. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32217. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32218. a.addAssign( uint( x ) );
  32219. b.addAssign( uint( y ) );
  32220. return mx_bjfinal( a, b, c );
  32221. } ).setLayout( {
  32222. name: 'mx_hash_int_1',
  32223. type: 'uint',
  32224. inputs: [
  32225. { name: 'x', type: 'int' },
  32226. { name: 'y', type: 'int' }
  32227. ]
  32228. } );
  32229. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32230. const z = int( z_immutable ).toVar();
  32231. const y = int( y_immutable ).toVar();
  32232. const x = int( x_immutable ).toVar();
  32233. const len = uint( uint( 3 ) ).toVar();
  32234. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32235. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32236. a.addAssign( uint( x ) );
  32237. b.addAssign( uint( y ) );
  32238. c.addAssign( uint( z ) );
  32239. return mx_bjfinal( a, b, c );
  32240. } ).setLayout( {
  32241. name: 'mx_hash_int_2',
  32242. type: 'uint',
  32243. inputs: [
  32244. { name: 'x', type: 'int' },
  32245. { name: 'y', type: 'int' },
  32246. { name: 'z', type: 'int' }
  32247. ]
  32248. } );
  32249. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  32250. const xx = int( xx_immutable ).toVar();
  32251. const z = int( z_immutable ).toVar();
  32252. const y = int( y_immutable ).toVar();
  32253. const x = int( x_immutable ).toVar();
  32254. const len = uint( uint( 4 ) ).toVar();
  32255. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32256. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32257. a.addAssign( uint( x ) );
  32258. b.addAssign( uint( y ) );
  32259. c.addAssign( uint( z ) );
  32260. mx_bjmix( a, b, c );
  32261. a.addAssign( uint( xx ) );
  32262. return mx_bjfinal( a, b, c );
  32263. } ).setLayout( {
  32264. name: 'mx_hash_int_3',
  32265. type: 'uint',
  32266. inputs: [
  32267. { name: 'x', type: 'int' },
  32268. { name: 'y', type: 'int' },
  32269. { name: 'z', type: 'int' },
  32270. { name: 'xx', type: 'int' }
  32271. ]
  32272. } );
  32273. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  32274. const yy = int( yy_immutable ).toVar();
  32275. const xx = int( xx_immutable ).toVar();
  32276. const z = int( z_immutable ).toVar();
  32277. const y = int( y_immutable ).toVar();
  32278. const x = int( x_immutable ).toVar();
  32279. const len = uint( uint( 5 ) ).toVar();
  32280. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32281. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32282. a.addAssign( uint( x ) );
  32283. b.addAssign( uint( y ) );
  32284. c.addAssign( uint( z ) );
  32285. mx_bjmix( a, b, c );
  32286. a.addAssign( uint( xx ) );
  32287. b.addAssign( uint( yy ) );
  32288. return mx_bjfinal( a, b, c );
  32289. } ).setLayout( {
  32290. name: 'mx_hash_int_4',
  32291. type: 'uint',
  32292. inputs: [
  32293. { name: 'x', type: 'int' },
  32294. { name: 'y', type: 'int' },
  32295. { name: 'z', type: 'int' },
  32296. { name: 'xx', type: 'int' },
  32297. { name: 'yy', type: 'int' }
  32298. ]
  32299. } );
  32300. 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 ] );
  32301. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32302. const y = int( y_immutable ).toVar();
  32303. const x = int( x_immutable ).toVar();
  32304. const h = uint( mx_hash_int( x, y ) ).toVar();
  32305. const result = uvec3().toVar();
  32306. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32307. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32308. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32309. return result;
  32310. } ).setLayout( {
  32311. name: 'mx_hash_vec3_0',
  32312. type: 'uvec3',
  32313. inputs: [
  32314. { name: 'x', type: 'int' },
  32315. { name: 'y', type: 'int' }
  32316. ]
  32317. } );
  32318. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32319. const z = int( z_immutable ).toVar();
  32320. const y = int( y_immutable ).toVar();
  32321. const x = int( x_immutable ).toVar();
  32322. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  32323. const result = uvec3().toVar();
  32324. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32325. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32326. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32327. return result;
  32328. } ).setLayout( {
  32329. name: 'mx_hash_vec3_1',
  32330. type: 'uvec3',
  32331. inputs: [
  32332. { name: 'x', type: 'int' },
  32333. { name: 'y', type: 'int' },
  32334. { name: 'z', type: 'int' }
  32335. ]
  32336. } );
  32337. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  32338. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32339. const p = vec2( p_immutable ).toVar();
  32340. const X = int().toVar(), Y = int().toVar();
  32341. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32342. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32343. const u = float( mx_fade( fx ) ).toVar();
  32344. const v = float( mx_fade( fy ) ).toVar();
  32345. 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();
  32346. return mx_gradient_scale2d( result );
  32347. } ).setLayout( {
  32348. name: 'mx_perlin_noise_float_0',
  32349. type: 'float',
  32350. inputs: [
  32351. { name: 'p', type: 'vec2' }
  32352. ]
  32353. } );
  32354. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32355. const p = vec3( p_immutable ).toVar();
  32356. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32357. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32358. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32359. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32360. const u = float( mx_fade( fx ) ).toVar();
  32361. const v = float( mx_fade( fy ) ).toVar();
  32362. const w = float( mx_fade( fz ) ).toVar();
  32363. 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();
  32364. return mx_gradient_scale3d( result );
  32365. } ).setLayout( {
  32366. name: 'mx_perlin_noise_float_1',
  32367. type: 'float',
  32368. inputs: [
  32369. { name: 'p', type: 'vec3' }
  32370. ]
  32371. } );
  32372. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  32373. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32374. const p = vec2( p_immutable ).toVar();
  32375. const X = int().toVar(), Y = int().toVar();
  32376. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32377. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32378. const u = float( mx_fade( fx ) ).toVar();
  32379. const v = float( mx_fade( fy ) ).toVar();
  32380. 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();
  32381. return mx_gradient_scale2d( result );
  32382. } ).setLayout( {
  32383. name: 'mx_perlin_noise_vec3_0',
  32384. type: 'vec3',
  32385. inputs: [
  32386. { name: 'p', type: 'vec2' }
  32387. ]
  32388. } );
  32389. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32390. const p = vec3( p_immutable ).toVar();
  32391. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32392. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32393. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32394. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32395. const u = float( mx_fade( fx ) ).toVar();
  32396. const v = float( mx_fade( fy ) ).toVar();
  32397. const w = float( mx_fade( fz ) ).toVar();
  32398. 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();
  32399. return mx_gradient_scale3d( result );
  32400. } ).setLayout( {
  32401. name: 'mx_perlin_noise_vec3_1',
  32402. type: 'vec3',
  32403. inputs: [
  32404. { name: 'p', type: 'vec3' }
  32405. ]
  32406. } );
  32407. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  32408. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32409. const p = float( p_immutable ).toVar();
  32410. const ix = int( mx_floor( p ) ).toVar();
  32411. return mx_bits_to_01( mx_hash_int( ix ) );
  32412. } ).setLayout( {
  32413. name: 'mx_cell_noise_float_0',
  32414. type: 'float',
  32415. inputs: [
  32416. { name: 'p', type: 'float' }
  32417. ]
  32418. } );
  32419. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32420. const p = vec2( p_immutable ).toVar();
  32421. const ix = int( mx_floor( p.x ) ).toVar();
  32422. const iy = int( mx_floor( p.y ) ).toVar();
  32423. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  32424. } ).setLayout( {
  32425. name: 'mx_cell_noise_float_1',
  32426. type: 'float',
  32427. inputs: [
  32428. { name: 'p', type: 'vec2' }
  32429. ]
  32430. } );
  32431. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32432. const p = vec3( p_immutable ).toVar();
  32433. const ix = int( mx_floor( p.x ) ).toVar();
  32434. const iy = int( mx_floor( p.y ) ).toVar();
  32435. const iz = int( mx_floor( p.z ) ).toVar();
  32436. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  32437. } ).setLayout( {
  32438. name: 'mx_cell_noise_float_2',
  32439. type: 'float',
  32440. inputs: [
  32441. { name: 'p', type: 'vec3' }
  32442. ]
  32443. } );
  32444. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32445. const p = vec4( p_immutable ).toVar();
  32446. const ix = int( mx_floor( p.x ) ).toVar();
  32447. const iy = int( mx_floor( p.y ) ).toVar();
  32448. const iz = int( mx_floor( p.z ) ).toVar();
  32449. const iw = int( mx_floor( p.w ) ).toVar();
  32450. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  32451. } ).setLayout( {
  32452. name: 'mx_cell_noise_float_3',
  32453. type: 'float',
  32454. inputs: [
  32455. { name: 'p', type: 'vec4' }
  32456. ]
  32457. } );
  32458. 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 ] );
  32459. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32460. const p = float( p_immutable ).toVar();
  32461. const ix = int( mx_floor( p ) ).toVar();
  32462. 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 ) ) ) );
  32463. } ).setLayout( {
  32464. name: 'mx_cell_noise_vec3_0',
  32465. type: 'vec3',
  32466. inputs: [
  32467. { name: 'p', type: 'float' }
  32468. ]
  32469. } );
  32470. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32471. const p = vec2( p_immutable ).toVar();
  32472. const ix = int( mx_floor( p.x ) ).toVar();
  32473. const iy = int( mx_floor( p.y ) ).toVar();
  32474. 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 ) ) ) );
  32475. } ).setLayout( {
  32476. name: 'mx_cell_noise_vec3_1',
  32477. type: 'vec3',
  32478. inputs: [
  32479. { name: 'p', type: 'vec2' }
  32480. ]
  32481. } );
  32482. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32483. const p = vec3( p_immutable ).toVar();
  32484. const ix = int( mx_floor( p.x ) ).toVar();
  32485. const iy = int( mx_floor( p.y ) ).toVar();
  32486. const iz = int( mx_floor( p.z ) ).toVar();
  32487. 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 ) ) ) );
  32488. } ).setLayout( {
  32489. name: 'mx_cell_noise_vec3_2',
  32490. type: 'vec3',
  32491. inputs: [
  32492. { name: 'p', type: 'vec3' }
  32493. ]
  32494. } );
  32495. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32496. const p = vec4( p_immutable ).toVar();
  32497. const ix = int( mx_floor( p.x ) ).toVar();
  32498. const iy = int( mx_floor( p.y ) ).toVar();
  32499. const iz = int( mx_floor( p.z ) ).toVar();
  32500. const iw = int( mx_floor( p.w ) ).toVar();
  32501. 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 ) ) ) );
  32502. } ).setLayout( {
  32503. name: 'mx_cell_noise_vec3_3',
  32504. type: 'vec3',
  32505. inputs: [
  32506. { name: 'p', type: 'vec4' }
  32507. ]
  32508. } );
  32509. 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 ] );
  32510. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32511. const diminish = float( diminish_immutable ).toVar();
  32512. const lacunarity = float( lacunarity_immutable ).toVar();
  32513. const octaves = int( octaves_immutable ).toVar();
  32514. const p = vec3( p_immutable ).toVar();
  32515. const result = float( 0.0 ).toVar();
  32516. const amplitude = float( 1.0 ).toVar();
  32517. Loop( octaves, () => {
  32518. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  32519. amplitude.mulAssign( diminish );
  32520. p.mulAssign( lacunarity );
  32521. } );
  32522. return result;
  32523. } ).setLayout( {
  32524. name: 'mx_fractal_noise_float',
  32525. type: 'float',
  32526. inputs: [
  32527. { name: 'p', type: 'vec3' },
  32528. { name: 'octaves', type: 'int' },
  32529. { name: 'lacunarity', type: 'float' },
  32530. { name: 'diminish', type: 'float' }
  32531. ]
  32532. } );
  32533. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32534. const diminish = float( diminish_immutable ).toVar();
  32535. const lacunarity = float( lacunarity_immutable ).toVar();
  32536. const octaves = int( octaves_immutable ).toVar();
  32537. const p = vec3( p_immutable ).toVar();
  32538. const result = vec3( 0.0 ).toVar();
  32539. const amplitude = float( 1.0 ).toVar();
  32540. Loop( octaves, () => {
  32541. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  32542. amplitude.mulAssign( diminish );
  32543. p.mulAssign( lacunarity );
  32544. } );
  32545. return result;
  32546. } ).setLayout( {
  32547. name: 'mx_fractal_noise_vec3',
  32548. type: 'vec3',
  32549. inputs: [
  32550. { name: 'p', type: 'vec3' },
  32551. { name: 'octaves', type: 'int' },
  32552. { name: 'lacunarity', type: 'float' },
  32553. { name: 'diminish', type: 'float' }
  32554. ]
  32555. } );
  32556. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32557. const diminish = float( diminish_immutable ).toVar();
  32558. const lacunarity = float( lacunarity_immutable ).toVar();
  32559. const octaves = int( octaves_immutable ).toVar();
  32560. const p = vec3( p_immutable ).toVar();
  32561. 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 ) );
  32562. } ).setLayout( {
  32563. name: 'mx_fractal_noise_vec2',
  32564. type: 'vec2',
  32565. inputs: [
  32566. { name: 'p', type: 'vec3' },
  32567. { name: 'octaves', type: 'int' },
  32568. { name: 'lacunarity', type: 'float' },
  32569. { name: 'diminish', type: 'float' }
  32570. ]
  32571. } );
  32572. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32573. const diminish = float( diminish_immutable ).toVar();
  32574. const lacunarity = float( lacunarity_immutable ).toVar();
  32575. const octaves = int( octaves_immutable ).toVar();
  32576. const p = vec3( p_immutable ).toVar();
  32577. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  32578. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  32579. return vec4( c, f );
  32580. } ).setLayout( {
  32581. name: 'mx_fractal_noise_vec4',
  32582. type: 'vec4',
  32583. inputs: [
  32584. { name: 'p', type: 'vec3' },
  32585. { name: 'octaves', type: 'int' },
  32586. { name: 'lacunarity', type: 'float' },
  32587. { name: 'diminish', type: 'float' }
  32588. ]
  32589. } );
  32590. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  32591. const metric = int( metric_immutable ).toVar();
  32592. const jitter = float( jitter_immutable ).toVar();
  32593. const yoff = int( yoff_immutable ).toVar();
  32594. const xoff = int( xoff_immutable ).toVar();
  32595. const y = int( y_immutable ).toVar();
  32596. const x = int( x_immutable ).toVar();
  32597. const p = vec2( p_immutable ).toVar();
  32598. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  32599. const off = vec2( tmp.x, tmp.y ).toVar();
  32600. off.subAssign( 0.5 );
  32601. off.mulAssign( jitter );
  32602. off.addAssign( 0.5 );
  32603. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  32604. const diff = vec2( cellpos.sub( p ) ).toVar();
  32605. If( metric.equal( int( 2 ) ), () => {
  32606. return abs( diff.x ).add( abs( diff.y ) );
  32607. } );
  32608. If( metric.equal( int( 3 ) ), () => {
  32609. return max$1( abs( diff.x ), abs( diff.y ) );
  32610. } );
  32611. return dot( diff, diff );
  32612. } ).setLayout( {
  32613. name: 'mx_worley_distance_0',
  32614. type: 'float',
  32615. inputs: [
  32616. { name: 'p', type: 'vec2' },
  32617. { name: 'x', type: 'int' },
  32618. { name: 'y', type: 'int' },
  32619. { name: 'xoff', type: 'int' },
  32620. { name: 'yoff', type: 'int' },
  32621. { name: 'jitter', type: 'float' },
  32622. { name: 'metric', type: 'int' }
  32623. ]
  32624. } );
  32625. 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 ] ) => {
  32626. const metric = int( metric_immutable ).toVar();
  32627. const jitter = float( jitter_immutable ).toVar();
  32628. const zoff = int( zoff_immutable ).toVar();
  32629. const yoff = int( yoff_immutable ).toVar();
  32630. const xoff = int( xoff_immutable ).toVar();
  32631. const z = int( z_immutable ).toVar();
  32632. const y = int( y_immutable ).toVar();
  32633. const x = int( x_immutable ).toVar();
  32634. const p = vec3( p_immutable ).toVar();
  32635. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  32636. off.subAssign( 0.5 );
  32637. off.mulAssign( jitter );
  32638. off.addAssign( 0.5 );
  32639. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  32640. const diff = vec3( cellpos.sub( p ) ).toVar();
  32641. If( metric.equal( int( 2 ) ), () => {
  32642. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  32643. } );
  32644. If( metric.equal( int( 3 ) ), () => {
  32645. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  32646. } );
  32647. return dot( diff, diff );
  32648. } ).setLayout( {
  32649. name: 'mx_worley_distance_1',
  32650. type: 'float',
  32651. inputs: [
  32652. { name: 'p', type: 'vec3' },
  32653. { name: 'x', type: 'int' },
  32654. { name: 'y', type: 'int' },
  32655. { name: 'z', type: 'int' },
  32656. { name: 'xoff', type: 'int' },
  32657. { name: 'yoff', type: 'int' },
  32658. { name: 'zoff', type: 'int' },
  32659. { name: 'jitter', type: 'float' },
  32660. { name: 'metric', type: 'int' }
  32661. ]
  32662. } );
  32663. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  32664. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32665. const metric = int( metric_immutable ).toVar();
  32666. const jitter = float( jitter_immutable ).toVar();
  32667. const p = vec2( p_immutable ).toVar();
  32668. const X = int().toVar(), Y = int().toVar();
  32669. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32670. const sqdist = float( 1e6 ).toVar();
  32671. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32672. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32673. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32674. sqdist.assign( min$1( sqdist, dist ) );
  32675. } );
  32676. } );
  32677. If( metric.equal( int( 0 ) ), () => {
  32678. sqdist.assign( sqrt( sqdist ) );
  32679. } );
  32680. return sqdist;
  32681. } ).setLayout( {
  32682. name: 'mx_worley_noise_float_0',
  32683. type: 'float',
  32684. inputs: [
  32685. { name: 'p', type: 'vec2' },
  32686. { name: 'jitter', type: 'float' },
  32687. { name: 'metric', type: 'int' }
  32688. ]
  32689. } );
  32690. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32691. const metric = int( metric_immutable ).toVar();
  32692. const jitter = float( jitter_immutable ).toVar();
  32693. const p = vec2( p_immutable ).toVar();
  32694. const X = int().toVar(), Y = int().toVar();
  32695. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32696. const sqdist = vec2( 1e6, 1e6 ).toVar();
  32697. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32698. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32699. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32700. If( dist.lessThan( sqdist.x ), () => {
  32701. sqdist.y.assign( sqdist.x );
  32702. sqdist.x.assign( dist );
  32703. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32704. sqdist.y.assign( dist );
  32705. } );
  32706. } );
  32707. } );
  32708. If( metric.equal( int( 0 ) ), () => {
  32709. sqdist.assign( sqrt( sqdist ) );
  32710. } );
  32711. return sqdist;
  32712. } ).setLayout( {
  32713. name: 'mx_worley_noise_vec2_0',
  32714. type: 'vec2',
  32715. inputs: [
  32716. { name: 'p', type: 'vec2' },
  32717. { name: 'jitter', type: 'float' },
  32718. { name: 'metric', type: 'int' }
  32719. ]
  32720. } );
  32721. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32722. const metric = int( metric_immutable ).toVar();
  32723. const jitter = float( jitter_immutable ).toVar();
  32724. const p = vec2( p_immutable ).toVar();
  32725. const X = int().toVar(), Y = int().toVar();
  32726. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32727. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  32728. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32729. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32730. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32731. If( dist.lessThan( sqdist.x ), () => {
  32732. sqdist.z.assign( sqdist.y );
  32733. sqdist.y.assign( sqdist.x );
  32734. sqdist.x.assign( dist );
  32735. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32736. sqdist.z.assign( sqdist.y );
  32737. sqdist.y.assign( dist );
  32738. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  32739. sqdist.z.assign( dist );
  32740. } );
  32741. } );
  32742. } );
  32743. If( metric.equal( int( 0 ) ), () => {
  32744. sqdist.assign( sqrt( sqdist ) );
  32745. } );
  32746. return sqdist;
  32747. } ).setLayout( {
  32748. name: 'mx_worley_noise_vec3_0',
  32749. type: 'vec3',
  32750. inputs: [
  32751. { name: 'p', type: 'vec2' },
  32752. { name: 'jitter', type: 'float' },
  32753. { name: 'metric', type: 'int' }
  32754. ]
  32755. } );
  32756. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32757. const metric = int( metric_immutable ).toVar();
  32758. const jitter = float( jitter_immutable ).toVar();
  32759. const p = vec3( p_immutable ).toVar();
  32760. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32761. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  32762. const sqdist = float( 1e6 ).toVar();
  32763. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32764. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32765. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  32766. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  32767. sqdist.assign( min$1( sqdist, dist ) );
  32768. } );
  32769. } );
  32770. } );
  32771. If( metric.equal( int( 0 ) ), () => {
  32772. sqdist.assign( sqrt( sqdist ) );
  32773. } );
  32774. return sqdist;
  32775. } ).setLayout( {
  32776. name: 'mx_worley_noise_float_1',
  32777. type: 'float',
  32778. inputs: [
  32779. { name: 'p', type: 'vec3' },
  32780. { name: 'jitter', type: 'float' },
  32781. { name: 'metric', type: 'int' }
  32782. ]
  32783. } );
  32784. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  32785. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32786. const metric = int( metric_immutable ).toVar();
  32787. const jitter = float( jitter_immutable ).toVar();
  32788. const p = vec3( p_immutable ).toVar();
  32789. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32790. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  32791. const sqdist = vec2( 1e6, 1e6 ).toVar();
  32792. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32793. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32794. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  32795. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  32796. If( dist.lessThan( sqdist.x ), () => {
  32797. sqdist.y.assign( sqdist.x );
  32798. sqdist.x.assign( dist );
  32799. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32800. sqdist.y.assign( dist );
  32801. } );
  32802. } );
  32803. } );
  32804. } );
  32805. If( metric.equal( int( 0 ) ), () => {
  32806. sqdist.assign( sqrt( sqdist ) );
  32807. } );
  32808. return sqdist;
  32809. } ).setLayout( {
  32810. name: 'mx_worley_noise_vec2_1',
  32811. type: 'vec2',
  32812. inputs: [
  32813. { name: 'p', type: 'vec3' },
  32814. { name: 'jitter', type: 'float' },
  32815. { name: 'metric', type: 'int' }
  32816. ]
  32817. } );
  32818. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  32819. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32820. const metric = int( metric_immutable ).toVar();
  32821. const jitter = float( jitter_immutable ).toVar();
  32822. const p = vec3( p_immutable ).toVar();
  32823. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32824. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  32825. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  32826. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32827. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32828. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  32829. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  32830. If( dist.lessThan( sqdist.x ), () => {
  32831. sqdist.z.assign( sqdist.y );
  32832. sqdist.y.assign( sqdist.x );
  32833. sqdist.x.assign( dist );
  32834. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32835. sqdist.z.assign( sqdist.y );
  32836. sqdist.y.assign( dist );
  32837. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  32838. sqdist.z.assign( dist );
  32839. } );
  32840. } );
  32841. } );
  32842. } );
  32843. If( metric.equal( int( 0 ) ), () => {
  32844. sqdist.assign( sqrt( sqdist ) );
  32845. } );
  32846. return sqdist;
  32847. } ).setLayout( {
  32848. name: 'mx_worley_noise_vec3_1',
  32849. type: 'vec3',
  32850. inputs: [
  32851. { name: 'p', type: 'vec3' },
  32852. { name: 'jitter', type: 'float' },
  32853. { name: 'metric', type: 'int' }
  32854. ]
  32855. } );
  32856. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  32857. // Unified Noise 2D
  32858. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  32859. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  32860. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  32861. octaves_immutable, lacunarity_immutable, diminish_immutable
  32862. ] ) => {
  32863. const noiseType = int( noiseType_immutable ).toVar();
  32864. const texcoord = vec2( texcoord_immutable ).toVar();
  32865. const freq = vec2( freq_immutable ).toVar();
  32866. const offset = vec2( offset_immutable ).toVar();
  32867. const jitter = float( jitter_immutable ).toVar();
  32868. const outmin = float( outmin_immutable ).toVar();
  32869. const outmax = float( outmax_immutable ).toVar();
  32870. const clampoutput = bool( clampoutput_immutable ).toVar();
  32871. const octaves = int( octaves_immutable ).toVar();
  32872. const lacunarity = float( lacunarity_immutable ).toVar();
  32873. const diminish = float( diminish_immutable ).toVar();
  32874. // Compute input position
  32875. const p = texcoord.mul( freq ).add( offset );
  32876. const result = float( 0.0 ).toVar();
  32877. // Perlin
  32878. If( noiseType.equal( int( 0 ) ), () => {
  32879. result.assign( mx_perlin_noise_vec3( p ) );
  32880. } );
  32881. // Cell
  32882. If( noiseType.equal( int( 1 ) ), () => {
  32883. result.assign( mx_cell_noise_vec3( p ) );
  32884. } );
  32885. // Worley (metric=0 = euclidean)
  32886. If( noiseType.equal( int( 2 ) ), () => {
  32887. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  32888. } );
  32889. // Fractal (use vec3(p, 0.0) for 2D input)
  32890. If( noiseType.equal( int( 3 ) ), () => {
  32891. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  32892. } );
  32893. // Remap output to [outmin, outmax]
  32894. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  32895. // Clamp if requested
  32896. If( clampoutput, () => {
  32897. result.assign( clamp( result, outmin, outmax ) );
  32898. } );
  32899. return result;
  32900. } ).setLayout( {
  32901. name: 'mx_unifiednoise2d',
  32902. type: 'float',
  32903. inputs: [
  32904. { name: 'noiseType', type: 'int' },
  32905. { name: 'texcoord', type: 'vec2' },
  32906. { name: 'freq', type: 'vec2' },
  32907. { name: 'offset', type: 'vec2' },
  32908. { name: 'jitter', type: 'float' },
  32909. { name: 'outmin', type: 'float' },
  32910. { name: 'outmax', type: 'float' },
  32911. { name: 'clampoutput', type: 'bool' },
  32912. { name: 'octaves', type: 'int' },
  32913. { name: 'lacunarity', type: 'float' },
  32914. { name: 'diminish', type: 'float' }
  32915. ]
  32916. } );
  32917. // Unified Noise 3D
  32918. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  32919. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  32920. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  32921. octaves_immutable, lacunarity_immutable, diminish_immutable
  32922. ] ) => {
  32923. const noiseType = int( noiseType_immutable ).toVar();
  32924. const position = vec3( position_immutable ).toVar();
  32925. const freq = vec3( freq_immutable ).toVar();
  32926. const offset = vec3( offset_immutable ).toVar();
  32927. const jitter = float( jitter_immutable ).toVar();
  32928. const outmin = float( outmin_immutable ).toVar();
  32929. const outmax = float( outmax_immutable ).toVar();
  32930. const clampoutput = bool( clampoutput_immutable ).toVar();
  32931. const octaves = int( octaves_immutable ).toVar();
  32932. const lacunarity = float( lacunarity_immutable ).toVar();
  32933. const diminish = float( diminish_immutable ).toVar();
  32934. // Compute input position
  32935. const p = position.mul( freq ).add( offset );
  32936. const result = float( 0.0 ).toVar();
  32937. // Perlin
  32938. If( noiseType.equal( int( 0 ) ), () => {
  32939. result.assign( mx_perlin_noise_vec3( p ) );
  32940. } );
  32941. // Cell
  32942. If( noiseType.equal( int( 1 ) ), () => {
  32943. result.assign( mx_cell_noise_vec3( p ) );
  32944. } );
  32945. // Worley (metric=0 = euclidean)
  32946. If( noiseType.equal( int( 2 ) ), () => {
  32947. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  32948. } );
  32949. // Fractal
  32950. If( noiseType.equal( int( 3 ) ), () => {
  32951. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  32952. } );
  32953. // Remap output to [outmin, outmax]
  32954. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  32955. // Clamp if requested
  32956. If( clampoutput, () => {
  32957. result.assign( clamp( result, outmin, outmax ) );
  32958. } );
  32959. return result;
  32960. } ).setLayout( {
  32961. name: 'mx_unifiednoise3d',
  32962. type: 'float',
  32963. inputs: [
  32964. { name: 'noiseType', type: 'int' },
  32965. { name: 'position', type: 'vec3' },
  32966. { name: 'freq', type: 'vec3' },
  32967. { name: 'offset', type: 'vec3' },
  32968. { name: 'jitter', type: 'float' },
  32969. { name: 'outmin', type: 'float' },
  32970. { name: 'outmax', type: 'float' },
  32971. { name: 'clampoutput', type: 'bool' },
  32972. { name: 'octaves', type: 'int' },
  32973. { name: 'lacunarity', type: 'float' },
  32974. { name: 'diminish', type: 'float' }
  32975. ]
  32976. } );
  32977. // Three.js Transpiler
  32978. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  32979. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  32980. const s = hsv.y;
  32981. const v = hsv.z;
  32982. const result = vec3().toVar();
  32983. If( s.lessThan( 0.0001 ), () => {
  32984. result.assign( vec3( v, v, v ) );
  32985. } ).Else( () => {
  32986. let h = hsv.x;
  32987. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  32988. const hi = int( trunc( h ) );
  32989. const f = h.sub( float( hi ) );
  32990. const p = v.mul( s.oneMinus() );
  32991. const q = v.mul( s.mul( f ).oneMinus() );
  32992. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  32993. If( hi.equal( int( 0 ) ), () => {
  32994. result.assign( vec3( v, t, p ) );
  32995. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  32996. result.assign( vec3( q, v, p ) );
  32997. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  32998. result.assign( vec3( p, v, t ) );
  32999. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  33000. result.assign( vec3( p, q, v ) );
  33001. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  33002. result.assign( vec3( t, p, v ) );
  33003. } ).Else( () => {
  33004. result.assign( vec3( v, p, q ) );
  33005. } );
  33006. } );
  33007. return result;
  33008. } ).setLayout( {
  33009. name: 'mx_hsvtorgb',
  33010. type: 'vec3',
  33011. inputs: [
  33012. { name: 'hsv', type: 'vec3' }
  33013. ]
  33014. } );
  33015. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  33016. const c = vec3( c_immutable ).toVar();
  33017. const r = float( c.x ).toVar();
  33018. const g = float( c.y ).toVar();
  33019. const b = float( c.z ).toVar();
  33020. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  33021. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  33022. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  33023. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  33024. v.assign( maxcomp );
  33025. If( maxcomp.greaterThan( 0.0 ), () => {
  33026. s.assign( delta.div( maxcomp ) );
  33027. } ).Else( () => {
  33028. s.assign( 0.0 );
  33029. } );
  33030. If( s.lessThanEqual( 0.0 ), () => {
  33031. h.assign( 0.0 );
  33032. } ).Else( () => {
  33033. If( r.greaterThanEqual( maxcomp ), () => {
  33034. h.assign( g.sub( b ).div( delta ) );
  33035. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  33036. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  33037. } ).Else( () => {
  33038. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  33039. } );
  33040. h.mulAssign( 1.0 / 6.0 );
  33041. If( h.lessThan( 0.0 ), () => {
  33042. h.addAssign( 1.0 );
  33043. } );
  33044. } );
  33045. return vec3( h, s, v );
  33046. } ).setLayout( {
  33047. name: 'mx_rgbtohsv',
  33048. type: 'vec3',
  33049. inputs: [
  33050. { name: 'c', type: 'vec3' }
  33051. ]
  33052. } );
  33053. // Three.js Transpiler
  33054. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  33055. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  33056. const color = vec3( color_immutable ).toVar();
  33057. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  33058. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  33059. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  33060. return mix( linSeg, powSeg, isAbove );
  33061. } ).setLayout( {
  33062. name: 'mx_srgb_texture_to_lin_rec709',
  33063. type: 'vec3',
  33064. inputs: [
  33065. { name: 'color', type: 'vec3' }
  33066. ]
  33067. } );
  33068. const mx_aastep = ( threshold, value ) => {
  33069. threshold = float( threshold );
  33070. value = float( value );
  33071. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  33072. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  33073. };
  33074. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  33075. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  33076. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  33077. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  33078. const mx_ramp4 = (
  33079. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  33080. ) => {
  33081. const u = texcoord.x.clamp();
  33082. const v = texcoord.y.clamp();
  33083. const top = mix( valuetl, valuetr, u );
  33084. const bottom = mix( valuebl, valuebr, u );
  33085. return mix( top, bottom, v );
  33086. };
  33087. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  33088. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  33089. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  33090. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  33091. const mx_safepower = ( in1, in2 = 1 ) => {
  33092. in1 = float( in1 );
  33093. return in1.abs().pow( in2 ).mul( in1.sign() );
  33094. };
  33095. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  33096. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33097. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33098. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33099. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  33100. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  33101. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  33102. return noise_vec4.mul( amplitude ).add( pivot );
  33103. };
  33104. 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 );
  33105. 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 );
  33106. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33107. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33108. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33109. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  33110. 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 );
  33111. 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 );
  33112. 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 );
  33113. 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 );
  33114. // === Moved from MaterialXLoader.js ===
  33115. // Math ops
  33116. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  33117. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  33118. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  33119. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  33120. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  33121. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  33122. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  33123. const mx_timer = () => time;
  33124. const mx_frame = () => frameId;
  33125. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  33126. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  33127. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  33128. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  33129. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  33130. const mx_separate = ( in1, channelOrOut = null ) => {
  33131. if ( typeof channelOrOut === 'string' ) {
  33132. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33133. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  33134. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  33135. }
  33136. if ( typeof channelOrOut === 'number' ) {
  33137. return in1.element( channelOrOut );
  33138. }
  33139. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  33140. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33141. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  33142. }
  33143. return in1;
  33144. };
  33145. const mx_place2d = (
  33146. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  33147. ) => {
  33148. let uv = texcoord;
  33149. if ( pivot ) uv = uv.sub( pivot );
  33150. if ( scale ) uv = uv.mul( scale );
  33151. if ( rotate ) {
  33152. const rad = rotate.mul( Math.PI / 180.0 );
  33153. const cosR = rad.cos();
  33154. const sinR = rad.sin();
  33155. uv = vec2(
  33156. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  33157. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  33158. );
  33159. }
  33160. if ( pivot ) uv = uv.add( pivot );
  33161. if ( offset ) uv = uv.add( offset );
  33162. return uv;
  33163. };
  33164. const mx_rotate2d = ( input, amount ) => {
  33165. input = vec2( input );
  33166. amount = float( amount );
  33167. const radians = amount.mul( Math.PI / 180.0 );
  33168. return rotate( input, radians );
  33169. };
  33170. const mx_rotate3d = ( input, amount, axis ) => {
  33171. input = vec3( input );
  33172. amount = float( amount );
  33173. axis = vec3( axis );
  33174. const radians = amount.mul( Math.PI / 180.0 );
  33175. const nAxis = axis.normalize();
  33176. const cosA = radians.cos();
  33177. const sinA = radians.sin();
  33178. const oneMinusCosA = float( 1 ).sub( cosA );
  33179. const rot =
  33180. input.mul( cosA )
  33181. .add( nAxis.cross( input ).mul( sinA ) )
  33182. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  33183. return rot;
  33184. };
  33185. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  33186. input = vec3( input );
  33187. scale = float( scale );
  33188. return bumpMap( input, scale );
  33189. };
  33190. /**
  33191. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  33192. *
  33193. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  33194. *
  33195. * ```js
  33196. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  33197. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  33198. * ```
  33199. *
  33200. * @tsl
  33201. * @function
  33202. * @param {Node<vec3>} normal - The normal to correct.
  33203. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  33204. * @param {Node<vec3>} cubePos - The cube position.
  33205. * @return {Node<vec3>} The parallax corrected normal.
  33206. */
  33207. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  33208. const nDir = normalize( normal ).toVar();
  33209. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33210. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33211. const rbminmax = vec3().toVar();
  33212. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  33213. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  33214. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  33215. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  33216. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  33217. return boxIntersection.sub( cubePos );
  33218. } );
  33219. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  33220. // normal is assumed to have unit length
  33221. const x = normal.x, y = normal.y, z = normal.z;
  33222. // band 0
  33223. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  33224. // band 1
  33225. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  33226. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  33227. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  33228. // band 2
  33229. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  33230. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  33231. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  33232. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  33233. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  33234. return result;
  33235. } );
  33236. // constants
  33237. var TSL = /*#__PURE__*/Object.freeze({
  33238. __proto__: null,
  33239. BRDF_GGX: BRDF_GGX,
  33240. BRDF_Lambert: BRDF_Lambert,
  33241. BasicPointShadowFilter: BasicPointShadowFilter,
  33242. BasicShadowFilter: BasicShadowFilter,
  33243. Break: Break,
  33244. Const: Const,
  33245. Continue: Continue,
  33246. DFGLUT: DFGLUT,
  33247. D_GGX: D_GGX,
  33248. Discard: Discard,
  33249. EPSILON: EPSILON,
  33250. F_Schlick: F_Schlick,
  33251. Fn: Fn,
  33252. HALF_PI: HALF_PI,
  33253. INFINITY: INFINITY,
  33254. If: If,
  33255. Loop: Loop,
  33256. NodeAccess: NodeAccess,
  33257. NodeShaderStage: NodeShaderStage,
  33258. NodeType: NodeType,
  33259. NodeUpdateType: NodeUpdateType,
  33260. OnBeforeMaterialUpdate: OnBeforeMaterialUpdate,
  33261. OnBeforeObjectUpdate: OnBeforeObjectUpdate,
  33262. OnMaterialUpdate: OnMaterialUpdate,
  33263. OnObjectUpdate: OnObjectUpdate,
  33264. PCFShadowFilter: PCFShadowFilter,
  33265. PCFSoftShadowFilter: PCFSoftShadowFilter,
  33266. PI: PI,
  33267. PI2: PI2,
  33268. PointShadowFilter: PointShadowFilter,
  33269. Return: Return,
  33270. Schlick_to_F0: Schlick_to_F0,
  33271. ShaderNode: ShaderNode,
  33272. Stack: Stack,
  33273. Switch: Switch,
  33274. TBNViewMatrix: TBNViewMatrix,
  33275. TWO_PI: TWO_PI,
  33276. VSMShadowFilter: VSMShadowFilter,
  33277. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  33278. Var: Var,
  33279. VarIntent: VarIntent,
  33280. abs: abs,
  33281. acesFilmicToneMapping: acesFilmicToneMapping,
  33282. acos: acos,
  33283. add: add,
  33284. addMethodChaining: addMethodChaining,
  33285. addNodeElement: addNodeElement,
  33286. agxToneMapping: agxToneMapping,
  33287. all: all,
  33288. alphaT: alphaT,
  33289. and: and,
  33290. anisotropy: anisotropy,
  33291. anisotropyB: anisotropyB,
  33292. anisotropyT: anisotropyT,
  33293. any: any,
  33294. append: append,
  33295. array: array,
  33296. arrayBuffer: arrayBuffer,
  33297. asin: asin,
  33298. assign: assign,
  33299. atan: atan,
  33300. atomicAdd: atomicAdd,
  33301. atomicAnd: atomicAnd,
  33302. atomicFunc: atomicFunc,
  33303. atomicLoad: atomicLoad,
  33304. atomicMax: atomicMax,
  33305. atomicMin: atomicMin,
  33306. atomicOr: atomicOr,
  33307. atomicStore: atomicStore,
  33308. atomicSub: atomicSub,
  33309. atomicXor: atomicXor,
  33310. attenuationColor: attenuationColor,
  33311. attenuationDistance: attenuationDistance,
  33312. attribute: attribute,
  33313. attributeArray: attributeArray,
  33314. backgroundBlurriness: backgroundBlurriness,
  33315. backgroundIntensity: backgroundIntensity,
  33316. backgroundRotation: backgroundRotation,
  33317. batch: batch,
  33318. bentNormalView: bentNormalView,
  33319. billboarding: billboarding,
  33320. bitAnd: bitAnd,
  33321. bitNot: bitNot,
  33322. bitOr: bitOr,
  33323. bitXor: bitXor,
  33324. bitangentGeometry: bitangentGeometry,
  33325. bitangentLocal: bitangentLocal,
  33326. bitangentView: bitangentView,
  33327. bitangentWorld: bitangentWorld,
  33328. bitcast: bitcast,
  33329. blendBurn: blendBurn,
  33330. blendColor: blendColor,
  33331. blendDodge: blendDodge,
  33332. blendOverlay: blendOverlay,
  33333. blendScreen: blendScreen,
  33334. blur: blur,
  33335. bool: bool,
  33336. buffer: buffer,
  33337. bufferAttribute: bufferAttribute,
  33338. builtin: builtin,
  33339. builtinAOContext: builtinAOContext,
  33340. builtinShadowContext: builtinShadowContext,
  33341. bumpMap: bumpMap,
  33342. bvec2: bvec2,
  33343. bvec3: bvec3,
  33344. bvec4: bvec4,
  33345. bypass: bypass,
  33346. cache: cache,
  33347. call: call,
  33348. cameraFar: cameraFar,
  33349. cameraIndex: cameraIndex,
  33350. cameraNear: cameraNear,
  33351. cameraNormalMatrix: cameraNormalMatrix,
  33352. cameraPosition: cameraPosition,
  33353. cameraProjectionMatrix: cameraProjectionMatrix,
  33354. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  33355. cameraViewMatrix: cameraViewMatrix,
  33356. cameraViewport: cameraViewport,
  33357. cameraWorldMatrix: cameraWorldMatrix,
  33358. cbrt: cbrt,
  33359. cdl: cdl,
  33360. ceil: ceil,
  33361. checker: checker,
  33362. cineonToneMapping: cineonToneMapping,
  33363. clamp: clamp,
  33364. clearcoat: clearcoat,
  33365. clearcoatNormalView: clearcoatNormalView,
  33366. clearcoatRoughness: clearcoatRoughness,
  33367. clipSpace: clipSpace,
  33368. code: code,
  33369. color: color,
  33370. colorSpaceToWorking: colorSpaceToWorking,
  33371. colorToDirection: colorToDirection,
  33372. compute: compute,
  33373. computeKernel: computeKernel,
  33374. computeSkinning: computeSkinning,
  33375. context: context,
  33376. convert: convert,
  33377. convertColorSpace: convertColorSpace,
  33378. convertToTexture: convertToTexture,
  33379. cos: cos,
  33380. countLeadingZeros: countLeadingZeros,
  33381. countOneBits: countOneBits,
  33382. countTrailingZeros: countTrailingZeros,
  33383. cross: cross,
  33384. cubeTexture: cubeTexture,
  33385. cubeTextureBase: cubeTextureBase,
  33386. dFdx: dFdx,
  33387. dFdy: dFdy,
  33388. dashSize: dashSize,
  33389. debug: debug,
  33390. decrement: decrement,
  33391. decrementBefore: decrementBefore,
  33392. defaultBuildStages: defaultBuildStages,
  33393. defaultShaderStages: defaultShaderStages,
  33394. defined: defined,
  33395. degrees: degrees,
  33396. deltaTime: deltaTime,
  33397. densityFogFactor: densityFogFactor,
  33398. depth: depth,
  33399. depthPass: depthPass,
  33400. determinant: determinant,
  33401. difference: difference,
  33402. diffuseColor: diffuseColor,
  33403. diffuseContribution: diffuseContribution,
  33404. directPointLight: directPointLight,
  33405. directionToColor: directionToColor,
  33406. directionToFaceDirection: directionToFaceDirection,
  33407. dispersion: dispersion,
  33408. disposeShadowMaterial: disposeShadowMaterial,
  33409. distance: distance,
  33410. div: div,
  33411. dot: dot,
  33412. drawIndex: drawIndex,
  33413. dynamicBufferAttribute: dynamicBufferAttribute,
  33414. element: element,
  33415. emissive: emissive,
  33416. equal: equal,
  33417. equirectUV: equirectUV,
  33418. exp: exp,
  33419. exp2: exp2,
  33420. exponentialHeightFogFactor: exponentialHeightFogFactor,
  33421. expression: expression,
  33422. faceDirection: faceDirection,
  33423. faceForward: faceForward,
  33424. faceforward: faceforward,
  33425. float: float,
  33426. floatBitsToInt: floatBitsToInt,
  33427. floatBitsToUint: floatBitsToUint,
  33428. floor: floor,
  33429. fog: fog,
  33430. fract: fract,
  33431. frameGroup: frameGroup,
  33432. frameId: frameId,
  33433. frontFacing: frontFacing,
  33434. fwidth: fwidth,
  33435. gain: gain,
  33436. gapSize: gapSize,
  33437. getConstNodeType: getConstNodeType,
  33438. getCurrentStack: getCurrentStack,
  33439. getDirection: getDirection,
  33440. getDistanceAttenuation: getDistanceAttenuation,
  33441. getGeometryRoughness: getGeometryRoughness,
  33442. getNormalFromDepth: getNormalFromDepth,
  33443. getParallaxCorrectNormal: getParallaxCorrectNormal,
  33444. getRoughness: getRoughness,
  33445. getScreenPosition: getScreenPosition,
  33446. getShIrradianceAt: getShIrradianceAt,
  33447. getShadowMaterial: getShadowMaterial,
  33448. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  33449. getTextureIndex: getTextureIndex,
  33450. getViewPosition: getViewPosition,
  33451. ggxConvolution: ggxConvolution,
  33452. globalId: globalId,
  33453. glsl: glsl,
  33454. glslFn: glslFn,
  33455. grayscale: grayscale,
  33456. greaterThan: greaterThan,
  33457. greaterThanEqual: greaterThanEqual,
  33458. hash: hash,
  33459. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  33460. highpModelViewMatrix: highpModelViewMatrix,
  33461. hue: hue,
  33462. increment: increment,
  33463. incrementBefore: incrementBefore,
  33464. inspector: inspector,
  33465. instance: instance,
  33466. instanceIndex: instanceIndex,
  33467. instancedArray: instancedArray,
  33468. instancedBufferAttribute: instancedBufferAttribute,
  33469. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  33470. instancedMesh: instancedMesh,
  33471. int: int,
  33472. intBitsToFloat: intBitsToFloat,
  33473. interleavedGradientNoise: interleavedGradientNoise,
  33474. inverse: inverse,
  33475. inverseSqrt: inverseSqrt,
  33476. inversesqrt: inversesqrt,
  33477. invocationLocalIndex: invocationLocalIndex,
  33478. invocationSubgroupIndex: invocationSubgroupIndex,
  33479. ior: ior,
  33480. iridescence: iridescence,
  33481. iridescenceIOR: iridescenceIOR,
  33482. iridescenceThickness: iridescenceThickness,
  33483. isolate: isolate,
  33484. ivec2: ivec2,
  33485. ivec3: ivec3,
  33486. ivec4: ivec4,
  33487. js: js,
  33488. label: label,
  33489. length: length,
  33490. lengthSq: lengthSq,
  33491. lessThan: lessThan,
  33492. lessThanEqual: lessThanEqual,
  33493. lightPosition: lightPosition,
  33494. lightProjectionUV: lightProjectionUV,
  33495. lightShadowMatrix: lightShadowMatrix,
  33496. lightTargetDirection: lightTargetDirection,
  33497. lightTargetPosition: lightTargetPosition,
  33498. lightViewPosition: lightViewPosition,
  33499. lightingContext: lightingContext,
  33500. lights: lights,
  33501. linearDepth: linearDepth,
  33502. linearToneMapping: linearToneMapping,
  33503. localId: localId,
  33504. log: log,
  33505. log2: log2,
  33506. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  33507. luminance: luminance,
  33508. mat2: mat2,
  33509. mat3: mat3,
  33510. mat4: mat4,
  33511. matcapUV: matcapUV,
  33512. materialAO: materialAO,
  33513. materialAlphaTest: materialAlphaTest,
  33514. materialAnisotropy: materialAnisotropy,
  33515. materialAnisotropyVector: materialAnisotropyVector,
  33516. materialAttenuationColor: materialAttenuationColor,
  33517. materialAttenuationDistance: materialAttenuationDistance,
  33518. materialClearcoat: materialClearcoat,
  33519. materialClearcoatNormal: materialClearcoatNormal,
  33520. materialClearcoatRoughness: materialClearcoatRoughness,
  33521. materialColor: materialColor,
  33522. materialDispersion: materialDispersion,
  33523. materialEmissive: materialEmissive,
  33524. materialEnvIntensity: materialEnvIntensity,
  33525. materialEnvRotation: materialEnvRotation,
  33526. materialIOR: materialIOR,
  33527. materialIridescence: materialIridescence,
  33528. materialIridescenceIOR: materialIridescenceIOR,
  33529. materialIridescenceThickness: materialIridescenceThickness,
  33530. materialLightMap: materialLightMap,
  33531. materialLineDashOffset: materialLineDashOffset,
  33532. materialLineDashSize: materialLineDashSize,
  33533. materialLineGapSize: materialLineGapSize,
  33534. materialLineScale: materialLineScale,
  33535. materialLineWidth: materialLineWidth,
  33536. materialMetalness: materialMetalness,
  33537. materialNormal: materialNormal,
  33538. materialOpacity: materialOpacity,
  33539. materialPointSize: materialPointSize,
  33540. materialReference: materialReference,
  33541. materialReflectivity: materialReflectivity,
  33542. materialRefractionRatio: materialRefractionRatio,
  33543. materialRotation: materialRotation,
  33544. materialRoughness: materialRoughness,
  33545. materialSheen: materialSheen,
  33546. materialSheenRoughness: materialSheenRoughness,
  33547. materialShininess: materialShininess,
  33548. materialSpecular: materialSpecular,
  33549. materialSpecularColor: materialSpecularColor,
  33550. materialSpecularIntensity: materialSpecularIntensity,
  33551. materialSpecularStrength: materialSpecularStrength,
  33552. materialThickness: materialThickness,
  33553. materialTransmission: materialTransmission,
  33554. max: max$1,
  33555. maxMipLevel: maxMipLevel,
  33556. mediumpModelViewMatrix: mediumpModelViewMatrix,
  33557. metalness: metalness,
  33558. min: min$1,
  33559. mix: mix,
  33560. mixElement: mixElement,
  33561. mod: mod,
  33562. modInt: modInt,
  33563. modelDirection: modelDirection,
  33564. modelNormalMatrix: modelNormalMatrix,
  33565. modelPosition: modelPosition,
  33566. modelRadius: modelRadius,
  33567. modelScale: modelScale,
  33568. modelViewMatrix: modelViewMatrix,
  33569. modelViewPosition: modelViewPosition,
  33570. modelViewProjection: modelViewProjection,
  33571. modelWorldMatrix: modelWorldMatrix,
  33572. modelWorldMatrixInverse: modelWorldMatrixInverse,
  33573. morphReference: morphReference,
  33574. mrt: mrt,
  33575. mul: mul,
  33576. mx_aastep: mx_aastep,
  33577. mx_add: mx_add,
  33578. mx_atan2: mx_atan2,
  33579. mx_cell_noise_float: mx_cell_noise_float,
  33580. mx_contrast: mx_contrast,
  33581. mx_divide: mx_divide,
  33582. mx_fractal_noise_float: mx_fractal_noise_float,
  33583. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  33584. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  33585. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  33586. mx_frame: mx_frame,
  33587. mx_heighttonormal: mx_heighttonormal,
  33588. mx_hsvtorgb: mx_hsvtorgb,
  33589. mx_ifequal: mx_ifequal,
  33590. mx_ifgreater: mx_ifgreater,
  33591. mx_ifgreatereq: mx_ifgreatereq,
  33592. mx_invert: mx_invert,
  33593. mx_modulo: mx_modulo,
  33594. mx_multiply: mx_multiply,
  33595. mx_noise_float: mx_noise_float,
  33596. mx_noise_vec3: mx_noise_vec3,
  33597. mx_noise_vec4: mx_noise_vec4,
  33598. mx_place2d: mx_place2d,
  33599. mx_power: mx_power,
  33600. mx_ramp4: mx_ramp4,
  33601. mx_ramplr: mx_ramplr,
  33602. mx_ramptb: mx_ramptb,
  33603. mx_rgbtohsv: mx_rgbtohsv,
  33604. mx_rotate2d: mx_rotate2d,
  33605. mx_rotate3d: mx_rotate3d,
  33606. mx_safepower: mx_safepower,
  33607. mx_separate: mx_separate,
  33608. mx_splitlr: mx_splitlr,
  33609. mx_splittb: mx_splittb,
  33610. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  33611. mx_subtract: mx_subtract,
  33612. mx_timer: mx_timer,
  33613. mx_transform_uv: mx_transform_uv,
  33614. mx_unifiednoise2d: mx_unifiednoise2d,
  33615. mx_unifiednoise3d: mx_unifiednoise3d,
  33616. mx_worley_noise_float: mx_worley_noise_float,
  33617. mx_worley_noise_vec2: mx_worley_noise_vec2,
  33618. mx_worley_noise_vec3: mx_worley_noise_vec3,
  33619. negate: negate,
  33620. neutralToneMapping: neutralToneMapping,
  33621. nodeArray: nodeArray,
  33622. nodeImmutable: nodeImmutable,
  33623. nodeObject: nodeObject,
  33624. nodeObjectIntent: nodeObjectIntent,
  33625. nodeObjects: nodeObjects,
  33626. nodeProxy: nodeProxy,
  33627. nodeProxyIntent: nodeProxyIntent,
  33628. normalFlat: normalFlat,
  33629. normalGeometry: normalGeometry,
  33630. normalLocal: normalLocal,
  33631. normalMap: normalMap,
  33632. normalView: normalView,
  33633. normalViewGeometry: normalViewGeometry,
  33634. normalWorld: normalWorld,
  33635. normalWorldGeometry: normalWorldGeometry,
  33636. normalize: normalize,
  33637. not: not,
  33638. notEqual: notEqual,
  33639. numWorkgroups: numWorkgroups,
  33640. objectDirection: objectDirection,
  33641. objectGroup: objectGroup,
  33642. objectPosition: objectPosition,
  33643. objectRadius: objectRadius,
  33644. objectScale: objectScale,
  33645. objectViewPosition: objectViewPosition,
  33646. objectWorldMatrix: objectWorldMatrix,
  33647. oneMinus: oneMinus,
  33648. or: or,
  33649. orthographicDepthToViewZ: orthographicDepthToViewZ,
  33650. oscSawtooth: oscSawtooth,
  33651. oscSine: oscSine,
  33652. oscSquare: oscSquare,
  33653. oscTriangle: oscTriangle,
  33654. output: output,
  33655. outputStruct: outputStruct,
  33656. overloadingFn: overloadingFn,
  33657. packHalf2x16: packHalf2x16,
  33658. packSnorm2x16: packSnorm2x16,
  33659. packUnorm2x16: packUnorm2x16,
  33660. parabola: parabola,
  33661. parallaxDirection: parallaxDirection,
  33662. parallaxUV: parallaxUV,
  33663. parameter: parameter,
  33664. pass: pass,
  33665. passTexture: passTexture,
  33666. pcurve: pcurve,
  33667. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  33668. pmremTexture: pmremTexture,
  33669. pointShadow: pointShadow,
  33670. pointUV: pointUV,
  33671. pointWidth: pointWidth,
  33672. positionGeometry: positionGeometry,
  33673. positionLocal: positionLocal,
  33674. positionPrevious: positionPrevious,
  33675. positionView: positionView,
  33676. positionViewDirection: positionViewDirection,
  33677. positionWorld: positionWorld,
  33678. positionWorldDirection: positionWorldDirection,
  33679. posterize: posterize,
  33680. pow: pow,
  33681. pow2: pow2,
  33682. pow3: pow3,
  33683. pow4: pow4,
  33684. premultiplyAlpha: premultiplyAlpha,
  33685. property: property,
  33686. quadBroadcast: quadBroadcast,
  33687. quadSwapDiagonal: quadSwapDiagonal,
  33688. quadSwapX: quadSwapX,
  33689. quadSwapY: quadSwapY,
  33690. radians: radians,
  33691. rand: rand,
  33692. range: range,
  33693. rangeFogFactor: rangeFogFactor,
  33694. reciprocal: reciprocal,
  33695. reference: reference,
  33696. referenceBuffer: referenceBuffer,
  33697. reflect: reflect,
  33698. reflectVector: reflectVector,
  33699. reflectView: reflectView,
  33700. reflector: reflector,
  33701. refract: refract,
  33702. refractVector: refractVector,
  33703. refractView: refractView,
  33704. reinhardToneMapping: reinhardToneMapping,
  33705. remap: remap,
  33706. remapClamp: remapClamp,
  33707. renderGroup: renderGroup,
  33708. renderOutput: renderOutput,
  33709. rendererReference: rendererReference,
  33710. replaceDefaultUV: replaceDefaultUV,
  33711. rotate: rotate,
  33712. rotateUV: rotateUV,
  33713. roughness: roughness,
  33714. round: round,
  33715. rtt: rtt,
  33716. sRGBTransferEOTF: sRGBTransferEOTF,
  33717. sRGBTransferOETF: sRGBTransferOETF,
  33718. sample: sample,
  33719. sampler: sampler,
  33720. samplerComparison: samplerComparison,
  33721. saturate: saturate,
  33722. saturation: saturation,
  33723. screenCoordinate: screenCoordinate,
  33724. screenDPR: screenDPR,
  33725. screenSize: screenSize,
  33726. screenUV: screenUV,
  33727. select: select,
  33728. setCurrentStack: setCurrentStack,
  33729. setName: setName,
  33730. shaderStages: shaderStages,
  33731. shadow: shadow,
  33732. shadowPositionWorld: shadowPositionWorld,
  33733. shapeCircle: shapeCircle,
  33734. sharedUniformGroup: sharedUniformGroup,
  33735. sheen: sheen,
  33736. sheenRoughness: sheenRoughness,
  33737. shiftLeft: shiftLeft,
  33738. shiftRight: shiftRight,
  33739. shininess: shininess,
  33740. sign: sign,
  33741. sin: sin,
  33742. sinc: sinc,
  33743. skinning: skinning,
  33744. smoothstep: smoothstep,
  33745. smoothstepElement: smoothstepElement,
  33746. specularColor: specularColor,
  33747. specularColorBlended: specularColorBlended,
  33748. specularF90: specularF90,
  33749. spherizeUV: spherizeUV,
  33750. split: split,
  33751. spritesheetUV: spritesheetUV,
  33752. sqrt: sqrt,
  33753. stack: stack,
  33754. step: step,
  33755. stepElement: stepElement,
  33756. storage: storage,
  33757. storageBarrier: storageBarrier,
  33758. storageTexture: storageTexture,
  33759. string: string,
  33760. struct: struct,
  33761. sub: sub,
  33762. subBuild: subBuild,
  33763. subgroupAdd: subgroupAdd,
  33764. subgroupAll: subgroupAll,
  33765. subgroupAnd: subgroupAnd,
  33766. subgroupAny: subgroupAny,
  33767. subgroupBallot: subgroupBallot,
  33768. subgroupBroadcast: subgroupBroadcast,
  33769. subgroupBroadcastFirst: subgroupBroadcastFirst,
  33770. subgroupElect: subgroupElect,
  33771. subgroupExclusiveAdd: subgroupExclusiveAdd,
  33772. subgroupExclusiveMul: subgroupExclusiveMul,
  33773. subgroupInclusiveAdd: subgroupInclusiveAdd,
  33774. subgroupInclusiveMul: subgroupInclusiveMul,
  33775. subgroupIndex: subgroupIndex,
  33776. subgroupMax: subgroupMax,
  33777. subgroupMin: subgroupMin,
  33778. subgroupMul: subgroupMul,
  33779. subgroupOr: subgroupOr,
  33780. subgroupShuffle: subgroupShuffle,
  33781. subgroupShuffleDown: subgroupShuffleDown,
  33782. subgroupShuffleUp: subgroupShuffleUp,
  33783. subgroupShuffleXor: subgroupShuffleXor,
  33784. subgroupSize: subgroupSize,
  33785. subgroupXor: subgroupXor,
  33786. tan: tan,
  33787. tangentGeometry: tangentGeometry,
  33788. tangentLocal: tangentLocal,
  33789. tangentView: tangentView,
  33790. tangentWorld: tangentWorld,
  33791. texture: texture,
  33792. texture3D: texture3D,
  33793. texture3DLevel: texture3DLevel,
  33794. texture3DLoad: texture3DLoad,
  33795. textureBarrier: textureBarrier,
  33796. textureBicubic: textureBicubic,
  33797. textureBicubicLevel: textureBicubicLevel,
  33798. textureCubeUV: textureCubeUV,
  33799. textureLevel: textureLevel,
  33800. textureLoad: textureLoad,
  33801. textureSize: textureSize,
  33802. textureStore: textureStore,
  33803. thickness: thickness,
  33804. time: time,
  33805. toneMapping: toneMapping,
  33806. toneMappingExposure: toneMappingExposure,
  33807. toonOutlinePass: toonOutlinePass,
  33808. transformDirection: transformDirection,
  33809. transformNormal: transformNormal,
  33810. transformNormalToView: transformNormalToView,
  33811. transformedClearcoatNormalView: transformedClearcoatNormalView,
  33812. transformedNormalView: transformedNormalView,
  33813. transformedNormalWorld: transformedNormalWorld,
  33814. transmission: transmission,
  33815. transpose: transpose,
  33816. triNoise3D: triNoise3D,
  33817. triplanarTexture: triplanarTexture,
  33818. triplanarTextures: triplanarTextures,
  33819. trunc: trunc,
  33820. uint: uint,
  33821. uintBitsToFloat: uintBitsToFloat,
  33822. uniform: uniform,
  33823. uniformArray: uniformArray,
  33824. uniformCubeTexture: uniformCubeTexture,
  33825. uniformFlow: uniformFlow,
  33826. uniformGroup: uniformGroup,
  33827. uniformTexture: uniformTexture,
  33828. unpackHalf2x16: unpackHalf2x16,
  33829. unpackNormal: unpackNormal,
  33830. unpackSnorm2x16: unpackSnorm2x16,
  33831. unpackUnorm2x16: unpackUnorm2x16,
  33832. unpremultiplyAlpha: unpremultiplyAlpha,
  33833. userData: userData,
  33834. uv: uv$1,
  33835. uvec2: uvec2,
  33836. uvec3: uvec3,
  33837. uvec4: uvec4,
  33838. varying: varying,
  33839. varyingProperty: varyingProperty,
  33840. vec2: vec2,
  33841. vec3: vec3,
  33842. vec4: vec4,
  33843. vectorComponents: vectorComponents,
  33844. velocity: velocity,
  33845. vertexColor: vertexColor,
  33846. vertexIndex: vertexIndex,
  33847. vertexStage: vertexStage,
  33848. vibrance: vibrance,
  33849. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  33850. viewZToOrthographicDepth: viewZToOrthographicDepth,
  33851. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  33852. viewZToReversedPerspectiveDepth: viewZToReversedPerspectiveDepth,
  33853. viewport: viewport,
  33854. viewportCoordinate: viewportCoordinate,
  33855. viewportDepthTexture: viewportDepthTexture,
  33856. viewportLinearDepth: viewportLinearDepth,
  33857. viewportMipTexture: viewportMipTexture,
  33858. viewportOpaqueMipTexture: viewportOpaqueMipTexture,
  33859. viewportResolution: viewportResolution,
  33860. viewportSafeUV: viewportSafeUV,
  33861. viewportSharedTexture: viewportSharedTexture,
  33862. viewportSize: viewportSize,
  33863. viewportTexture: viewportTexture,
  33864. viewportUV: viewportUV,
  33865. vogelDiskSample: vogelDiskSample,
  33866. wgsl: wgsl,
  33867. wgslFn: wgslFn,
  33868. workgroupArray: workgroupArray,
  33869. workgroupBarrier: workgroupBarrier,
  33870. workgroupId: workgroupId,
  33871. workingToColorSpace: workingToColorSpace,
  33872. xor: xor
  33873. });
  33874. const _clearColor = /*@__PURE__*/ new Color4();
  33875. /**
  33876. * This renderer module manages the background.
  33877. *
  33878. * @private
  33879. * @augments DataMap
  33880. */
  33881. class Background extends DataMap {
  33882. /**
  33883. * Constructs a new background management component.
  33884. *
  33885. * @param {Renderer} renderer - The renderer.
  33886. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  33887. */
  33888. constructor( renderer, nodes ) {
  33889. super();
  33890. /**
  33891. * The renderer.
  33892. *
  33893. * @type {Renderer}
  33894. */
  33895. this.renderer = renderer;
  33896. /**
  33897. * Renderer component for managing nodes related logic.
  33898. *
  33899. * @type {Nodes}
  33900. */
  33901. this.nodes = nodes;
  33902. }
  33903. /**
  33904. * Updates the background for the given scene. Depending on how `Scene.background`
  33905. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  33906. * or add a mesh to the render list for rendering the background as a textured plane
  33907. * or skybox.
  33908. *
  33909. * @param {Scene} scene - The scene.
  33910. * @param {RenderList} renderList - The current render list.
  33911. * @param {RenderContext} renderContext - The current render context.
  33912. */
  33913. update( scene, renderList, renderContext ) {
  33914. const renderer = this.renderer;
  33915. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  33916. let forceClear = false;
  33917. if ( background === null ) {
  33918. // no background settings, use clear color configuration from the renderer
  33919. renderer._clearColor.getRGB( _clearColor );
  33920. _clearColor.a = renderer._clearColor.a;
  33921. } else if ( background.isColor === true ) {
  33922. // background is an opaque color
  33923. background.getRGB( _clearColor );
  33924. _clearColor.a = 1;
  33925. forceClear = true;
  33926. } else if ( background.isNode === true ) {
  33927. const sceneData = this.get( scene );
  33928. const backgroundNode = background;
  33929. _clearColor.copy( renderer._clearColor );
  33930. let backgroundMesh = sceneData.backgroundMesh;
  33931. if ( backgroundMesh === undefined ) {
  33932. const backgroundMeshNode = vec4( backgroundNode ).mul( backgroundIntensity ).context( {
  33933. // @TODO: Add Texture2D support using node context
  33934. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  33935. getTextureLevel: () => backgroundBlurriness
  33936. } );
  33937. // when using orthographic cameras, we must scale the skybox sphere
  33938. // up to exceed the dimensions of the camera's viewing box.
  33939. const isOrtho = cameraProjectionMatrix.element( 3 ).element( 3 ).equal( 1.0 );
  33940. // calculate the orthographic scale
  33941. // projectionMatrix[1][1] is (1 / top). Invert it to get the height and multiply by 3.0
  33942. // (an arbitrary safety factor) to ensure the skybox is large enough to cover the corners
  33943. // of the rectangular screen
  33944. const orthoScale = div( 1.0, cameraProjectionMatrix.element( 1 ).element( 1 ) ).mul( 3.0 );
  33945. // compute vertex position
  33946. const modifiedPosition = isOrtho.select( positionLocal.mul( orthoScale ), positionLocal );
  33947. // by using a w component of 0, the skybox will not translate when the camera moves through the scene
  33948. const viewPosition = modelViewMatrix.mul( vec4( modifiedPosition, 0.0 ) );
  33949. // we force w=1.0 here to prevent the w_clip=0 divide-by-zero error for ortho cameras.
  33950. let viewProj = cameraProjectionMatrix.mul( vec4( viewPosition.xyz, 1.0 ) );
  33951. // force background to far plane so it does not occlude objects
  33952. viewProj = viewProj.setZ( viewProj.w );
  33953. const nodeMaterial = new NodeMaterial();
  33954. nodeMaterial.name = 'Background.material';
  33955. nodeMaterial.side = BackSide;
  33956. nodeMaterial.depthTest = false;
  33957. nodeMaterial.depthWrite = false;
  33958. nodeMaterial.allowOverride = false;
  33959. nodeMaterial.fog = false;
  33960. nodeMaterial.lights = false;
  33961. nodeMaterial.vertexNode = viewProj;
  33962. nodeMaterial.colorNode = backgroundMeshNode;
  33963. sceneData.backgroundMeshNode = backgroundMeshNode;
  33964. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  33965. backgroundMesh.frustumCulled = false;
  33966. backgroundMesh.name = 'Background.mesh';
  33967. function onBackgroundDispose() {
  33968. background.removeEventListener( 'dispose', onBackgroundDispose );
  33969. backgroundMesh.material.dispose();
  33970. backgroundMesh.geometry.dispose();
  33971. }
  33972. background.addEventListener( 'dispose', onBackgroundDispose );
  33973. }
  33974. const backgroundCacheKey = backgroundNode.getCacheKey();
  33975. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  33976. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  33977. sceneData.backgroundMeshNode.needsUpdate = true;
  33978. backgroundMesh.material.needsUpdate = true;
  33979. sceneData.backgroundCacheKey = backgroundCacheKey;
  33980. }
  33981. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  33982. } else {
  33983. error( 'Renderer: Unsupported background configuration.', background );
  33984. }
  33985. //
  33986. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  33987. if ( environmentBlendMode === 'additive' ) {
  33988. _clearColor.set( 0, 0, 0, 1 );
  33989. } else if ( environmentBlendMode === 'alpha-blend' ) {
  33990. _clearColor.set( 0, 0, 0, 0 );
  33991. }
  33992. //
  33993. if ( renderer.autoClear === true || forceClear === true ) {
  33994. const clearColorValue = renderContext.clearColorValue;
  33995. clearColorValue.r = _clearColor.r;
  33996. clearColorValue.g = _clearColor.g;
  33997. clearColorValue.b = _clearColor.b;
  33998. clearColorValue.a = _clearColor.a;
  33999. // premultiply alpha
  34000. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  34001. clearColorValue.r *= clearColorValue.a;
  34002. clearColorValue.g *= clearColorValue.a;
  34003. clearColorValue.b *= clearColorValue.a;
  34004. }
  34005. //
  34006. renderContext.depthClearValue = renderer.getClearDepth();
  34007. renderContext.stencilClearValue = renderer.getClearStencil();
  34008. renderContext.clearColor = renderer.autoClearColor === true;
  34009. renderContext.clearDepth = renderer.autoClearDepth === true;
  34010. renderContext.clearStencil = renderer.autoClearStencil === true;
  34011. } else {
  34012. renderContext.clearColor = false;
  34013. renderContext.clearDepth = false;
  34014. renderContext.clearStencil = false;
  34015. }
  34016. }
  34017. }
  34018. let _id$7 = 0;
  34019. /**
  34020. * A bind group represents a collection of bindings and thus a collection
  34021. * or resources. Bind groups are assigned to pipelines to provide them
  34022. * with the required resources (like uniform buffers or textures).
  34023. *
  34024. * @private
  34025. */
  34026. class BindGroup {
  34027. /**
  34028. * Constructs a new bind group.
  34029. *
  34030. * @param {string} name - The bind group's name.
  34031. * @param {Array<Binding>} bindings - An array of bindings.
  34032. * @param {number} index - The group index.
  34033. */
  34034. constructor( name = '', bindings = [], index = 0 ) {
  34035. /**
  34036. * The bind group's name.
  34037. *
  34038. * @type {string}
  34039. */
  34040. this.name = name;
  34041. /**
  34042. * An array of bindings.
  34043. *
  34044. * @type {Array<Binding>}
  34045. */
  34046. this.bindings = bindings;
  34047. /**
  34048. * The group index.
  34049. *
  34050. * @type {number}
  34051. */
  34052. this.index = index;
  34053. /**
  34054. * The group's ID.
  34055. *
  34056. * @type {number}
  34057. */
  34058. this.id = _id$7 ++;
  34059. }
  34060. }
  34061. /**
  34062. * This module represents the state of a node builder after it was
  34063. * used to build the nodes for a render object. The state holds the
  34064. * results of the build for further processing in the renderer.
  34065. *
  34066. * Render objects with identical cache keys share the same node builder state.
  34067. *
  34068. * @private
  34069. */
  34070. class NodeBuilderState {
  34071. /**
  34072. * Constructs a new node builder state.
  34073. *
  34074. * @param {string} vertexShader - The native vertex shader code.
  34075. * @param {string} fragmentShader - The native fragment shader code.
  34076. * @param {string} computeShader - The native compute shader code.
  34077. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  34078. * @param {Array<BindGroup>} bindings - An array of bind groups.
  34079. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  34080. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  34081. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  34082. * @param {NodeMaterialObserver} observer - A node material observer.
  34083. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  34084. */
  34085. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  34086. /**
  34087. * The native vertex shader code.
  34088. *
  34089. * @type {string}
  34090. */
  34091. this.vertexShader = vertexShader;
  34092. /**
  34093. * The native fragment shader code.
  34094. *
  34095. * @type {string}
  34096. */
  34097. this.fragmentShader = fragmentShader;
  34098. /**
  34099. * The native compute shader code.
  34100. *
  34101. * @type {string}
  34102. */
  34103. this.computeShader = computeShader;
  34104. /**
  34105. * An array with transform attribute objects.
  34106. * Only relevant when using compute shaders with WebGL 2.
  34107. *
  34108. * @type {Array<Object>}
  34109. */
  34110. this.transforms = transforms;
  34111. /**
  34112. * An array of node attributes representing
  34113. * the attributes of the shaders.
  34114. *
  34115. * @type {Array<NodeAttribute>}
  34116. */
  34117. this.nodeAttributes = nodeAttributes;
  34118. /**
  34119. * An array of bind groups representing the uniform or storage
  34120. * buffers, texture or samplers of the shader.
  34121. *
  34122. * @type {Array<BindGroup>}
  34123. */
  34124. this.bindings = bindings;
  34125. /**
  34126. * An array of nodes that implement their `update()` method.
  34127. *
  34128. * @type {Array<Node>}
  34129. */
  34130. this.updateNodes = updateNodes;
  34131. /**
  34132. * An array of nodes that implement their `updateBefore()` method.
  34133. *
  34134. * @type {Array<Node>}
  34135. */
  34136. this.updateBeforeNodes = updateBeforeNodes;
  34137. /**
  34138. * An array of nodes that implement their `updateAfter()` method.
  34139. *
  34140. * @type {Array<Node>}
  34141. */
  34142. this.updateAfterNodes = updateAfterNodes;
  34143. /**
  34144. * A node material observer.
  34145. *
  34146. * @type {NodeMaterialObserver}
  34147. */
  34148. this.observer = observer;
  34149. /**
  34150. * How often this state is used by render objects.
  34151. *
  34152. * @type {number}
  34153. */
  34154. this.usedTimes = 0;
  34155. }
  34156. /**
  34157. * This method is used to create a array of bind groups based
  34158. * on the existing bind groups of this state. Shared groups are
  34159. * not cloned.
  34160. *
  34161. * @return {Array<BindGroup>} A array of bind groups.
  34162. */
  34163. createBindings() {
  34164. const bindings = [];
  34165. for ( const instanceGroup of this.bindings ) {
  34166. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  34167. if ( shared !== true ) {
  34168. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index );
  34169. bindings.push( bindingsGroup );
  34170. for ( const instanceBinding of instanceGroup.bindings ) {
  34171. bindingsGroup.bindings.push( instanceBinding.clone() );
  34172. }
  34173. } else {
  34174. bindings.push( instanceGroup );
  34175. }
  34176. }
  34177. return bindings;
  34178. }
  34179. }
  34180. /**
  34181. * {@link NodeBuilder} is going to create instances of this class during the build process
  34182. * of nodes. They represent the final shader attributes that are going to be generated
  34183. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  34184. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  34185. */
  34186. class NodeAttribute {
  34187. /**
  34188. * Constructs a new node attribute.
  34189. *
  34190. * @param {string} name - The name of the attribute.
  34191. * @param {string} type - The type of the attribute.
  34192. * @param {?Node} node - An optional reference to the node.
  34193. */
  34194. constructor( name, type, node = null ) {
  34195. /**
  34196. * This flag can be used for type testing.
  34197. *
  34198. * @type {boolean}
  34199. * @readonly
  34200. * @default true
  34201. */
  34202. this.isNodeAttribute = true;
  34203. /**
  34204. * The name of the attribute.
  34205. *
  34206. * @type {string}
  34207. */
  34208. this.name = name;
  34209. /**
  34210. * The type of the attribute.
  34211. *
  34212. * @type {string}
  34213. */
  34214. this.type = type;
  34215. /**
  34216. * An optional reference to the node.
  34217. *
  34218. * @type {?Node}
  34219. * @default null
  34220. */
  34221. this.node = node;
  34222. }
  34223. }
  34224. /**
  34225. * {@link NodeBuilder} is going to create instances of this class during the build process
  34226. * of nodes. They represent the final shader uniforms that are going to be generated
  34227. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  34228. * for this purpose.
  34229. */
  34230. class NodeUniform {
  34231. /**
  34232. * Constructs a new node uniform.
  34233. *
  34234. * @param {string} name - The name of the uniform.
  34235. * @param {string} type - The type of the uniform.
  34236. * @param {UniformNode} node - An reference to the node.
  34237. */
  34238. constructor( name, type, node ) {
  34239. /**
  34240. * This flag can be used for type testing.
  34241. *
  34242. * @type {boolean}
  34243. * @readonly
  34244. * @default true
  34245. */
  34246. this.isNodeUniform = true;
  34247. /**
  34248. * The name of the uniform.
  34249. *
  34250. * @type {string}
  34251. */
  34252. this.name = name;
  34253. /**
  34254. * The type of the uniform.
  34255. *
  34256. * @type {string}
  34257. */
  34258. this.type = type;
  34259. /**
  34260. * An reference to the node.
  34261. *
  34262. * @type {UniformNode}
  34263. */
  34264. this.node = node;
  34265. }
  34266. /**
  34267. * The value of the uniform node.
  34268. *
  34269. * @type {any}
  34270. */
  34271. get value() {
  34272. return this.node.value;
  34273. }
  34274. set value( val ) {
  34275. this.node.value = val;
  34276. }
  34277. /**
  34278. * The id of the uniform node.
  34279. *
  34280. * @type {number}
  34281. */
  34282. get id() {
  34283. return this.node.id;
  34284. }
  34285. /**
  34286. * The uniform node's group.
  34287. *
  34288. * @type {UniformGroupNode}
  34289. */
  34290. get groupNode() {
  34291. return this.node.groupNode;
  34292. }
  34293. }
  34294. /**
  34295. * {@link NodeBuilder} is going to create instances of this class during the build process
  34296. * of nodes. They represent the final shader variables that are going to be generated
  34297. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  34298. * this purpose.
  34299. */
  34300. class NodeVar {
  34301. /**
  34302. * Constructs a new node variable.
  34303. *
  34304. * @param {string} name - The name of the variable.
  34305. * @param {string} type - The type of the variable.
  34306. * @param {boolean} [readOnly=false] - The read-only flag.
  34307. * @param {?number} [count=null] - The size.
  34308. */
  34309. constructor( name, type, readOnly = false, count = null ) {
  34310. /**
  34311. * This flag can be used for type testing.
  34312. *
  34313. * @type {boolean}
  34314. * @readonly
  34315. * @default true
  34316. */
  34317. this.isNodeVar = true;
  34318. /**
  34319. * The name of the variable.
  34320. *
  34321. * @type {string}
  34322. */
  34323. this.name = name;
  34324. /**
  34325. * The type of the variable.
  34326. *
  34327. * @type {string}
  34328. */
  34329. this.type = type;
  34330. /**
  34331. * The read-only flag.
  34332. *
  34333. * @type {boolean}
  34334. */
  34335. this.readOnly = readOnly;
  34336. /**
  34337. * The size.
  34338. *
  34339. * @type {?number}
  34340. */
  34341. this.count = count;
  34342. }
  34343. }
  34344. /**
  34345. * {@link NodeBuilder} is going to create instances of this class during the build process
  34346. * of nodes. They represent the final shader varyings that are going to be generated
  34347. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  34348. * this purpose.
  34349. *
  34350. * @augments NodeVar
  34351. */
  34352. class NodeVarying extends NodeVar {
  34353. /**
  34354. * Constructs a new node varying.
  34355. *
  34356. * @param {string} name - The name of the varying.
  34357. * @param {string} type - The type of the varying.
  34358. * @param {?string} interpolationType - The interpolation type of the varying.
  34359. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  34360. */
  34361. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  34362. super( name, type );
  34363. /**
  34364. * Whether this varying requires interpolation or not. This property can be used
  34365. * to check if the varying can be optimized for a variable.
  34366. *
  34367. * @type {boolean}
  34368. * @default false
  34369. */
  34370. this.needsInterpolation = false;
  34371. /**
  34372. * This flag can be used for type testing.
  34373. *
  34374. * @type {boolean}
  34375. * @readonly
  34376. * @default true
  34377. */
  34378. this.isNodeVarying = true;
  34379. /**
  34380. * The interpolation type of the varying data.
  34381. *
  34382. * @type {?string}
  34383. * @default null
  34384. */
  34385. this.interpolationType = interpolationType;
  34386. /**
  34387. * The interpolation sampling type of varying data.
  34388. *
  34389. * @type {?string}
  34390. * @default null
  34391. */
  34392. this.interpolationSampling = interpolationSampling;
  34393. }
  34394. }
  34395. /**
  34396. * {@link NodeBuilder} is going to create instances of this class during the build process
  34397. * of nodes. They represent user-defined, native shader code portions that are going to be
  34398. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  34399. * for this purpose.
  34400. */
  34401. class NodeCode {
  34402. /**
  34403. * Constructs a new code node.
  34404. *
  34405. * @param {string} name - The name of the code.
  34406. * @param {string} type - The node type.
  34407. * @param {string} [code=''] - The native shader code.
  34408. */
  34409. constructor( name, type, code = '' ) {
  34410. /**
  34411. * The name of the code.
  34412. *
  34413. * @type {string}
  34414. */
  34415. this.name = name;
  34416. /**
  34417. * The node type.
  34418. *
  34419. * @type {string}
  34420. */
  34421. this.type = type;
  34422. /**
  34423. * The native shader code.
  34424. *
  34425. * @type {string}
  34426. * @default ''
  34427. */
  34428. this.code = code;
  34429. Object.defineProperty( this, 'isNodeCode', { value: true } );
  34430. }
  34431. }
  34432. let _id$6 = 0;
  34433. /**
  34434. * This utility class is used in {@link NodeBuilder} as an internal
  34435. * cache data structure for node data.
  34436. */
  34437. class NodeCache {
  34438. /**
  34439. * Constructs a new node cache.
  34440. *
  34441. * @param {?NodeCache} parent - A reference to a parent cache.
  34442. */
  34443. constructor( parent = null ) {
  34444. /**
  34445. * The id of the cache.
  34446. *
  34447. * @type {number}
  34448. * @readonly
  34449. */
  34450. this.id = _id$6 ++;
  34451. /**
  34452. * A weak map for managing node data.
  34453. *
  34454. * @type {WeakMap<Node, Object>}
  34455. */
  34456. this.nodesData = new WeakMap();
  34457. /**
  34458. * Reference to a parent node cache.
  34459. *
  34460. * @type {?NodeCache}
  34461. * @default null
  34462. */
  34463. this.parent = parent;
  34464. }
  34465. /**
  34466. * Returns the data for the given node.
  34467. *
  34468. * @param {Node} node - The node.
  34469. * @return {?Object} The data for the node.
  34470. */
  34471. getData( node ) {
  34472. let data = this.nodesData.get( node );
  34473. if ( data === undefined && this.parent !== null ) {
  34474. data = this.parent.getData( node );
  34475. }
  34476. return data;
  34477. }
  34478. /**
  34479. * Sets the data for a given node.
  34480. *
  34481. * @param {Node} node - The node.
  34482. * @param {Object} data - The data that should be cached.
  34483. */
  34484. setData( node, data ) {
  34485. this.nodesData.set( node, data );
  34486. }
  34487. }
  34488. class StructType {
  34489. constructor( name, members ) {
  34490. this.name = name;
  34491. this.members = members;
  34492. this.output = false;
  34493. }
  34494. }
  34495. /**
  34496. * Abstract base class for uniforms.
  34497. *
  34498. * @abstract
  34499. * @private
  34500. */
  34501. class Uniform {
  34502. /**
  34503. * Constructs a new uniform.
  34504. *
  34505. * @param {string} name - The uniform's name.
  34506. * @param {any} value - The uniform's value.
  34507. */
  34508. constructor( name, value ) {
  34509. /**
  34510. * The uniform's name.
  34511. *
  34512. * @type {string}
  34513. */
  34514. this.name = name;
  34515. /**
  34516. * The uniform's value.
  34517. *
  34518. * @type {any}
  34519. */
  34520. this.value = value;
  34521. /**
  34522. * Used to build the uniform buffer according to the STD140 layout.
  34523. * Derived uniforms will set this property to a data type specific
  34524. * value.
  34525. *
  34526. * @type {number}
  34527. */
  34528. this.boundary = 0;
  34529. /**
  34530. * The item size. Derived uniforms will set this property to a data
  34531. * type specific value.
  34532. *
  34533. * @type {number}
  34534. */
  34535. this.itemSize = 0;
  34536. /**
  34537. * This property is set by {@link UniformsGroup} and marks
  34538. * the start position in the uniform buffer.
  34539. *
  34540. * @type {number}
  34541. */
  34542. this.offset = 0;
  34543. /**
  34544. * This property is set by {@link UniformsGroup} and marks
  34545. * the index position in the uniform array.
  34546. *
  34547. * @type {number}
  34548. */
  34549. this.index = -1;
  34550. }
  34551. /**
  34552. * Sets the uniform's value.
  34553. *
  34554. * @param {any} value - The value to set.
  34555. */
  34556. setValue( value ) {
  34557. this.value = value;
  34558. }
  34559. /**
  34560. * Returns the uniform's value.
  34561. *
  34562. * @return {any} The value.
  34563. */
  34564. getValue() {
  34565. return this.value;
  34566. }
  34567. }
  34568. /**
  34569. * Represents a Number uniform.
  34570. *
  34571. * @private
  34572. * @augments Uniform
  34573. */
  34574. class NumberUniform extends Uniform {
  34575. /**
  34576. * Constructs a new Number uniform.
  34577. *
  34578. * @param {string} name - The uniform's name.
  34579. * @param {number} value - The uniform's value.
  34580. */
  34581. constructor( name, value = 0 ) {
  34582. super( name, value );
  34583. /**
  34584. * This flag can be used for type testing.
  34585. *
  34586. * @type {boolean}
  34587. * @readonly
  34588. * @default true
  34589. */
  34590. this.isNumberUniform = true;
  34591. this.boundary = 4;
  34592. this.itemSize = 1;
  34593. }
  34594. }
  34595. /**
  34596. * Represents a Vector2 uniform.
  34597. *
  34598. * @private
  34599. * @augments Uniform
  34600. */
  34601. class Vector2Uniform extends Uniform {
  34602. /**
  34603. * Constructs a new Number uniform.
  34604. *
  34605. * @param {string} name - The uniform's name.
  34606. * @param {Vector2} value - The uniform's value.
  34607. */
  34608. constructor( name, value = new Vector2() ) {
  34609. super( name, value );
  34610. /**
  34611. * This flag can be used for type testing.
  34612. *
  34613. * @type {boolean}
  34614. * @readonly
  34615. * @default true
  34616. */
  34617. this.isVector2Uniform = true;
  34618. this.boundary = 8;
  34619. this.itemSize = 2;
  34620. }
  34621. }
  34622. /**
  34623. * Represents a Vector3 uniform.
  34624. *
  34625. * @private
  34626. * @augments Uniform
  34627. */
  34628. class Vector3Uniform extends Uniform {
  34629. /**
  34630. * Constructs a new Number uniform.
  34631. *
  34632. * @param {string} name - The uniform's name.
  34633. * @param {Vector3} value - The uniform's value.
  34634. */
  34635. constructor( name, value = new Vector3() ) {
  34636. super( name, value );
  34637. /**
  34638. * This flag can be used for type testing.
  34639. *
  34640. * @type {boolean}
  34641. * @readonly
  34642. * @default true
  34643. */
  34644. this.isVector3Uniform = true;
  34645. this.boundary = 16;
  34646. this.itemSize = 3;
  34647. }
  34648. }
  34649. /**
  34650. * Represents a Vector4 uniform.
  34651. *
  34652. * @private
  34653. * @augments Uniform
  34654. */
  34655. class Vector4Uniform extends Uniform {
  34656. /**
  34657. * Constructs a new Number uniform.
  34658. *
  34659. * @param {string} name - The uniform's name.
  34660. * @param {Vector4} value - The uniform's value.
  34661. */
  34662. constructor( name, value = new Vector4() ) {
  34663. super( name, value );
  34664. /**
  34665. * This flag can be used for type testing.
  34666. *
  34667. * @type {boolean}
  34668. * @readonly
  34669. * @default true
  34670. */
  34671. this.isVector4Uniform = true;
  34672. this.boundary = 16;
  34673. this.itemSize = 4;
  34674. }
  34675. }
  34676. /**
  34677. * Represents a Color uniform.
  34678. *
  34679. * @private
  34680. * @augments Uniform
  34681. */
  34682. class ColorUniform extends Uniform {
  34683. /**
  34684. * Constructs a new Number uniform.
  34685. *
  34686. * @param {string} name - The uniform's name.
  34687. * @param {Color} value - The uniform's value.
  34688. */
  34689. constructor( name, value = new Color() ) {
  34690. super( name, value );
  34691. /**
  34692. * This flag can be used for type testing.
  34693. *
  34694. * @type {boolean}
  34695. * @readonly
  34696. * @default true
  34697. */
  34698. this.isColorUniform = true;
  34699. this.boundary = 16;
  34700. this.itemSize = 3;
  34701. }
  34702. }
  34703. /**
  34704. * Represents a Matrix2 uniform.
  34705. *
  34706. * @private
  34707. * @augments Uniform
  34708. */
  34709. class Matrix2Uniform extends Uniform {
  34710. /**
  34711. * Constructs a new Number uniform.
  34712. *
  34713. * @param {string} name - The uniform's name.
  34714. * @param {Matrix2} value - The uniform's value.
  34715. */
  34716. constructor( name, value = new Matrix2() ) {
  34717. super( name, value );
  34718. /**
  34719. * This flag can be used for type testing.
  34720. *
  34721. * @type {boolean}
  34722. * @readonly
  34723. * @default true
  34724. */
  34725. this.isMatrix2Uniform = true;
  34726. this.boundary = 8;
  34727. this.itemSize = 4;
  34728. }
  34729. }
  34730. /**
  34731. * Represents a Matrix3 uniform.
  34732. *
  34733. * @private
  34734. * @augments Uniform
  34735. */
  34736. class Matrix3Uniform extends Uniform {
  34737. /**
  34738. * Constructs a new Number uniform.
  34739. *
  34740. * @param {string} name - The uniform's name.
  34741. * @param {Matrix3} value - The uniform's value.
  34742. */
  34743. constructor( name, value = new Matrix3() ) {
  34744. super( name, value );
  34745. /**
  34746. * This flag can be used for type testing.
  34747. *
  34748. * @type {boolean}
  34749. * @readonly
  34750. * @default true
  34751. */
  34752. this.isMatrix3Uniform = true;
  34753. this.boundary = 48;
  34754. this.itemSize = 12;
  34755. }
  34756. }
  34757. /**
  34758. * Represents a Matrix4 uniform.
  34759. *
  34760. * @private
  34761. * @augments Uniform
  34762. */
  34763. class Matrix4Uniform extends Uniform {
  34764. /**
  34765. * Constructs a new Number uniform.
  34766. *
  34767. * @param {string} name - The uniform's name.
  34768. * @param {Matrix4} value - The uniform's value.
  34769. */
  34770. constructor( name, value = new Matrix4() ) {
  34771. super( name, value );
  34772. /**
  34773. * This flag can be used for type testing.
  34774. *
  34775. * @type {boolean}
  34776. * @readonly
  34777. * @default true
  34778. */
  34779. this.isMatrix4Uniform = true;
  34780. this.boundary = 64;
  34781. this.itemSize = 16;
  34782. }
  34783. }
  34784. /**
  34785. * A special form of Number uniform binding type.
  34786. * It's value is managed by a node object.
  34787. *
  34788. * @private
  34789. * @augments NumberUniform
  34790. */
  34791. class NumberNodeUniform extends NumberUniform {
  34792. /**
  34793. * Constructs a new node-based Number uniform.
  34794. *
  34795. * @param {NodeUniform} nodeUniform - The node uniform.
  34796. */
  34797. constructor( nodeUniform ) {
  34798. super( nodeUniform.name, nodeUniform.value );
  34799. /**
  34800. * The node uniform.
  34801. *
  34802. * @type {NodeUniform}
  34803. */
  34804. this.nodeUniform = nodeUniform;
  34805. }
  34806. /**
  34807. * Overwritten to return the value of the node uniform.
  34808. *
  34809. * @return {number} The value.
  34810. */
  34811. getValue() {
  34812. return this.nodeUniform.value;
  34813. }
  34814. /**
  34815. * Returns the node uniform data type.
  34816. *
  34817. * @return {string} The data type.
  34818. */
  34819. getType() {
  34820. return this.nodeUniform.type;
  34821. }
  34822. }
  34823. /**
  34824. * A special form of Vector2 uniform binding type.
  34825. * It's value is managed by a node object.
  34826. *
  34827. * @private
  34828. * @augments Vector2Uniform
  34829. */
  34830. class Vector2NodeUniform extends Vector2Uniform {
  34831. /**
  34832. * Constructs a new node-based Vector2 uniform.
  34833. *
  34834. * @param {NodeUniform} nodeUniform - The node uniform.
  34835. */
  34836. constructor( nodeUniform ) {
  34837. super( nodeUniform.name, nodeUniform.value );
  34838. /**
  34839. * The node uniform.
  34840. *
  34841. * @type {NodeUniform}
  34842. */
  34843. this.nodeUniform = nodeUniform;
  34844. }
  34845. /**
  34846. * Overwritten to return the value of the node uniform.
  34847. *
  34848. * @return {Vector2} The value.
  34849. */
  34850. getValue() {
  34851. return this.nodeUniform.value;
  34852. }
  34853. /**
  34854. * Returns the node uniform data type.
  34855. *
  34856. * @return {string} The data type.
  34857. */
  34858. getType() {
  34859. return this.nodeUniform.type;
  34860. }
  34861. }
  34862. /**
  34863. * A special form of Vector3 uniform binding type.
  34864. * It's value is managed by a node object.
  34865. *
  34866. * @private
  34867. * @augments Vector3Uniform
  34868. */
  34869. class Vector3NodeUniform extends Vector3Uniform {
  34870. /**
  34871. * Constructs a new node-based Vector3 uniform.
  34872. *
  34873. * @param {NodeUniform} nodeUniform - The node uniform.
  34874. */
  34875. constructor( nodeUniform ) {
  34876. super( nodeUniform.name, nodeUniform.value );
  34877. /**
  34878. * The node uniform.
  34879. *
  34880. * @type {NodeUniform}
  34881. */
  34882. this.nodeUniform = nodeUniform;
  34883. }
  34884. /**
  34885. * Overwritten to return the value of the node uniform.
  34886. *
  34887. * @return {Vector3} The value.
  34888. */
  34889. getValue() {
  34890. return this.nodeUniform.value;
  34891. }
  34892. /**
  34893. * Returns the node uniform data type.
  34894. *
  34895. * @return {string} The data type.
  34896. */
  34897. getType() {
  34898. return this.nodeUniform.type;
  34899. }
  34900. }
  34901. /**
  34902. * A special form of Vector4 uniform binding type.
  34903. * It's value is managed by a node object.
  34904. *
  34905. * @private
  34906. * @augments Vector4Uniform
  34907. */
  34908. class Vector4NodeUniform extends Vector4Uniform {
  34909. /**
  34910. * Constructs a new node-based Vector4 uniform.
  34911. *
  34912. * @param {NodeUniform} nodeUniform - The node uniform.
  34913. */
  34914. constructor( nodeUniform ) {
  34915. super( nodeUniform.name, nodeUniform.value );
  34916. /**
  34917. * The node uniform.
  34918. *
  34919. * @type {NodeUniform}
  34920. */
  34921. this.nodeUniform = nodeUniform;
  34922. }
  34923. /**
  34924. * Overwritten to return the value of the node uniform.
  34925. *
  34926. * @return {Vector4} The value.
  34927. */
  34928. getValue() {
  34929. return this.nodeUniform.value;
  34930. }
  34931. /**
  34932. * Returns the node uniform data type.
  34933. *
  34934. * @return {string} The data type.
  34935. */
  34936. getType() {
  34937. return this.nodeUniform.type;
  34938. }
  34939. }
  34940. /**
  34941. * A special form of Color uniform binding type.
  34942. * It's value is managed by a node object.
  34943. *
  34944. * @private
  34945. * @augments ColorUniform
  34946. */
  34947. class ColorNodeUniform extends ColorUniform {
  34948. /**
  34949. * Constructs a new node-based Color uniform.
  34950. *
  34951. * @param {NodeUniform} nodeUniform - The node uniform.
  34952. */
  34953. constructor( nodeUniform ) {
  34954. super( nodeUniform.name, nodeUniform.value );
  34955. /**
  34956. * The node uniform.
  34957. *
  34958. * @type {NodeUniform}
  34959. */
  34960. this.nodeUniform = nodeUniform;
  34961. }
  34962. /**
  34963. * Overwritten to return the value of the node uniform.
  34964. *
  34965. * @return {Color} The value.
  34966. */
  34967. getValue() {
  34968. return this.nodeUniform.value;
  34969. }
  34970. /**
  34971. * Returns the node uniform data type.
  34972. *
  34973. * @return {string} The data type.
  34974. */
  34975. getType() {
  34976. return this.nodeUniform.type;
  34977. }
  34978. }
  34979. /**
  34980. * A special form of Matrix2 uniform binding type.
  34981. * It's value is managed by a node object.
  34982. *
  34983. * @private
  34984. * @augments Matrix2Uniform
  34985. */
  34986. class Matrix2NodeUniform extends Matrix2Uniform {
  34987. /**
  34988. * Constructs a new node-based Matrix2 uniform.
  34989. *
  34990. * @param {NodeUniform} nodeUniform - The node uniform.
  34991. */
  34992. constructor( nodeUniform ) {
  34993. super( nodeUniform.name, nodeUniform.value );
  34994. /**
  34995. * The node uniform.
  34996. *
  34997. * @type {NodeUniform}
  34998. */
  34999. this.nodeUniform = nodeUniform;
  35000. }
  35001. /**
  35002. * Overwritten to return the value of the node uniform.
  35003. *
  35004. * @return {Matrix2} The value.
  35005. */
  35006. getValue() {
  35007. return this.nodeUniform.value;
  35008. }
  35009. /**
  35010. * Returns the node uniform data type.
  35011. *
  35012. * @return {string} The data type.
  35013. */
  35014. getType() {
  35015. return this.nodeUniform.type;
  35016. }
  35017. }
  35018. /**
  35019. * A special form of Matrix3 uniform binding type.
  35020. * It's value is managed by a node object.
  35021. *
  35022. * @private
  35023. * @augments Matrix3Uniform
  35024. */
  35025. class Matrix3NodeUniform extends Matrix3Uniform {
  35026. /**
  35027. * Constructs a new node-based Matrix3 uniform.
  35028. *
  35029. * @param {NodeUniform} nodeUniform - The node uniform.
  35030. */
  35031. constructor( nodeUniform ) {
  35032. super( nodeUniform.name, nodeUniform.value );
  35033. /**
  35034. * The node uniform.
  35035. *
  35036. * @type {NodeUniform}
  35037. */
  35038. this.nodeUniform = nodeUniform;
  35039. }
  35040. /**
  35041. * Overwritten to return the value of the node uniform.
  35042. *
  35043. * @return {Matrix3} The value.
  35044. */
  35045. getValue() {
  35046. return this.nodeUniform.value;
  35047. }
  35048. /**
  35049. * Returns the node uniform data type.
  35050. *
  35051. * @return {string} The data type.
  35052. */
  35053. getType() {
  35054. return this.nodeUniform.type;
  35055. }
  35056. }
  35057. /**
  35058. * A special form of Matrix4 uniform binding type.
  35059. * It's value is managed by a node object.
  35060. *
  35061. * @private
  35062. * @augments Matrix4Uniform
  35063. */
  35064. class Matrix4NodeUniform extends Matrix4Uniform {
  35065. /**
  35066. * Constructs a new node-based Matrix4 uniform.
  35067. *
  35068. * @param {NodeUniform} nodeUniform - The node uniform.
  35069. */
  35070. constructor( nodeUniform ) {
  35071. super( nodeUniform.name, nodeUniform.value );
  35072. /**
  35073. * The node uniform.
  35074. *
  35075. * @type {NodeUniform}
  35076. */
  35077. this.nodeUniform = nodeUniform;
  35078. }
  35079. /**
  35080. * Overwritten to return the value of the node uniform.
  35081. *
  35082. * @return {Matrix4} The value.
  35083. */
  35084. getValue() {
  35085. return this.nodeUniform.value;
  35086. }
  35087. /**
  35088. * Returns the node uniform data type.
  35089. *
  35090. * @return {string} The data type.
  35091. */
  35092. getType() {
  35093. return this.nodeUniform.type;
  35094. }
  35095. }
  35096. let _id$5 = 0;
  35097. const _bindingGroupsCache = new WeakMap();
  35098. const sharedNodeData = new WeakMap();
  35099. const typeFromArray = new Map( [
  35100. [ Int8Array, 'int' ],
  35101. [ Int16Array, 'int' ],
  35102. [ Int32Array, 'int' ],
  35103. [ Uint8Array, 'uint' ],
  35104. [ Uint16Array, 'uint' ],
  35105. [ Uint32Array, 'uint' ],
  35106. [ Float32Array, 'float' ]
  35107. ] );
  35108. const toFloat = ( value ) => {
  35109. if ( /e/g.test( value ) ) {
  35110. return String( value ).replace( /\+/g, '' );
  35111. } else {
  35112. value = Number( value );
  35113. return value + ( value % 1 ? '' : '.0' );
  35114. }
  35115. };
  35116. /**
  35117. * Base class for builders which generate a shader program based
  35118. * on a 3D object and its node material definition.
  35119. */
  35120. class NodeBuilder {
  35121. /**
  35122. * Constructs a new node builder.
  35123. *
  35124. * @param {Object3D} object - The 3D object.
  35125. * @param {Renderer} renderer - The current renderer.
  35126. * @param {NodeParser} parser - A reference to a node parser.
  35127. */
  35128. constructor( object, renderer, parser ) {
  35129. /**
  35130. * The 3D object.
  35131. *
  35132. * @type {Object3D}
  35133. */
  35134. this.object = object;
  35135. /**
  35136. * The material of the 3D object.
  35137. *
  35138. * @type {?Material}
  35139. */
  35140. this.material = ( object && object.material ) || null;
  35141. /**
  35142. * The geometry of the 3D object.
  35143. *
  35144. * @type {?BufferGeometry}
  35145. */
  35146. this.geometry = ( object && object.geometry ) || null;
  35147. /**
  35148. * The current renderer.
  35149. *
  35150. * @type {Renderer}
  35151. */
  35152. this.renderer = renderer;
  35153. /**
  35154. * A reference to a node parser.
  35155. *
  35156. * @type {NodeParser}
  35157. */
  35158. this.parser = parser;
  35159. /**
  35160. * The scene the 3D object belongs to.
  35161. *
  35162. * @type {?Scene}
  35163. * @default null
  35164. */
  35165. this.scene = null;
  35166. /**
  35167. * The camera the 3D object is rendered with.
  35168. *
  35169. * @type {?Camera}
  35170. * @default null
  35171. */
  35172. this.camera = null;
  35173. /**
  35174. * A list of all nodes the builder is processing
  35175. * for this 3D object.
  35176. *
  35177. * @type {Array<Node>}
  35178. */
  35179. this.nodes = [];
  35180. /**
  35181. * A list of all nodes the builder is processing in sequential order.
  35182. *
  35183. * This is used to determine the update order of nodes, which is important for
  35184. * {@link NodeUpdateType#UPDATE_BEFORE} and {@link NodeUpdateType#UPDATE_AFTER}.
  35185. *
  35186. * @type {Array<Node>}
  35187. */
  35188. this.sequentialNodes = [];
  35189. /**
  35190. * A list of all nodes which {@link Node#update} method should be executed.
  35191. *
  35192. * @type {Array<Node>}
  35193. */
  35194. this.updateNodes = [];
  35195. /**
  35196. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  35197. *
  35198. * @type {Array<Node>}
  35199. */
  35200. this.updateBeforeNodes = [];
  35201. /**
  35202. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  35203. *
  35204. * @type {Array<Node>}
  35205. */
  35206. this.updateAfterNodes = [];
  35207. /**
  35208. * A dictionary that assigns each node to a unique hash.
  35209. *
  35210. * @type {Object<number,Node>}
  35211. */
  35212. this.hashNodes = {};
  35213. /**
  35214. * A reference to a node material observer.
  35215. *
  35216. * @type {?NodeMaterialObserver}
  35217. * @default null
  35218. */
  35219. this.observer = null;
  35220. /**
  35221. * A reference to the current lights node.
  35222. *
  35223. * @type {?LightsNode}
  35224. * @default null
  35225. */
  35226. this.lightsNode = null;
  35227. /**
  35228. * A reference to the current environment node.
  35229. *
  35230. * @type {?Node}
  35231. * @default null
  35232. */
  35233. this.environmentNode = null;
  35234. /**
  35235. * A reference to the current fog node.
  35236. *
  35237. * @type {?Node}
  35238. * @default null
  35239. */
  35240. this.fogNode = null;
  35241. /**
  35242. * The current clipping context.
  35243. *
  35244. * @type {?ClippingContext}
  35245. */
  35246. this.clippingContext = null;
  35247. /**
  35248. * The generated vertex shader.
  35249. *
  35250. * @type {?string}
  35251. */
  35252. this.vertexShader = null;
  35253. /**
  35254. * The generated fragment shader.
  35255. *
  35256. * @type {?string}
  35257. */
  35258. this.fragmentShader = null;
  35259. /**
  35260. * The generated compute shader.
  35261. *
  35262. * @type {?string}
  35263. */
  35264. this.computeShader = null;
  35265. /**
  35266. * Nodes used in the primary flow of code generation.
  35267. *
  35268. * @type {Object<string,Array<Node>>}
  35269. */
  35270. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  35271. /**
  35272. * Nodes code from `.flowNodes`.
  35273. *
  35274. * @type {Object<string,string>}
  35275. */
  35276. this.flowCode = { vertex: '', fragment: '', compute: '' };
  35277. /**
  35278. * This dictionary holds the node uniforms of the builder.
  35279. * The uniforms are maintained in an array for each shader stage.
  35280. *
  35281. * @type {Object}
  35282. */
  35283. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  35284. /**
  35285. * This dictionary holds the output structs of the builder.
  35286. * The structs are maintained in an array for each shader stage.
  35287. *
  35288. * @type {Object}
  35289. */
  35290. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  35291. /**
  35292. * This dictionary holds the types of the builder.
  35293. *
  35294. * @type {Object}
  35295. */
  35296. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  35297. /**
  35298. * This dictionary holds the bindings for each shader stage.
  35299. *
  35300. * @type {Object}
  35301. */
  35302. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  35303. /**
  35304. * This dictionary maintains the binding indices per bind group.
  35305. *
  35306. * @type {Object}
  35307. */
  35308. this.bindingsIndexes = {};
  35309. /**
  35310. * Reference to the array of bind groups.
  35311. *
  35312. * @type {?Array<BindGroup>}
  35313. */
  35314. this.bindGroups = null;
  35315. /**
  35316. * This array holds the node attributes of this builder
  35317. * created via {@link AttributeNode}.
  35318. *
  35319. * @type {Array<NodeAttribute>}
  35320. */
  35321. this.attributes = [];
  35322. /**
  35323. * This array holds the node attributes of this builder
  35324. * created via {@link BufferAttributeNode}.
  35325. *
  35326. * @type {Array<NodeAttribute>}
  35327. */
  35328. this.bufferAttributes = [];
  35329. /**
  35330. * This array holds the node varyings of this builder.
  35331. *
  35332. * @type {Array<NodeVarying>}
  35333. */
  35334. this.varyings = [];
  35335. /**
  35336. * This dictionary holds the (native) node codes of this builder.
  35337. * The codes are maintained in an array for each shader stage.
  35338. *
  35339. * @type {Object<string,Array<NodeCode>>}
  35340. */
  35341. this.codes = {};
  35342. /**
  35343. * This dictionary holds the node variables of this builder.
  35344. * The variables are maintained in an array for each shader stage.
  35345. * This dictionary is also used to count the number of variables
  35346. * according to their type (const, vars).
  35347. *
  35348. * @type {Object<string,Array<NodeVar>|number>}
  35349. */
  35350. this.vars = {};
  35351. /**
  35352. * This dictionary holds the declarations for each shader stage.
  35353. *
  35354. * @type {Object}
  35355. */
  35356. this.declarations = {};
  35357. /**
  35358. * Current code flow.
  35359. * All code generated in this stack will be stored in `.flow`.
  35360. *
  35361. * @type {{code: string}}
  35362. */
  35363. this.flow = { code: '' };
  35364. /**
  35365. * A chain of nodes.
  35366. * Used to check recursive calls in node-graph.
  35367. *
  35368. * @type {Array<Node>}
  35369. */
  35370. this.chaining = [];
  35371. /**
  35372. * The current stack.
  35373. * This reflects the current process in the code block hierarchy,
  35374. * it is useful to know if the current process is inside a conditional for example.
  35375. *
  35376. * @type {StackNode}
  35377. */
  35378. this.stack = stack();
  35379. /**
  35380. * List of stack nodes.
  35381. * The current stack hierarchy is stored in an array.
  35382. *
  35383. * @type {Array<StackNode>}
  35384. */
  35385. this.stacks = [];
  35386. /**
  35387. * A tab value. Used for shader string generation.
  35388. *
  35389. * @type {string}
  35390. * @default '\t'
  35391. */
  35392. this.tab = '\t';
  35393. /**
  35394. * Reference to the current function node.
  35395. *
  35396. * @type {?FunctionNode}
  35397. * @default null
  35398. */
  35399. this.currentFunctionNode = null;
  35400. /**
  35401. * The builder's context.
  35402. *
  35403. * @type {Object}
  35404. */
  35405. this.context = {
  35406. material: this.material
  35407. };
  35408. /**
  35409. * The builder's cache.
  35410. *
  35411. * @type {NodeCache}
  35412. */
  35413. this.cache = new NodeCache();
  35414. /**
  35415. * Since the {@link NodeBuilder#cache} might be temporarily
  35416. * overwritten by other caches, this member retains the reference
  35417. * to the builder's own cache.
  35418. *
  35419. * @type {NodeCache}
  35420. * @default this.cache
  35421. */
  35422. this.globalCache = this.cache;
  35423. this.flowsData = new WeakMap();
  35424. /**
  35425. * The current shader stage.
  35426. *
  35427. * @type {?('vertex'|'fragment'|'compute'|'any')}
  35428. */
  35429. this.shaderStage = null;
  35430. /**
  35431. * The current build stage.
  35432. *
  35433. * @type {?('setup'|'analyze'|'generate')}
  35434. */
  35435. this.buildStage = null;
  35436. /**
  35437. * The sub-build layers.
  35438. *
  35439. * @type {Array<SubBuildNode>}
  35440. * @default []
  35441. */
  35442. this.subBuildLayers = [];
  35443. /**
  35444. * The active stack nodes.
  35445. *
  35446. * @type {Array<StackNode>}
  35447. */
  35448. this.activeStacks = [];
  35449. /**
  35450. * The current sub-build TSL function(Fn).
  35451. *
  35452. * @type {?string}
  35453. * @default null
  35454. */
  35455. this.subBuildFn = null;
  35456. /**
  35457. * The current TSL function(Fn) call node.
  35458. *
  35459. * @type {?Node}
  35460. * @default null
  35461. */
  35462. this.fnCall = null;
  35463. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  35464. }
  35465. /**
  35466. * Whether the material is using flat shading or not.
  35467. *
  35468. * @returns {boolean} Whether the material is using flat shading or not.
  35469. */
  35470. isFlatShading() {
  35471. return this.material.flatShading === true || this.geometry.hasAttribute( 'normal' ) === false;
  35472. }
  35473. /**
  35474. * Whether the material is opaque or not.
  35475. *
  35476. * @return {boolean} Whether the material is opaque or not.
  35477. */
  35478. isOpaque() {
  35479. const material = this.material;
  35480. return material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false;
  35481. }
  35482. /**
  35483. * Factory method for creating an instance of {@link RenderTarget} with the given
  35484. * dimensions and options.
  35485. *
  35486. * @param {number} width - The width of the render target.
  35487. * @param {number} height - The height of the render target.
  35488. * @param {Object} options - The options of the render target.
  35489. * @return {RenderTarget} The render target.
  35490. */
  35491. createRenderTarget( width, height, options ) {
  35492. return new RenderTarget( width, height, options );
  35493. }
  35494. /**
  35495. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  35496. * dimensions and options.
  35497. *
  35498. * @param {number} size - The size of the cube render target.
  35499. * @param {Object} options - The options of the cube render target.
  35500. * @return {CubeRenderTarget} The cube render target.
  35501. */
  35502. createCubeRenderTarget( size, options ) {
  35503. return new CubeRenderTarget( size, options );
  35504. }
  35505. /**
  35506. * Whether the given node is included in the internal array of nodes or not.
  35507. *
  35508. * @param {Node} node - The node to test.
  35509. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  35510. */
  35511. includes( node ) {
  35512. return this.nodes.includes( node );
  35513. }
  35514. /**
  35515. * Returns the output struct name which is required by
  35516. * {@link OutputStructNode}.
  35517. *
  35518. * @abstract
  35519. * @return {string} The name of the output struct.
  35520. */
  35521. getOutputStructName() {}
  35522. /**
  35523. * Returns a bind group for the given group name and binding.
  35524. *
  35525. * @private
  35526. * @param {string} groupName - The group name.
  35527. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  35528. * @return {BindGroup} The bind group
  35529. */
  35530. _getBindGroup( groupName, bindings ) {
  35531. const groupNode = bindings[ 0 ].groupNode;
  35532. let sharedGroup = groupNode.shared;
  35533. if ( sharedGroup ) {
  35534. for ( let i = 1; i < bindings.length; i ++ ) {
  35535. if ( groupNode !== bindings[ i ].groupNode ) {
  35536. sharedGroup = false;
  35537. }
  35538. }
  35539. }
  35540. //
  35541. let bindGroup;
  35542. if ( sharedGroup ) {
  35543. let cacheKeyString = '';
  35544. for ( const binding of bindings ) {
  35545. if ( binding.isNodeUniformsGroup ) {
  35546. binding.uniforms.sort( ( a, b ) => a.nodeUniform.node.id - b.nodeUniform.node.id );
  35547. for ( const uniform of binding.uniforms ) {
  35548. cacheKeyString += uniform.nodeUniform.node.id;
  35549. }
  35550. } else {
  35551. cacheKeyString += binding.nodeUniform.id;
  35552. }
  35553. }
  35554. // TODO: Remove this hack ._currentRenderContext
  35555. const currentContext = this.renderer._currentRenderContext || this.renderer; // use renderer as fallback until we have a compute context
  35556. let bindingGroupsCache = _bindingGroupsCache.get( currentContext );
  35557. if ( bindingGroupsCache === undefined ) {
  35558. bindingGroupsCache = new Map();
  35559. _bindingGroupsCache.set( currentContext, bindingGroupsCache );
  35560. }
  35561. //
  35562. const cacheKey = hashString( cacheKeyString );
  35563. bindGroup = bindingGroupsCache.get( cacheKey );
  35564. if ( bindGroup === undefined ) {
  35565. bindGroup = new BindGroup( groupName, bindings, this.bindingsIndexes[ groupName ].group );
  35566. bindingGroupsCache.set( cacheKey, bindGroup );
  35567. } else {
  35568. for ( let i = 0; i < bindings.length; i ++ ) {
  35569. bindGroup.bindings[ i ].visibility |= bindings[ i ].visibility;
  35570. }
  35571. }
  35572. } else {
  35573. bindGroup = new BindGroup( groupName, bindings, this.bindingsIndexes[ groupName ].group );
  35574. }
  35575. return bindGroup;
  35576. }
  35577. /**
  35578. * Returns an array of node uniform groups for the given group name and shader stage.
  35579. *
  35580. * @param {string} groupName - The group name.
  35581. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35582. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  35583. */
  35584. getBindGroupArray( groupName, shaderStage ) {
  35585. const bindings = this.bindings[ shaderStage ];
  35586. let bindGroup = bindings[ groupName ];
  35587. if ( bindGroup === undefined ) {
  35588. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  35589. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  35590. }
  35591. bindings[ groupName ] = bindGroup = [];
  35592. }
  35593. return bindGroup;
  35594. }
  35595. /**
  35596. * Returns a list bindings of all shader stages separated by groups.
  35597. *
  35598. * @return {Array<BindGroup>} The list of bindings.
  35599. */
  35600. getBindings() {
  35601. let bindingsGroups = this.bindGroups;
  35602. if ( bindingsGroups === null ) {
  35603. const groups = {};
  35604. const bindings = this.bindings;
  35605. for ( const shaderStage of shaderStages ) {
  35606. for ( const groupName in bindings[ shaderStage ] ) {
  35607. const uniforms = bindings[ shaderStage ][ groupName ];
  35608. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  35609. for ( const uniform of uniforms ) {
  35610. if ( groupUniforms.includes( uniform ) === false ) {
  35611. groupUniforms.push( uniform );
  35612. }
  35613. }
  35614. }
  35615. }
  35616. bindingsGroups = [];
  35617. for ( const groupName in groups ) {
  35618. const group = groups[ groupName ];
  35619. const bindingsGroup = this._getBindGroup( groupName, group );
  35620. bindingsGroups.push( bindingsGroup );
  35621. }
  35622. this.bindGroups = bindingsGroups;
  35623. }
  35624. return bindingsGroups;
  35625. }
  35626. /**
  35627. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  35628. */
  35629. sortBindingGroups() {
  35630. const bindingsGroups = this.getBindings();
  35631. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  35632. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  35633. const bindingGroup = bindingsGroups[ i ];
  35634. this.bindingsIndexes[ bindingGroup.name ].group = i;
  35635. bindingGroup.index = i;
  35636. }
  35637. }
  35638. /**
  35639. * The builder maintains each node in a hash-based dictionary.
  35640. * This method sets the given node (value) with the given hash (key) into this dictionary.
  35641. *
  35642. * @param {Node} node - The node to add.
  35643. * @param {number} hash - The hash of the node.
  35644. */
  35645. setHashNode( node, hash ) {
  35646. this.hashNodes[ hash ] = node;
  35647. }
  35648. /**
  35649. * Adds a node to this builder.
  35650. *
  35651. * @param {Node} node - The node to add.
  35652. */
  35653. addNode( node ) {
  35654. if ( this.nodes.includes( node ) === false ) {
  35655. this.nodes.push( node );
  35656. this.setHashNode( node, node.getHash( this ) );
  35657. }
  35658. }
  35659. /**
  35660. * It is used to add Nodes that will be used as FRAME and RENDER events,
  35661. * and need to follow a certain sequence in the calls to work correctly.
  35662. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  35663. *
  35664. * @param {Node} node - The node to add.
  35665. */
  35666. addSequentialNode( node ) {
  35667. const updateBeforeType = node.getUpdateBeforeType();
  35668. const updateAfterType = node.getUpdateAfterType();
  35669. if ( updateBeforeType !== NodeUpdateType.NONE || updateAfterType !== NodeUpdateType.NONE ) {
  35670. if ( this.sequentialNodes.includes( node ) === false ) {
  35671. this.sequentialNodes.push( node );
  35672. }
  35673. }
  35674. }
  35675. /**
  35676. * Checks the update types of nodes
  35677. */
  35678. buildUpdateNodes() {
  35679. for ( const node of this.nodes ) {
  35680. const updateType = node.getUpdateType();
  35681. if ( updateType !== NodeUpdateType.NONE ) {
  35682. this.updateNodes.push( node );
  35683. }
  35684. }
  35685. for ( const node of this.sequentialNodes ) {
  35686. const updateBeforeType = node.getUpdateBeforeType();
  35687. const updateAfterType = node.getUpdateAfterType();
  35688. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  35689. this.updateBeforeNodes.push( node );
  35690. }
  35691. if ( updateAfterType !== NodeUpdateType.NONE ) {
  35692. this.updateAfterNodes.push( node );
  35693. }
  35694. }
  35695. }
  35696. /**
  35697. * A reference the current node which is the
  35698. * last node in the chain of nodes.
  35699. *
  35700. * @type {Node}
  35701. */
  35702. get currentNode() {
  35703. return this.chaining[ this.chaining.length - 1 ];
  35704. }
  35705. /**
  35706. * Whether the given texture is filtered or not.
  35707. *
  35708. * @param {Texture} texture - The texture to check.
  35709. * @return {boolean} Whether the given texture is filtered or not.
  35710. */
  35711. isFilteredTexture( texture ) {
  35712. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  35713. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  35714. }
  35715. /**
  35716. * Returns the maximum number of bytes available for uniform buffers.
  35717. *
  35718. * @return {number} The maximum number of bytes available for uniform buffers.
  35719. */
  35720. getUniformBufferLimit() {
  35721. return 16384;
  35722. }
  35723. /**
  35724. * Adds the given node to the internal node chain.
  35725. * This is used to check recursive calls in node-graph.
  35726. *
  35727. * @param {Node} node - The node to add.
  35728. */
  35729. addChain( node ) {
  35730. /*
  35731. if ( this.chaining.indexOf( node ) !== - 1 ) {
  35732. warn( 'Recursive node: ', node );
  35733. }
  35734. */
  35735. this.chaining.push( node );
  35736. }
  35737. /**
  35738. * Removes the given node from the internal node chain.
  35739. *
  35740. * @param {Node} node - The node to remove.
  35741. */
  35742. removeChain( node ) {
  35743. const lastChain = this.chaining.pop();
  35744. if ( lastChain !== node ) {
  35745. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  35746. }
  35747. }
  35748. /**
  35749. * Returns the native shader method name for a given generic name. E.g.
  35750. * the method name `textureDimensions` matches the WGSL name but must be
  35751. * resolved to `textureSize` in GLSL.
  35752. *
  35753. * @abstract
  35754. * @param {string} method - The method name to resolve.
  35755. * @return {string} The resolved method name.
  35756. */
  35757. getMethod( method ) {
  35758. return method;
  35759. }
  35760. /**
  35761. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  35762. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  35763. *
  35764. * @abstract
  35765. * @param {string} condSnippet - The condition determining which expression gets resolved.
  35766. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  35767. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  35768. * @return {string} The resolved method name.
  35769. */
  35770. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  35771. return null;
  35772. }
  35773. /**
  35774. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  35775. *
  35776. * @param {number} hash - The hash of the node.
  35777. * @return {Node} The found node.
  35778. */
  35779. getNodeFromHash( hash ) {
  35780. return this.hashNodes[ hash ];
  35781. }
  35782. /**
  35783. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  35784. *
  35785. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  35786. * @param {Node} node - The node to add.
  35787. * @return {Node} The node.
  35788. */
  35789. addFlow( shaderStage, node ) {
  35790. this.flowNodes[ shaderStage ].push( node );
  35791. return node;
  35792. }
  35793. /**
  35794. * Sets builder's context.
  35795. *
  35796. * @param {Object} context - The context to set.
  35797. */
  35798. setContext( context ) {
  35799. this.context = context;
  35800. }
  35801. /**
  35802. * Returns the builder's current context.
  35803. *
  35804. * @return {Object} The builder's current context.
  35805. */
  35806. getContext() {
  35807. return this.context;
  35808. }
  35809. /**
  35810. * Adds context data to the builder's current context.
  35811. *
  35812. * @param {Object} context - The context to add.
  35813. * @return {Object} The previous context.
  35814. */
  35815. addContext( context ) {
  35816. const previousContext = this.getContext();
  35817. this.setContext( { ...this.context, ...context } );
  35818. return previousContext;
  35819. }
  35820. /**
  35821. * Gets a context used in shader construction that can be shared across different materials.
  35822. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  35823. *
  35824. * @return {Object} The builder's current context without material.
  35825. */
  35826. getSharedContext() {
  35827. const context = { ...this.context };
  35828. delete context.material;
  35829. delete context.getUV;
  35830. delete context.getOutput;
  35831. delete context.getTextureLevel;
  35832. delete context.getAO;
  35833. delete context.getShadow;
  35834. return context;
  35835. }
  35836. /**
  35837. * Sets builder's cache.
  35838. *
  35839. * @param {NodeCache} cache - The cache to set.
  35840. */
  35841. setCache( cache ) {
  35842. this.cache = cache;
  35843. }
  35844. /**
  35845. * Returns the builder's current cache.
  35846. *
  35847. * @return {NodeCache} The builder's current cache.
  35848. */
  35849. getCache() {
  35850. return this.cache;
  35851. }
  35852. /**
  35853. * Returns a cache for the given node.
  35854. *
  35855. * @param {Node} node - The node.
  35856. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  35857. * @return {NodeCache} The cache.
  35858. */
  35859. getCacheFromNode( node, parent = true ) {
  35860. const data = this.getDataFromNode( node );
  35861. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  35862. return data.cache;
  35863. }
  35864. /**
  35865. * Whether the requested feature is available or not.
  35866. *
  35867. * @abstract
  35868. * @param {string} name - The requested feature.
  35869. * @return {boolean} Whether the requested feature is supported or not.
  35870. */
  35871. isAvailable( /*name*/ ) {
  35872. return false;
  35873. }
  35874. /**
  35875. * Returns the vertexIndex input variable as a native shader string.
  35876. *
  35877. * @abstract
  35878. * @return {string} The instanceIndex shader string.
  35879. */
  35880. getVertexIndex() {
  35881. warn( 'Abstract function.' );
  35882. }
  35883. /**
  35884. * Contextually returns either the vertex stage instance index builtin
  35885. * or the linearized index of an compute invocation within a grid of workgroups.
  35886. *
  35887. * @abstract
  35888. * @return {string} The instanceIndex shader string.
  35889. */
  35890. getInstanceIndex() {
  35891. warn( 'Abstract function.' );
  35892. }
  35893. /**
  35894. * Returns the drawIndex input variable as a native shader string.
  35895. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  35896. *
  35897. * @abstract
  35898. * @return {?string} The drawIndex shader string.
  35899. */
  35900. getDrawIndex() {
  35901. warn( 'Abstract function.' );
  35902. }
  35903. /**
  35904. * Returns the frontFacing input variable as a native shader string.
  35905. *
  35906. * @abstract
  35907. * @return {string} The frontFacing shader string.
  35908. */
  35909. getFrontFacing() {
  35910. warn( 'Abstract function.' );
  35911. }
  35912. /**
  35913. * Returns the fragCoord input variable as a native shader string.
  35914. *
  35915. * @abstract
  35916. * @return {string} The fragCoord shader string.
  35917. */
  35918. getFragCoord() {
  35919. warn( 'Abstract function.' );
  35920. }
  35921. /**
  35922. * Whether to flip texture data along its vertical axis or not. WebGL needs
  35923. * this method evaluate to `true`, WebGPU to `false`.
  35924. *
  35925. * @abstract
  35926. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  35927. */
  35928. isFlipY() {
  35929. return false;
  35930. }
  35931. /**
  35932. * Calling this method increases the usage count for the given node by one.
  35933. *
  35934. * @param {Node} node - The node to increase the usage count for.
  35935. * @return {number} The updated usage count.
  35936. */
  35937. increaseUsage( node ) {
  35938. const nodeData = this.getDataFromNode( node );
  35939. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  35940. return nodeData.usageCount;
  35941. }
  35942. /**
  35943. * Generates a texture sample shader string for the given texture data.
  35944. *
  35945. * @abstract
  35946. * @param {Texture} texture - The texture.
  35947. * @param {string} textureProperty - The texture property name.
  35948. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  35949. * @return {string} The generated shader string.
  35950. */
  35951. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  35952. warn( 'Abstract function.' );
  35953. }
  35954. /**
  35955. * Generates a texture LOD shader string for the given texture data.
  35956. *
  35957. * @abstract
  35958. * @param {Texture} texture - The texture.
  35959. * @param {string} textureProperty - The texture property name.
  35960. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  35961. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  35962. * @param {string} levelSnippet - Snippet defining the mip level.
  35963. * @return {string} The generated shader string.
  35964. */
  35965. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  35966. warn( 'Abstract function.' );
  35967. }
  35968. /**
  35969. * Generates the array declaration string.
  35970. *
  35971. * @param {string} type - The type.
  35972. * @param {?number} [count] - The count.
  35973. * @return {string} The generated value as a shader string.
  35974. */
  35975. generateArrayDeclaration( type, count ) {
  35976. return this.getType( type ) + '[ ' + count + ' ]';
  35977. }
  35978. /**
  35979. * Generates the array shader string for the given type and value.
  35980. *
  35981. * @param {string} type - The type.
  35982. * @param {?number} [count] - The count.
  35983. * @param {?Array<Node>} [values=null] - The default values.
  35984. * @return {string} The generated value as a shader string.
  35985. */
  35986. generateArray( type, count, values = null ) {
  35987. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  35988. for ( let i = 0; i < count; i ++ ) {
  35989. const value = values ? values[ i ] : null;
  35990. if ( value !== null ) {
  35991. snippet += value.build( this, type );
  35992. } else {
  35993. snippet += this.generateConst( type );
  35994. }
  35995. if ( i < count - 1 ) snippet += ', ';
  35996. }
  35997. snippet += ' )';
  35998. return snippet;
  35999. }
  36000. /**
  36001. * Generates the struct shader string.
  36002. *
  36003. * @param {string} type - The type.
  36004. * @param {Array<Object>} [membersLayout] - The count.
  36005. * @param {?Array<Node>} [values=null] - The default values.
  36006. * @return {string} The generated value as a shader string.
  36007. */
  36008. generateStruct( type, membersLayout, values = null ) {
  36009. const snippets = [];
  36010. for ( const member of membersLayout ) {
  36011. const { name, type } = member;
  36012. if ( values && values[ name ] && values[ name ].isNode ) {
  36013. snippets.push( values[ name ].build( this, type ) );
  36014. } else {
  36015. snippets.push( this.generateConst( type ) );
  36016. }
  36017. }
  36018. return type + '( ' + snippets.join( ', ' ) + ' )';
  36019. }
  36020. /**
  36021. * Generates the shader string for the given type and value.
  36022. *
  36023. * @param {string} type - The type.
  36024. * @param {?any} [value=null] - The value.
  36025. * @return {string} The generated value as a shader string.
  36026. */
  36027. generateConst( type, value = null ) {
  36028. if ( value === null ) {
  36029. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  36030. else if ( type === 'bool' ) value = false;
  36031. else if ( type === 'color' ) value = new Color();
  36032. else if ( type === 'vec2' || type === 'uvec2' || type === 'ivec2' ) value = new Vector2();
  36033. else if ( type === 'vec3' || type === 'uvec3' || type === 'ivec3' ) value = new Vector3();
  36034. else if ( type === 'vec4' || type === 'uvec4' || type === 'ivec4' ) value = new Vector4();
  36035. }
  36036. if ( type === 'float' ) return toFloat( value );
  36037. if ( type === 'int' ) return `${ Math.round( value ) }`;
  36038. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  36039. if ( type === 'bool' ) return value ? 'true' : 'false';
  36040. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  36041. const typeLength = this.getTypeLength( type );
  36042. const componentType = this.getComponentType( type );
  36043. const generateConst = value => this.generateConst( componentType, value );
  36044. if ( typeLength === 2 ) {
  36045. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  36046. } else if ( typeLength === 3 ) {
  36047. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  36048. } else if ( typeLength === 4 && type !== 'mat2' ) {
  36049. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  36050. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  36051. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  36052. } else if ( typeLength > 4 ) {
  36053. return `${ this.getType( type ) }()`;
  36054. }
  36055. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  36056. }
  36057. /**
  36058. * It might be necessary to convert certain data types to different ones
  36059. * so this method can be used to hide the conversion.
  36060. *
  36061. * @param {string} type - The type.
  36062. * @return {string} The updated type.
  36063. */
  36064. getType( type ) {
  36065. if ( type === 'color' ) return 'vec3';
  36066. return type;
  36067. }
  36068. /**
  36069. * Whether the given attribute name is defined in the geometry or not.
  36070. *
  36071. * @param {string} name - The attribute name.
  36072. * @return {boolean} Whether the given attribute name is defined in the geometry.
  36073. */
  36074. hasGeometryAttribute( name ) {
  36075. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  36076. }
  36077. /**
  36078. * Returns a node attribute for the given name and type.
  36079. *
  36080. * @param {string} name - The attribute's name.
  36081. * @param {string} type - The attribute's type.
  36082. * @return {NodeAttribute} The node attribute.
  36083. */
  36084. getAttribute( name, type ) {
  36085. const attributes = this.attributes;
  36086. // find attribute
  36087. for ( const attribute of attributes ) {
  36088. if ( attribute.name === name ) {
  36089. return attribute;
  36090. }
  36091. }
  36092. // create a new if no exist
  36093. const attribute = new NodeAttribute( name, type );
  36094. this.registerDeclaration( attribute );
  36095. attributes.push( attribute );
  36096. return attribute;
  36097. }
  36098. /**
  36099. * Returns for the given node and shader stage the property name for the shader.
  36100. *
  36101. * @param {Node} node - The node.
  36102. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36103. * @return {string} The property name.
  36104. */
  36105. getPropertyName( node/*, shaderStage*/ ) {
  36106. return node.name;
  36107. }
  36108. /**
  36109. * Whether the given type is a vector type or not.
  36110. *
  36111. * @param {string} type - The type to check.
  36112. * @return {boolean} Whether the given type is a vector type or not.
  36113. */
  36114. isVector( type ) {
  36115. return /vec\d/.test( type );
  36116. }
  36117. /**
  36118. * Whether the given type is a matrix type or not.
  36119. *
  36120. * @param {string} type - The type to check.
  36121. * @return {boolean} Whether the given type is a matrix type or not.
  36122. */
  36123. isMatrix( type ) {
  36124. return /mat\d/.test( type );
  36125. }
  36126. /**
  36127. * Whether the given type is a reference type or not.
  36128. *
  36129. * @param {string} type - The type to check.
  36130. * @return {boolean} Whether the given type is a reference type or not.
  36131. */
  36132. isReference( type ) {
  36133. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  36134. }
  36135. /**
  36136. * Checks if the given texture requires a manual conversion to the working color space.
  36137. *
  36138. * @abstract
  36139. * @param {Texture} texture - The texture to check.
  36140. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  36141. */
  36142. needsToWorkingColorSpace( /*texture*/ ) {
  36143. return false;
  36144. }
  36145. /**
  36146. * Returns the component type of a given texture.
  36147. *
  36148. * @param {Texture} texture - The texture.
  36149. * @return {string} The component type.
  36150. */
  36151. getComponentTypeFromTexture( texture ) {
  36152. const type = texture.type;
  36153. if ( texture.isDataTexture ) {
  36154. if ( type === IntType ) return 'int';
  36155. if ( type === UnsignedIntType ) return 'uint';
  36156. }
  36157. return 'float';
  36158. }
  36159. /**
  36160. * Returns the element type for a given type.
  36161. *
  36162. * @param {string} type - The type.
  36163. * @return {string} The element type.
  36164. */
  36165. getElementType( type ) {
  36166. if ( type === 'mat2' ) return 'vec2';
  36167. if ( type === 'mat3' ) return 'vec3';
  36168. if ( type === 'mat4' ) return 'vec4';
  36169. return this.getComponentType( type );
  36170. }
  36171. /**
  36172. * Returns the component type for a given type.
  36173. *
  36174. * @param {string} type - The type.
  36175. * @return {string} The component type.
  36176. */
  36177. getComponentType( type ) {
  36178. type = this.getVectorType( type );
  36179. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  36180. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  36181. if ( componentType === null ) return null;
  36182. if ( componentType[ 1 ] === 'b' ) return 'bool';
  36183. if ( componentType[ 1 ] === 'i' ) return 'int';
  36184. if ( componentType[ 1 ] === 'u' ) return 'uint';
  36185. return 'float';
  36186. }
  36187. /**
  36188. * Returns the vector type for a given type.
  36189. *
  36190. * @param {string} type - The type.
  36191. * @return {string} The vector type.
  36192. */
  36193. getVectorType( type ) {
  36194. if ( type === 'color' ) return 'vec3';
  36195. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  36196. return type;
  36197. }
  36198. /**
  36199. * Returns the data type for the given the length and component type.
  36200. *
  36201. * @param {number} length - The length.
  36202. * @param {string} [componentType='float'] - The component type.
  36203. * @return {string} The type.
  36204. */
  36205. getTypeFromLength( length, componentType = 'float' ) {
  36206. if ( length === 1 ) return componentType;
  36207. let baseType = getTypeFromLength( length );
  36208. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  36209. // fix edge case for mat2x2 being same size as vec4
  36210. if ( /mat2/.test( componentType ) === true ) {
  36211. baseType = baseType.replace( 'vec', 'mat' );
  36212. }
  36213. return prefix + baseType;
  36214. }
  36215. /**
  36216. * Returns the type for a given typed array.
  36217. *
  36218. * @param {TypedArray} array - The typed array.
  36219. * @return {string} The type.
  36220. */
  36221. getTypeFromArray( array ) {
  36222. return typeFromArray.get( array.constructor );
  36223. }
  36224. /**
  36225. * Returns the type is an integer type.
  36226. *
  36227. * @param {string} type - The type.
  36228. * @return {boolean} Whether the type is an integer type or not.
  36229. */
  36230. isInteger( type ) {
  36231. return /int|uint|(i|u)vec/.test( type );
  36232. }
  36233. /**
  36234. * Returns the type for a given buffer attribute.
  36235. *
  36236. * @param {BufferAttribute} attribute - The buffer attribute.
  36237. * @return {string} The type.
  36238. */
  36239. getTypeFromAttribute( attribute ) {
  36240. let dataAttribute = attribute;
  36241. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36242. const array = dataAttribute.array;
  36243. const itemSize = attribute.itemSize;
  36244. const normalized = attribute.normalized;
  36245. let arrayType;
  36246. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  36247. arrayType = this.getTypeFromArray( array );
  36248. }
  36249. return this.getTypeFromLength( itemSize, arrayType );
  36250. }
  36251. /**
  36252. * Returns the length for the given data type.
  36253. *
  36254. * @param {string} type - The data type.
  36255. * @return {number} The length.
  36256. */
  36257. getTypeLength( type ) {
  36258. const vecType = this.getVectorType( type );
  36259. const vecNum = /vec([2-4])/.exec( vecType );
  36260. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  36261. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  36262. if ( /mat2/.test( type ) === true ) return 4;
  36263. if ( /mat3/.test( type ) === true ) return 9;
  36264. if ( /mat4/.test( type ) === true ) return 16;
  36265. return 0;
  36266. }
  36267. /**
  36268. * Returns the vector type for a given matrix type.
  36269. *
  36270. * @param {string} type - The matrix type.
  36271. * @return {string} The vector type.
  36272. */
  36273. getVectorFromMatrix( type ) {
  36274. return type.replace( 'mat', 'vec' );
  36275. }
  36276. /**
  36277. * For a given type this method changes the component type to the
  36278. * given value. E.g. `vec4` should be changed to the new component type
  36279. * `uint` which results in `uvec4`.
  36280. *
  36281. * @param {string} type - The type.
  36282. * @param {string} newComponentType - The new component type.
  36283. * @return {string} The new type.
  36284. */
  36285. changeComponentType( type, newComponentType ) {
  36286. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  36287. }
  36288. /**
  36289. * Returns the integer type pendant for the given type.
  36290. *
  36291. * @param {string} type - The type.
  36292. * @return {string} The integer type.
  36293. */
  36294. getIntegerType( type ) {
  36295. const componentType = this.getComponentType( type );
  36296. if ( componentType === 'int' || componentType === 'uint' ) return type;
  36297. return this.changeComponentType( type, 'int' );
  36298. }
  36299. /**
  36300. * Adds an active stack to the internal stack.
  36301. *
  36302. * @param {StackNode} stack - The stack node to add.
  36303. */
  36304. setActiveStack( stack ) {
  36305. this.activeStacks.push( stack );
  36306. }
  36307. /**
  36308. * Removes the active stack from the internal stack.
  36309. *
  36310. * @param {StackNode} stack - The stack node to remove.
  36311. */
  36312. removeActiveStack( stack ) {
  36313. if ( this.activeStacks[ this.activeStacks.length - 1 ] === stack ) {
  36314. this.activeStacks.pop();
  36315. } else {
  36316. throw new Error( 'NodeBuilder: Invalid active stack removal.' );
  36317. }
  36318. }
  36319. /**
  36320. * Returns the active stack.
  36321. *
  36322. * @return {StackNode} The active stack.
  36323. */
  36324. getActiveStack() {
  36325. return this.activeStacks[ this.activeStacks.length - 1 ];
  36326. }
  36327. /**
  36328. * Returns the base stack.
  36329. *
  36330. * @return {StackNode} The base stack.
  36331. */
  36332. getBaseStack() {
  36333. return this.activeStacks[ 0 ];
  36334. }
  36335. /**
  36336. * Adds a stack node to the internal stack.
  36337. *
  36338. * @return {StackNode} The added stack node.
  36339. */
  36340. addStack() {
  36341. this.stack = stack( this.stack );
  36342. const previousStack = getCurrentStack();
  36343. this.stacks.push( previousStack );
  36344. setCurrentStack( this.stack );
  36345. return this.stack;
  36346. }
  36347. /**
  36348. * Removes the last stack node from the internal stack.
  36349. *
  36350. * @return {StackNode} The removed stack node.
  36351. */
  36352. removeStack() {
  36353. const lastStack = this.stack;
  36354. for ( const node of lastStack.nodes ) {
  36355. const nodeData = this.getDataFromNode( node );
  36356. nodeData.stack = lastStack;
  36357. }
  36358. this.stack = lastStack.parent;
  36359. setCurrentStack( this.stacks.pop() );
  36360. return lastStack;
  36361. }
  36362. /**
  36363. * The builder maintains (cached) data for each node during the building process. This method
  36364. * can be used to get these data for a specific shader stage and cache.
  36365. *
  36366. * @param {Node} node - The node to get the data for.
  36367. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36368. * @param {?NodeCache} cache - An optional cache.
  36369. * @return {Object} The node data.
  36370. */
  36371. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  36372. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  36373. let nodeData = cache.getData( node );
  36374. if ( nodeData === undefined ) {
  36375. nodeData = {};
  36376. cache.setData( node, nodeData );
  36377. }
  36378. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  36379. //
  36380. let data = nodeData[ shaderStage ];
  36381. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  36382. const subBuild = this.getClosestSubBuild( subBuilds );
  36383. if ( subBuild ) {
  36384. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  36385. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  36386. data.subBuilds = subBuilds;
  36387. }
  36388. return data;
  36389. }
  36390. /**
  36391. * Returns the properties for the given node and shader stage.
  36392. *
  36393. * Properties are typically used within a build stage to reference a node's
  36394. * child node or nodes manually assigned to the properties in a separate build stage.
  36395. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  36396. * to the current node's properties in the setup stage and building those properties in the generate stage.
  36397. *
  36398. * @param {Node} node - The node to get the properties for.
  36399. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  36400. * @return {Object} The node properties.
  36401. */
  36402. getNodeProperties( node, shaderStage = 'any' ) {
  36403. const nodeData = this.getDataFromNode( node, shaderStage );
  36404. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  36405. }
  36406. /**
  36407. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  36408. *
  36409. * @param {BufferAttributeNode} node - The buffer attribute node.
  36410. * @param {string} type - The node type.
  36411. * @return {NodeAttribute} The node attribute.
  36412. */
  36413. getBufferAttributeFromNode( node, type ) {
  36414. const nodeData = this.getDataFromNode( node, 'vertex' );
  36415. let bufferAttribute = nodeData.bufferAttribute;
  36416. if ( bufferAttribute === undefined ) {
  36417. const index = this.uniforms.index ++;
  36418. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  36419. this.bufferAttributes.push( bufferAttribute );
  36420. nodeData.bufferAttribute = bufferAttribute;
  36421. }
  36422. return bufferAttribute;
  36423. }
  36424. /**
  36425. * Returns an instance of {@link StructType} for the given struct name and shader stage
  36426. * or null if not found.
  36427. *
  36428. * @param {string} name - The name of the struct.
  36429. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36430. * @return {?StructType} The struct type or null if not found.
  36431. */
  36432. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  36433. return this.types[ shaderStage ][ name ] || null;
  36434. }
  36435. /**
  36436. * Returns an instance of {@link StructType} for the given output struct node.
  36437. *
  36438. * @param {OutputStructNode} node - The output struct node.
  36439. * @param {Array<Object>} membersLayout - The output struct types.
  36440. * @param {?string} [name=null] - The name of the struct.
  36441. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36442. * @return {StructType} The struct type attribute.
  36443. */
  36444. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  36445. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36446. let structType = nodeData.structType;
  36447. if ( structType === undefined ) {
  36448. const index = this.structs.index ++;
  36449. if ( name === null ) name = 'StructType' + index;
  36450. structType = new StructType( name, membersLayout );
  36451. this.structs[ shaderStage ].push( structType );
  36452. this.types[ shaderStage ][ name ] = node;
  36453. nodeData.structType = structType;
  36454. }
  36455. return structType;
  36456. }
  36457. /**
  36458. * Returns an instance of {@link StructType} for the given output struct node.
  36459. *
  36460. * @param {OutputStructNode} node - The output struct node.
  36461. * @param {Array<Object>} membersLayout - The output struct types.
  36462. * @return {StructType} The struct type attribute.
  36463. */
  36464. getOutputStructTypeFromNode( node, membersLayout ) {
  36465. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  36466. structType.output = true;
  36467. return structType;
  36468. }
  36469. /**
  36470. * Returns an instance of {@link NodeUniform} for the given uniform node.
  36471. *
  36472. * @param {UniformNode} node - The uniform node.
  36473. * @param {string} type - The uniform type.
  36474. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36475. * @param {?string} name - The name of the uniform.
  36476. * @return {NodeUniform} The node uniform.
  36477. */
  36478. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  36479. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36480. let nodeUniform = nodeData.uniform;
  36481. if ( nodeUniform === undefined ) {
  36482. const index = this.uniforms.index ++;
  36483. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  36484. this.uniforms[ shaderStage ].push( nodeUniform );
  36485. this.registerDeclaration( nodeUniform );
  36486. nodeData.uniform = nodeUniform;
  36487. }
  36488. return nodeUniform;
  36489. }
  36490. /**
  36491. * Returns an instance of {@link NodeVar} for the given variable node.
  36492. *
  36493. * @param {VarNode} node - The variable node.
  36494. * @param {?string} name - The variable's name.
  36495. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  36496. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36497. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  36498. *
  36499. * @return {NodeVar} The node variable.
  36500. */
  36501. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  36502. const nodeData = this.getDataFromNode( node, shaderStage );
  36503. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  36504. let nodeVar = nodeData[ subBuildVariable ];
  36505. if ( nodeVar === undefined ) {
  36506. const idNS = readOnly ? '_const' : '_var';
  36507. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  36508. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  36509. if ( name === null ) {
  36510. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  36511. this.vars[ idNS ] ++;
  36512. }
  36513. //
  36514. if ( subBuildVariable !== 'variable' ) {
  36515. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36516. }
  36517. //
  36518. const count = node.getArrayCount( this );
  36519. nodeVar = new NodeVar( name, type, readOnly, count );
  36520. if ( ! readOnly ) {
  36521. vars.push( nodeVar );
  36522. }
  36523. this.registerDeclaration( nodeVar );
  36524. nodeData[ subBuildVariable ] = nodeVar;
  36525. }
  36526. return nodeVar;
  36527. }
  36528. /**
  36529. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  36530. *
  36531. * @param {Node} node - The varying node.
  36532. * @return {boolean} Returns true if deterministic.
  36533. */
  36534. isDeterministic( node ) {
  36535. if ( node.isMathNode ) {
  36536. return this.isDeterministic( node.aNode ) &&
  36537. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  36538. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  36539. } else if ( node.isOperatorNode ) {
  36540. return this.isDeterministic( node.aNode ) &&
  36541. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  36542. } else if ( node.isArrayNode ) {
  36543. if ( node.values !== null ) {
  36544. for ( const n of node.values ) {
  36545. if ( ! this.isDeterministic( n ) ) {
  36546. return false;
  36547. }
  36548. }
  36549. }
  36550. return true;
  36551. } else if ( node.isConstNode ) {
  36552. return true;
  36553. }
  36554. return false;
  36555. }
  36556. /**
  36557. * Returns an instance of {@link NodeVarying} for the given varying node.
  36558. *
  36559. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  36560. * @param {?string} name - The varying's name.
  36561. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  36562. * @param {?string} interpolationType - The interpolation type of the varying.
  36563. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  36564. * @return {NodeVar} The node varying.
  36565. */
  36566. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  36567. const nodeData = this.getDataFromNode( node, 'any' );
  36568. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  36569. let nodeVarying = nodeData[ subBuildVarying ];
  36570. if ( nodeVarying === undefined ) {
  36571. const varyings = this.varyings;
  36572. const index = varyings.length;
  36573. if ( name === null ) name = 'nodeVarying' + index;
  36574. //
  36575. if ( subBuildVarying !== 'varying' ) {
  36576. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36577. }
  36578. //
  36579. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  36580. varyings.push( nodeVarying );
  36581. this.registerDeclaration( nodeVarying );
  36582. nodeData[ subBuildVarying ] = nodeVarying;
  36583. }
  36584. return nodeVarying;
  36585. }
  36586. /**
  36587. * Registers a node declaration in the current shader stage.
  36588. *
  36589. * @param {Object} node - The node to be registered.
  36590. */
  36591. registerDeclaration( node ) {
  36592. const shaderStage = this.shaderStage;
  36593. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  36594. const property = this.getPropertyName( node );
  36595. let index = 1;
  36596. let name = property;
  36597. // Automatically renames the property if the name is already in use.
  36598. while ( declarations[ name ] !== undefined ) {
  36599. name = property + '_' + index ++;
  36600. }
  36601. if ( index > 1 ) {
  36602. node.name = name;
  36603. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  36604. }
  36605. declarations[ name ] = node;
  36606. }
  36607. /**
  36608. * Returns an instance of {@link NodeCode} for the given code node.
  36609. *
  36610. * @param {CodeNode} node - The code node.
  36611. * @param {string} type - The node type.
  36612. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36613. * @return {NodeCode} The node code.
  36614. */
  36615. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  36616. const nodeData = this.getDataFromNode( node );
  36617. let nodeCode = nodeData.code;
  36618. if ( nodeCode === undefined ) {
  36619. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  36620. const index = codes.length;
  36621. nodeCode = new NodeCode( 'nodeCode' + index, type );
  36622. codes.push( nodeCode );
  36623. nodeData.code = nodeCode;
  36624. }
  36625. return nodeCode;
  36626. }
  36627. /**
  36628. * Adds a code flow based on the code-block hierarchy.
  36629. * This is used so that code-blocks like If,Else create their variables locally if the Node
  36630. * is only used inside one of these conditionals in the current shader stage.
  36631. *
  36632. * @param {Node} node - The node to add.
  36633. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  36634. */
  36635. addFlowCodeHierarchy( node, nodeBlock ) {
  36636. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  36637. let needsFlowCode = true;
  36638. let nodeBlockHierarchy = nodeBlock;
  36639. while ( nodeBlockHierarchy ) {
  36640. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  36641. needsFlowCode = false;
  36642. break;
  36643. }
  36644. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  36645. }
  36646. if ( needsFlowCode ) {
  36647. for ( const flowCode of flowCodes ) {
  36648. this.addLineFlowCode( flowCode );
  36649. }
  36650. }
  36651. }
  36652. /**
  36653. * Add a inline-code to the current flow code-block.
  36654. *
  36655. * @param {Node} node - The node to add.
  36656. * @param {string} code - The code to add.
  36657. * @param {Node} nodeBlock - Current ConditionalNode
  36658. */
  36659. addLineFlowCodeBlock( node, code, nodeBlock ) {
  36660. const nodeData = this.getDataFromNode( node );
  36661. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  36662. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  36663. flowCodes.push( code );
  36664. codeBlock.set( nodeBlock, true );
  36665. }
  36666. /**
  36667. * Add a inline-code to the current flow.
  36668. *
  36669. * @param {string} code - The code to add.
  36670. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  36671. * @return {NodeBuilder} A reference to this node builder.
  36672. */
  36673. addLineFlowCode( code, node = null ) {
  36674. if ( code === '' ) return this;
  36675. if ( node !== null && this.context.nodeBlock ) {
  36676. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  36677. }
  36678. code = this.tab + code;
  36679. if ( ! /;\s*$/.test( code ) ) {
  36680. code = code + ';\n';
  36681. }
  36682. this.flow.code += code;
  36683. return this;
  36684. }
  36685. /**
  36686. * Adds a code to the current code flow.
  36687. *
  36688. * @param {string} code - Shader code.
  36689. * @return {NodeBuilder} A reference to this node builder.
  36690. */
  36691. addFlowCode( code ) {
  36692. this.flow.code += code;
  36693. return this;
  36694. }
  36695. /**
  36696. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  36697. * Typically used in codes with If,Else.
  36698. *
  36699. * @return {NodeBuilder} A reference to this node builder.
  36700. */
  36701. addFlowTab() {
  36702. this.tab += '\t';
  36703. return this;
  36704. }
  36705. /**
  36706. * Removes a tab.
  36707. *
  36708. * @return {NodeBuilder} A reference to this node builder.
  36709. */
  36710. removeFlowTab() {
  36711. this.tab = this.tab.slice( 0, -1 );
  36712. return this;
  36713. }
  36714. /**
  36715. * Gets the current flow data based on a Node.
  36716. *
  36717. * @param {Node} node - Node that the flow was started.
  36718. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36719. * @return {Object} The flow data.
  36720. */
  36721. getFlowData( node/*, shaderStage*/ ) {
  36722. return this.flowsData.get( node );
  36723. }
  36724. /**
  36725. * Executes the node flow based on a root node to generate the final shader code.
  36726. *
  36727. * @param {Node} node - The node to execute.
  36728. * @return {Object} The code flow.
  36729. */
  36730. flowNode( node ) {
  36731. const output = node.getNodeType( this );
  36732. const flowData = this.flowChildNode( node, output );
  36733. this.flowsData.set( node, flowData );
  36734. return flowData;
  36735. }
  36736. /**
  36737. * Includes a node in the current function node.
  36738. *
  36739. * @param {Node} node - The node to include.
  36740. * @returns {void}
  36741. */
  36742. addInclude( node ) {
  36743. if ( this.currentFunctionNode !== null ) {
  36744. this.currentFunctionNode.includes.push( node );
  36745. }
  36746. }
  36747. /**
  36748. * Returns the native shader operator name for a given generic name.
  36749. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  36750. *
  36751. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  36752. * @return {FunctionNode} The build function node.
  36753. */
  36754. buildFunctionNode( shaderNode ) {
  36755. const fn = new FunctionNode();
  36756. const previous = this.currentFunctionNode;
  36757. this.currentFunctionNode = fn;
  36758. fn.code = this.buildFunctionCode( shaderNode );
  36759. this.currentFunctionNode = previous;
  36760. return fn;
  36761. }
  36762. /**
  36763. * Generates a code flow based on a TSL function: Fn().
  36764. *
  36765. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  36766. * @return {Object}
  36767. */
  36768. flowShaderNode( shaderNode ) {
  36769. const layout = shaderNode.layout;
  36770. const inputs = {
  36771. [ Symbol.iterator ]() {
  36772. let index = 0;
  36773. const values = Object.values( this );
  36774. return {
  36775. next: () => ( {
  36776. value: values[ index ],
  36777. done: index ++ >= values.length
  36778. } )
  36779. };
  36780. }
  36781. };
  36782. for ( const input of layout.inputs ) {
  36783. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  36784. }
  36785. //
  36786. shaderNode.layout = null;
  36787. const callNode = shaderNode.call( inputs );
  36788. const flowData = this.flowStagesNode( callNode, layout.type );
  36789. shaderNode.layout = layout;
  36790. return flowData;
  36791. }
  36792. /**
  36793. * Executes the node in a specific build stage.
  36794. *
  36795. * This function can be used to arbitrarily execute the specified build stage
  36796. * outside of the standard build process. For instance, if a node's type depends
  36797. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  36798. * can be used to execute the setup build stage and access its generated nodes
  36799. * before the standard build process begins.
  36800. *
  36801. * @param {Node} node - The node to execute.
  36802. * @param {string} buildStage - The build stage to execute the node in.
  36803. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  36804. * @return {?(Node|string)} The result of the node build.
  36805. */
  36806. flowBuildStage( node, buildStage, output = null ) {
  36807. const previousBuildStage = this.getBuildStage();
  36808. this.setBuildStage( buildStage );
  36809. const result = node.build( this, output );
  36810. this.setBuildStage( previousBuildStage );
  36811. return result;
  36812. }
  36813. /**
  36814. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  36815. *
  36816. * @param {Node} node - The node to execute.
  36817. * @param {?string} output - Expected output type. For example 'vec3'.
  36818. * @return {Object}
  36819. */
  36820. flowStagesNode( node, output = null ) {
  36821. const previousFlow = this.flow;
  36822. const previousVars = this.vars;
  36823. const previousDeclarations = this.declarations;
  36824. const previousCache = this.cache;
  36825. const previousBuildStage = this.buildStage;
  36826. const previousStack = this.stack;
  36827. const flow = {
  36828. code: ''
  36829. };
  36830. this.flow = flow;
  36831. this.vars = {};
  36832. this.declarations = {};
  36833. this.cache = new NodeCache();
  36834. this.stack = stack();
  36835. for ( const buildStage of defaultBuildStages ) {
  36836. this.setBuildStage( buildStage );
  36837. flow.result = node.build( this, output );
  36838. }
  36839. flow.vars = this.getVars( this.shaderStage );
  36840. this.flow = previousFlow;
  36841. this.vars = previousVars;
  36842. this.declarations = previousDeclarations;
  36843. this.cache = previousCache;
  36844. this.stack = previousStack;
  36845. this.setBuildStage( previousBuildStage );
  36846. return flow;
  36847. }
  36848. /**
  36849. * Returns the native shader operator name for a given generic name.
  36850. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  36851. *
  36852. * @abstract
  36853. * @param {string} op - The operator name to resolve.
  36854. * @return {?string} The resolved operator name.
  36855. */
  36856. getFunctionOperator( /* op */ ) {
  36857. return null;
  36858. }
  36859. /**
  36860. * Builds the given shader node.
  36861. *
  36862. * @abstract
  36863. * @param {ShaderNodeInternal} shaderNode - The shader node.
  36864. * @return {string} The function code.
  36865. */
  36866. buildFunctionCode( /* shaderNode */ ) {
  36867. warn( 'Abstract function.' );
  36868. }
  36869. /**
  36870. * Generates a code flow based on a child Node.
  36871. *
  36872. * @param {Node} node - The node to execute.
  36873. * @param {?string} output - Expected output type. For example 'vec3'.
  36874. * @return {Object} The code flow.
  36875. */
  36876. flowChildNode( node, output = null ) {
  36877. const previousFlow = this.flow;
  36878. const flow = {
  36879. code: ''
  36880. };
  36881. this.flow = flow;
  36882. flow.result = node.build( this, output );
  36883. this.flow = previousFlow;
  36884. return flow;
  36885. }
  36886. /**
  36887. * Executes a flow of code in a different stage.
  36888. *
  36889. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  36890. * return the value in fragment-stage even if it is being executed in an input fragment.
  36891. *
  36892. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36893. * @param {Node} node - The node to execute.
  36894. * @param {?string} output - Expected output type. For example 'vec3'.
  36895. * @param {?string} propertyName - The property name to assign the result.
  36896. * @return {?(Object|Node)} The code flow or node.build() result.
  36897. */
  36898. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  36899. const previousTab = this.tab;
  36900. const previousCache = this.cache;
  36901. const previousShaderStage = this.shaderStage;
  36902. const previousContext = this.context;
  36903. this.setShaderStage( shaderStage );
  36904. const context = { ...this.context };
  36905. delete context.nodeBlock;
  36906. this.cache = this.globalCache;
  36907. this.tab = '\t';
  36908. this.context = context;
  36909. let result = null;
  36910. if ( this.buildStage === 'generate' ) {
  36911. const flowData = this.flowChildNode( node, output );
  36912. if ( propertyName !== null ) {
  36913. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  36914. }
  36915. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  36916. result = flowData;
  36917. } else {
  36918. result = node.build( this );
  36919. }
  36920. this.setShaderStage( previousShaderStage );
  36921. this.cache = previousCache;
  36922. this.tab = previousTab;
  36923. this.context = previousContext;
  36924. return result;
  36925. }
  36926. /**
  36927. * Returns an array holding all node attributes of this node builder.
  36928. *
  36929. * @return {Array<NodeAttribute>} The node attributes of this builder.
  36930. */
  36931. getAttributesArray() {
  36932. return this.attributes.concat( this.bufferAttributes );
  36933. }
  36934. /**
  36935. * Returns the attribute definitions as a shader string for the given shader stage.
  36936. *
  36937. * @abstract
  36938. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36939. * @return {string} The attribute code section.
  36940. */
  36941. getAttributes( /*shaderStage*/ ) {
  36942. warn( 'Abstract function.' );
  36943. }
  36944. /**
  36945. * Returns the varying definitions as a shader string for the given shader stage.
  36946. *
  36947. * @abstract
  36948. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36949. * @return {string} The varying code section.
  36950. */
  36951. getVaryings( /*shaderStage*/ ) {
  36952. warn( 'Abstract function.' );
  36953. }
  36954. /**
  36955. * Returns a single variable definition as a shader string for the given variable type and name.
  36956. *
  36957. * @param {string} type - The variable's type.
  36958. * @param {string} name - The variable's name.
  36959. * @param {?number} [count=null] - The array length.
  36960. * @return {string} The shader string.
  36961. */
  36962. getVar( type, name, count = null ) {
  36963. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  36964. }
  36965. /**
  36966. * Returns the variable definitions as a shader string for the given shader stage.
  36967. *
  36968. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36969. * @return {string} The variable code section.
  36970. */
  36971. getVars( shaderStage ) {
  36972. let snippet = '';
  36973. const vars = this.vars[ shaderStage ];
  36974. if ( vars !== undefined ) {
  36975. for ( const variable of vars ) {
  36976. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  36977. }
  36978. }
  36979. return snippet;
  36980. }
  36981. /**
  36982. * Returns the uniform definitions as a shader string for the given shader stage.
  36983. *
  36984. * @abstract
  36985. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36986. * @return {string} The uniform code section.
  36987. */
  36988. getUniforms( /*shaderStage*/ ) {
  36989. warn( 'Abstract function.' );
  36990. }
  36991. /**
  36992. * Returns the native code definitions as a shader string for the given shader stage.
  36993. *
  36994. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36995. * @return {string} The native code section.
  36996. */
  36997. getCodes( shaderStage ) {
  36998. const codes = this.codes[ shaderStage ];
  36999. let code = '';
  37000. if ( codes !== undefined ) {
  37001. for ( const nodeCode of codes ) {
  37002. code += nodeCode.code + '\n';
  37003. }
  37004. }
  37005. return code;
  37006. }
  37007. /**
  37008. * Returns the hash of this node builder.
  37009. *
  37010. * @return {string} The hash.
  37011. */
  37012. getHash() {
  37013. return this.vertexShader + this.fragmentShader + this.computeShader;
  37014. }
  37015. /**
  37016. * Sets the current shader stage.
  37017. *
  37018. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  37019. */
  37020. setShaderStage( shaderStage ) {
  37021. this.shaderStage = shaderStage;
  37022. }
  37023. /**
  37024. * Returns the current shader stage.
  37025. *
  37026. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  37027. */
  37028. getShaderStage() {
  37029. return this.shaderStage;
  37030. }
  37031. /**
  37032. * Sets the current build stage.
  37033. *
  37034. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  37035. */
  37036. setBuildStage( buildStage ) {
  37037. this.buildStage = buildStage;
  37038. }
  37039. /**
  37040. * Returns the current build stage.
  37041. *
  37042. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  37043. */
  37044. getBuildStage() {
  37045. return this.buildStage;
  37046. }
  37047. /**
  37048. * Controls the code build of the shader stages.
  37049. *
  37050. * @abstract
  37051. */
  37052. buildCode() {
  37053. warn( 'Abstract function.' );
  37054. }
  37055. /**
  37056. * Returns the current sub-build layer.
  37057. *
  37058. * @return {SubBuildNode} The current sub-build layers.
  37059. */
  37060. get subBuild() {
  37061. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  37062. }
  37063. /**
  37064. * Adds a sub-build layer to the node builder.
  37065. *
  37066. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  37067. */
  37068. addSubBuild( subBuild ) {
  37069. this.subBuildLayers.push( subBuild );
  37070. }
  37071. /**
  37072. * Removes the last sub-build layer from the node builder.
  37073. *
  37074. * @return {SubBuildNode} The removed sub-build layer.
  37075. */
  37076. removeSubBuild() {
  37077. return this.subBuildLayers.pop();
  37078. }
  37079. /**
  37080. * Returns the closest sub-build layer for the given data.
  37081. *
  37082. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  37083. * @return {?string} The closest sub-build name or null if none found.
  37084. */
  37085. getClosestSubBuild( data ) {
  37086. let subBuilds;
  37087. if ( data && data.isNode ) {
  37088. if ( data.isShaderCallNodeInternal ) {
  37089. subBuilds = data.shaderNode.subBuilds;
  37090. } else if ( data.isStackNode ) {
  37091. subBuilds = [ data.subBuild ];
  37092. } else {
  37093. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  37094. }
  37095. } else if ( data instanceof Set ) {
  37096. subBuilds = [ ...data ];
  37097. } else {
  37098. subBuilds = data;
  37099. }
  37100. if ( ! subBuilds ) return null;
  37101. const subBuildLayers = this.subBuildLayers;
  37102. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  37103. const subBuild = subBuilds[ i ];
  37104. if ( subBuildLayers.includes( subBuild ) ) {
  37105. return subBuild;
  37106. }
  37107. }
  37108. return null;
  37109. }
  37110. /**
  37111. * Returns the output node of a sub-build layer.
  37112. *
  37113. * @param {Node} node - The node to get the output from.
  37114. * @return {string} The output node name.
  37115. */
  37116. getSubBuildOutput( node ) {
  37117. return this.getSubBuildProperty( 'outputNode', node );
  37118. }
  37119. /**
  37120. * Returns the sub-build property name for the given property and node.
  37121. *
  37122. * @param {string} [property=''] - The property name.
  37123. * @param {?Node} [node=null] - The node to get the sub-build from.
  37124. * @return {string} The sub-build property name.
  37125. */
  37126. getSubBuildProperty( property = '', node = null ) {
  37127. let subBuild;
  37128. if ( node !== null ) {
  37129. subBuild = this.getClosestSubBuild( node );
  37130. } else {
  37131. subBuild = this.subBuildFn;
  37132. }
  37133. let result;
  37134. if ( subBuild ) {
  37135. result = property ? ( subBuild + '_' + property ) : subBuild;
  37136. } else {
  37137. result = property;
  37138. }
  37139. return result;
  37140. }
  37141. /**
  37142. * Central build method which controls the build for the given object.
  37143. *
  37144. * @return {NodeBuilder} A reference to this node builder.
  37145. */
  37146. build() {
  37147. const { object, material, renderer } = this;
  37148. if ( material !== null ) {
  37149. let nodeMaterial = renderer.library.fromMaterial( material );
  37150. if ( nodeMaterial === null ) {
  37151. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  37152. nodeMaterial = new NodeMaterial();
  37153. }
  37154. nodeMaterial.build( this );
  37155. } else {
  37156. this.addFlow( 'compute', object );
  37157. }
  37158. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  37159. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  37160. // generate() -> stage 3: generate shader
  37161. for ( const buildStage of defaultBuildStages ) {
  37162. this.setBuildStage( buildStage );
  37163. if ( this.context.position && this.context.position.isNode ) {
  37164. this.flowNodeFromShaderStage( 'vertex', this.context.position );
  37165. }
  37166. for ( const shaderStage of shaderStages ) {
  37167. this.setShaderStage( shaderStage );
  37168. const flowNodes = this.flowNodes[ shaderStage ];
  37169. for ( const node of flowNodes ) {
  37170. if ( buildStage === 'generate' ) {
  37171. this.flowNode( node );
  37172. } else {
  37173. node.build( this );
  37174. }
  37175. }
  37176. }
  37177. }
  37178. this.setBuildStage( null );
  37179. this.setShaderStage( null );
  37180. // stage 4: build code for a specific output
  37181. this.buildCode();
  37182. this.buildUpdateNodes();
  37183. return this;
  37184. }
  37185. /**
  37186. * Returns shared data object for the given node.
  37187. *
  37188. * @param {Node} node - The node to get shared data from.
  37189. * @return {Object} The shared data.
  37190. */
  37191. getSharedDataFromNode( node ) {
  37192. let data = sharedNodeData.get( node );
  37193. if ( data === undefined ) {
  37194. data = {};
  37195. }
  37196. return data;
  37197. }
  37198. /**
  37199. * Returns a uniform representation which is later used for UBO generation and rendering.
  37200. *
  37201. * @param {NodeUniform} uniformNode - The uniform node.
  37202. * @param {string} type - The requested type.
  37203. * @return {Uniform} The uniform.
  37204. */
  37205. getNodeUniform( uniformNode, type ) {
  37206. const nodeData = this.getSharedDataFromNode( uniformNode );
  37207. let node = nodeData.cache;
  37208. if ( node === undefined ) {
  37209. if ( type === 'float' || type === 'int' || type === 'uint' ) node = new NumberNodeUniform( uniformNode );
  37210. else if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) node = new Vector2NodeUniform( uniformNode );
  37211. else if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) node = new Vector3NodeUniform( uniformNode );
  37212. else if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) node = new Vector4NodeUniform( uniformNode );
  37213. else if ( type === 'color' ) node = new ColorNodeUniform( uniformNode );
  37214. else if ( type === 'mat2' ) node = new Matrix2NodeUniform( uniformNode );
  37215. else if ( type === 'mat3' ) node = new Matrix3NodeUniform( uniformNode );
  37216. else if ( type === 'mat4' ) node = new Matrix4NodeUniform( uniformNode );
  37217. else {
  37218. throw new Error( `Uniform "${ type }" not implemented.` );
  37219. }
  37220. nodeData.cache = node;
  37221. }
  37222. return node;
  37223. }
  37224. /**
  37225. * Formats the given shader snippet from a given type into another one. E.g.
  37226. * this method might be used to convert a simple float string `"1.0"` into a
  37227. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  37228. *
  37229. * @param {string} snippet - The shader snippet.
  37230. * @param {string} fromType - The source type.
  37231. * @param {string} toType - The target type.
  37232. * @return {string} The updated shader string.
  37233. */
  37234. format( snippet, fromType, toType ) {
  37235. fromType = this.getVectorType( fromType );
  37236. toType = this.getVectorType( toType );
  37237. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  37238. return snippet;
  37239. }
  37240. const fromTypeLength = this.getTypeLength( fromType );
  37241. const toTypeLength = this.getTypeLength( toType );
  37242. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  37243. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  37244. }
  37245. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  37246. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  37247. }
  37248. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  37249. // @TODO: ignore for now
  37250. return snippet;
  37251. }
  37252. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  37253. // @TODO: ignore for now
  37254. return snippet;
  37255. }
  37256. if ( fromTypeLength === toTypeLength ) {
  37257. return `${ this.getType( toType ) }( ${ snippet } )`;
  37258. }
  37259. if ( fromTypeLength > toTypeLength ) {
  37260. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  37261. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  37262. }
  37263. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  37264. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  37265. }
  37266. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  37267. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  37268. }
  37269. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  37270. // convert a number value to vector type, e.g:
  37271. // vec3( 1u ) -> vec3( float( 1u ) )
  37272. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  37273. }
  37274. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  37275. }
  37276. /**
  37277. * Returns a signature with the engine's current revision.
  37278. *
  37279. * @return {string} The signature.
  37280. */
  37281. getSignature() {
  37282. return `// Three.js r${ REVISION } - Node System\n`;
  37283. }
  37284. /**
  37285. * Returns `true` if data from the previous frame are required. Relevant
  37286. * when computing motion vectors with {@link VelocityNode}.
  37287. *
  37288. * @return {boolean} Whether data from the previous frame are required or not.
  37289. */
  37290. needsPreviousData() {
  37291. const mrt = this.renderer.getMRT();
  37292. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( this.object ).useVelocity === true;
  37293. }
  37294. }
  37295. /**
  37296. * Management class for updating nodes. The module tracks metrics like
  37297. * the elapsed time, delta time, the render and frame ID to correctly
  37298. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  37299. * and {@link Node#updateAfter} depending on the node's configuration.
  37300. */
  37301. class NodeFrame {
  37302. /**
  37303. * Constructs a new node fame.
  37304. */
  37305. constructor() {
  37306. /**
  37307. * The elapsed time in seconds.
  37308. *
  37309. * @type {number}
  37310. * @default 0
  37311. */
  37312. this.time = 0;
  37313. /**
  37314. * The delta time in seconds.
  37315. *
  37316. * @type {number}
  37317. * @default 0
  37318. */
  37319. this.deltaTime = 0;
  37320. /**
  37321. * The frame ID.
  37322. *
  37323. * @type {number}
  37324. * @default 0
  37325. */
  37326. this.frameId = 0;
  37327. /**
  37328. * The render ID.
  37329. *
  37330. * @type {number}
  37331. * @default 0
  37332. */
  37333. this.renderId = 0;
  37334. /**
  37335. * Used to control the {@link Node#update} call.
  37336. *
  37337. * @type {WeakMap<Node, Object>}
  37338. */
  37339. this.updateMap = new WeakMap();
  37340. /**
  37341. * Used to control the {@link Node#updateBefore} call.
  37342. *
  37343. * @type {WeakMap<Node, Object>}
  37344. */
  37345. this.updateBeforeMap = new WeakMap();
  37346. /**
  37347. * Used to control the {@link Node#updateAfter} call.
  37348. *
  37349. * @type {WeakMap<Node, Object>}
  37350. */
  37351. this.updateAfterMap = new WeakMap();
  37352. /**
  37353. * A reference to the current renderer.
  37354. *
  37355. * @type {?Renderer}
  37356. * @default null
  37357. */
  37358. this.renderer = null;
  37359. /**
  37360. * A reference to the current material.
  37361. *
  37362. * @type {?Material}
  37363. * @default null
  37364. */
  37365. this.material = null;
  37366. /**
  37367. * A reference to the current camera.
  37368. *
  37369. * @type {?Camera}
  37370. * @default null
  37371. */
  37372. this.camera = null;
  37373. /**
  37374. * A reference to the current 3D object.
  37375. *
  37376. * @type {?Object3D}
  37377. * @default null
  37378. */
  37379. this.object = null;
  37380. /**
  37381. * A reference to the current scene.
  37382. *
  37383. * @type {?Scene}
  37384. * @default null
  37385. */
  37386. this.scene = null;
  37387. }
  37388. /**
  37389. * Returns a dictionary for a given node and update map which
  37390. * is used to correctly call node update methods per frame or render.
  37391. *
  37392. * @private
  37393. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  37394. * @param {Node} nodeRef - The reference to the current node.
  37395. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  37396. */
  37397. _getMaps( referenceMap, nodeRef ) {
  37398. let maps = referenceMap.get( nodeRef );
  37399. if ( maps === undefined ) {
  37400. maps = {
  37401. renderId: 0,
  37402. frameId: 0,
  37403. };
  37404. referenceMap.set( nodeRef, maps );
  37405. }
  37406. return maps;
  37407. }
  37408. /**
  37409. * This method executes the {@link Node#updateBefore} for the given node.
  37410. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  37411. * is only executed once per frame, render or object depending on the update
  37412. * type.
  37413. *
  37414. * @param {Node} node - The node that should be updated.
  37415. */
  37416. updateBeforeNode( node ) {
  37417. const updateType = node.getUpdateBeforeType();
  37418. const reference = node.updateReference( this );
  37419. if ( updateType === NodeUpdateType.FRAME ) {
  37420. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37421. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  37422. const previousFrameId = nodeUpdateBeforeMap.frameId;
  37423. nodeUpdateBeforeMap.frameId = this.frameId;
  37424. if ( node.updateBefore( this ) === false ) {
  37425. nodeUpdateBeforeMap.frameId = previousFrameId;
  37426. }
  37427. }
  37428. } else if ( updateType === NodeUpdateType.RENDER ) {
  37429. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37430. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  37431. const previousRenderId = nodeUpdateBeforeMap.renderId;
  37432. nodeUpdateBeforeMap.renderId = this.renderId;
  37433. if ( node.updateBefore( this ) === false ) {
  37434. nodeUpdateBeforeMap.renderId = previousRenderId;
  37435. }
  37436. }
  37437. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37438. node.updateBefore( this );
  37439. }
  37440. }
  37441. /**
  37442. * This method executes the {@link Node#updateAfter} for the given node.
  37443. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  37444. * is only executed once per frame, render or object depending on the update
  37445. * type.
  37446. *
  37447. * @param {Node} node - The node that should be updated.
  37448. */
  37449. updateAfterNode( node ) {
  37450. const updateType = node.getUpdateAfterType();
  37451. const reference = node.updateReference( this );
  37452. if ( updateType === NodeUpdateType.FRAME ) {
  37453. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37454. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  37455. if ( node.updateAfter( this ) !== false ) {
  37456. nodeUpdateAfterMap.frameId = this.frameId;
  37457. }
  37458. }
  37459. } else if ( updateType === NodeUpdateType.RENDER ) {
  37460. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37461. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  37462. if ( node.updateAfter( this ) !== false ) {
  37463. nodeUpdateAfterMap.renderId = this.renderId;
  37464. }
  37465. }
  37466. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37467. node.updateAfter( this );
  37468. }
  37469. }
  37470. /**
  37471. * This method executes the {@link Node#update} for the given node.
  37472. * It makes sure {@link Node#updateType} is honored meaning the update
  37473. * is only executed once per frame, render or object depending on the update
  37474. * type.
  37475. *
  37476. * @param {Node} node - The node that should be updated.
  37477. */
  37478. updateNode( node ) {
  37479. const updateType = node.getUpdateType();
  37480. const reference = node.updateReference( this );
  37481. if ( updateType === NodeUpdateType.FRAME ) {
  37482. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37483. if ( nodeUpdateMap.frameId !== this.frameId ) {
  37484. if ( node.update( this ) !== false ) {
  37485. nodeUpdateMap.frameId = this.frameId;
  37486. }
  37487. }
  37488. } else if ( updateType === NodeUpdateType.RENDER ) {
  37489. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37490. if ( nodeUpdateMap.renderId !== this.renderId ) {
  37491. if ( node.update( this ) !== false ) {
  37492. nodeUpdateMap.renderId = this.renderId;
  37493. }
  37494. }
  37495. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37496. node.update( this );
  37497. }
  37498. }
  37499. /**
  37500. * Updates the internal state of the node frame. This method is
  37501. * called by the renderer in its internal animation loop.
  37502. */
  37503. update() {
  37504. this.frameId ++;
  37505. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  37506. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  37507. this.lastTime = performance.now();
  37508. this.time += this.deltaTime;
  37509. }
  37510. }
  37511. /**
  37512. * Describes the input of a {@link NodeFunction}.
  37513. */
  37514. class NodeFunctionInput {
  37515. /**
  37516. * Constructs a new node function input.
  37517. *
  37518. * @param {string} type - The input type.
  37519. * @param {string} name - The input name.
  37520. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  37521. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  37522. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  37523. */
  37524. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  37525. /**
  37526. * The input type.
  37527. *
  37528. * @type {string}
  37529. */
  37530. this.type = type;
  37531. /**
  37532. * The input name.
  37533. *
  37534. * @type {string}
  37535. */
  37536. this.name = name;
  37537. /**
  37538. * If the input is an Array, count will be the length.
  37539. *
  37540. * @type {?number}
  37541. * @default null
  37542. */
  37543. this.count = count;
  37544. /**
  37545. *The parameter qualifier (only relevant for GLSL).
  37546. *
  37547. * @type {('in'|'out'|'inout')}
  37548. * @default ''
  37549. */
  37550. this.qualifier = qualifier;
  37551. /**
  37552. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  37553. *
  37554. * @type {boolean}
  37555. * @default false
  37556. */
  37557. this.isConst = isConst;
  37558. }
  37559. }
  37560. NodeFunctionInput.isNodeFunctionInput = true;
  37561. /**
  37562. * Module for representing ambient lights as nodes.
  37563. *
  37564. * @augments AnalyticLightNode
  37565. */
  37566. class AmbientLightNode extends AnalyticLightNode {
  37567. static get type() {
  37568. return 'AmbientLightNode';
  37569. }
  37570. /**
  37571. * Constructs a new ambient light node.
  37572. *
  37573. * @param {?AmbientLight} [light=null] - The ambient light source.
  37574. */
  37575. constructor( light = null ) {
  37576. super( light );
  37577. }
  37578. setup( { context } ) {
  37579. context.irradiance.addAssign( this.colorNode );
  37580. }
  37581. }
  37582. /**
  37583. * Module for representing directional lights as nodes.
  37584. *
  37585. * @augments AnalyticLightNode
  37586. */
  37587. class DirectionalLightNode extends AnalyticLightNode {
  37588. static get type() {
  37589. return 'DirectionalLightNode';
  37590. }
  37591. /**
  37592. * Constructs a new directional light node.
  37593. *
  37594. * @param {?DirectionalLight} [light=null] - The directional light source.
  37595. */
  37596. constructor( light = null ) {
  37597. super( light );
  37598. }
  37599. setupDirect() {
  37600. const lightColor = this.colorNode;
  37601. const lightDirection = lightTargetDirection( this.light );
  37602. return { lightDirection, lightColor };
  37603. }
  37604. }
  37605. /**
  37606. * Module for representing hemisphere lights as nodes.
  37607. *
  37608. * @augments AnalyticLightNode
  37609. */
  37610. class HemisphereLightNode extends AnalyticLightNode {
  37611. static get type() {
  37612. return 'HemisphereLightNode';
  37613. }
  37614. /**
  37615. * Constructs a new hemisphere light node.
  37616. *
  37617. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  37618. */
  37619. constructor( light = null ) {
  37620. super( light );
  37621. /**
  37622. * Uniform node representing the light's position.
  37623. *
  37624. * @type {UniformNode<vec3>}
  37625. */
  37626. this.lightPositionNode = lightPosition( light );
  37627. /**
  37628. * A node representing the light's direction.
  37629. *
  37630. * @type {Node<vec3>}
  37631. */
  37632. this.lightDirectionNode = this.lightPositionNode.normalize();
  37633. /**
  37634. * Uniform node representing the light's ground color.
  37635. *
  37636. * @type {UniformNode<vec3>}
  37637. */
  37638. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  37639. }
  37640. /**
  37641. * Overwritten to updated hemisphere light specific uniforms.
  37642. *
  37643. * @param {NodeFrame} frame - A reference to the current node frame.
  37644. */
  37645. update( frame ) {
  37646. const { light } = this;
  37647. super.update( frame );
  37648. this.lightPositionNode.object3d = light;
  37649. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  37650. }
  37651. setup( builder ) {
  37652. const { colorNode, groundColorNode, lightDirectionNode } = this;
  37653. const dotNL = normalWorld.dot( lightDirectionNode );
  37654. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  37655. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  37656. builder.context.irradiance.addAssign( irradiance );
  37657. }
  37658. }
  37659. /**
  37660. * Module for representing spot lights as nodes.
  37661. *
  37662. * @augments AnalyticLightNode
  37663. */
  37664. class SpotLightNode extends AnalyticLightNode {
  37665. static get type() {
  37666. return 'SpotLightNode';
  37667. }
  37668. /**
  37669. * Constructs a new spot light node.
  37670. *
  37671. * @param {?SpotLight} [light=null] - The spot light source.
  37672. */
  37673. constructor( light = null ) {
  37674. super( light );
  37675. /**
  37676. * Uniform node representing the cone cosine.
  37677. *
  37678. * @type {UniformNode<float>}
  37679. */
  37680. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  37681. /**
  37682. * Uniform node representing the penumbra cosine.
  37683. *
  37684. * @type {UniformNode<float>}
  37685. */
  37686. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  37687. /**
  37688. * Uniform node representing the cutoff distance.
  37689. *
  37690. * @type {UniformNode<float>}
  37691. */
  37692. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  37693. /**
  37694. * Uniform node representing the decay exponent.
  37695. *
  37696. * @type {UniformNode<float>}
  37697. */
  37698. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  37699. /**
  37700. * Uniform node representing the light color.
  37701. *
  37702. * @type {UniformNode<Color>}
  37703. */
  37704. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  37705. }
  37706. /**
  37707. * Overwritten to updated spot light specific uniforms.
  37708. *
  37709. * @param {NodeFrame} frame - A reference to the current node frame.
  37710. */
  37711. update( frame ) {
  37712. super.update( frame );
  37713. const { light } = this;
  37714. this.coneCosNode.value = Math.cos( light.angle );
  37715. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  37716. this.cutoffDistanceNode.value = light.distance;
  37717. this.decayExponentNode.value = light.decay;
  37718. }
  37719. /**
  37720. * Computes the spot attenuation for the given angle.
  37721. *
  37722. * @param {NodeBuilder} builder - The node builder.
  37723. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  37724. * @return {Node<float>} The spot attenuation.
  37725. */
  37726. getSpotAttenuation( builder, angleCosine ) {
  37727. const { coneCosNode, penumbraCosNode } = this;
  37728. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  37729. }
  37730. getLightCoord( builder ) {
  37731. const properties = builder.getNodeProperties( this );
  37732. let projectionUV = properties.projectionUV;
  37733. if ( projectionUV === undefined ) {
  37734. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  37735. properties.projectionUV = projectionUV;
  37736. }
  37737. return projectionUV;
  37738. }
  37739. setupDirect( builder ) {
  37740. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  37741. const lightVector = this.getLightVector( builder );
  37742. const lightDirection = lightVector.normalize();
  37743. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  37744. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  37745. const lightDistance = lightVector.length();
  37746. const lightAttenuation = getDistanceAttenuation( {
  37747. lightDistance,
  37748. cutoffDistance: cutoffDistanceNode,
  37749. decayExponent: decayExponentNode
  37750. } );
  37751. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  37752. let projected, lightCoord;
  37753. if ( light.colorNode ) {
  37754. lightCoord = this.getLightCoord( builder );
  37755. projected = light.colorNode( lightCoord );
  37756. } else if ( light.map ) {
  37757. lightCoord = this.getLightCoord( builder );
  37758. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  37759. }
  37760. if ( projected ) {
  37761. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  37762. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  37763. }
  37764. return { lightColor, lightDirection };
  37765. }
  37766. }
  37767. /**
  37768. * An IES version of the default spot light node.
  37769. *
  37770. * @augments SpotLightNode
  37771. */
  37772. class IESSpotLightNode extends SpotLightNode {
  37773. static get type() {
  37774. return 'IESSpotLightNode';
  37775. }
  37776. /**
  37777. * Overwrites the default implementation to compute an IES conform spot attenuation.
  37778. *
  37779. * @param {NodeBuilder} builder - The node builder.
  37780. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  37781. * @return {Node<float>} The spot attenuation.
  37782. */
  37783. getSpotAttenuation( builder, angleCosine ) {
  37784. const iesMap = this.light.iesMap;
  37785. let spotAttenuation = null;
  37786. if ( iesMap && iesMap.isTexture === true ) {
  37787. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  37788. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  37789. } else {
  37790. spotAttenuation = super.getSpotAttenuation( angleCosine );
  37791. }
  37792. return spotAttenuation;
  37793. }
  37794. }
  37795. /**
  37796. * Module for representing light probes as nodes.
  37797. *
  37798. * @augments AnalyticLightNode
  37799. */
  37800. class LightProbeNode extends AnalyticLightNode {
  37801. static get type() {
  37802. return 'LightProbeNode';
  37803. }
  37804. /**
  37805. * Constructs a new light probe node.
  37806. *
  37807. * @param {?LightProbe} [light=null] - The light probe.
  37808. */
  37809. constructor( light = null ) {
  37810. super( light );
  37811. const array = [];
  37812. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  37813. /**
  37814. * Light probe represented as a uniform of spherical harmonics.
  37815. *
  37816. * @type {UniformArrayNode}
  37817. */
  37818. this.lightProbe = uniformArray( array );
  37819. }
  37820. /**
  37821. * Overwritten to updated light probe specific uniforms.
  37822. *
  37823. * @param {NodeFrame} frame - A reference to the current node frame.
  37824. */
  37825. update( frame ) {
  37826. const { light } = this;
  37827. super.update( frame );
  37828. //
  37829. for ( let i = 0; i < 9; i ++ ) {
  37830. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  37831. }
  37832. }
  37833. setup( builder ) {
  37834. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  37835. builder.context.irradiance.addAssign( irradiance );
  37836. }
  37837. }
  37838. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  37839. const d = p.abs().sub( b );
  37840. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  37841. } );
  37842. /**
  37843. * An implementation of a projector light node.
  37844. *
  37845. * @augments SpotLightNode
  37846. */
  37847. class ProjectorLightNode extends SpotLightNode {
  37848. static get type() {
  37849. return 'ProjectorLightNode';
  37850. }
  37851. update( frame ) {
  37852. super.update( frame );
  37853. const light = this.light;
  37854. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  37855. if ( light.aspect === null ) {
  37856. let aspect = 1;
  37857. if ( light.map !== null ) {
  37858. aspect = light.map.width / light.map.height;
  37859. }
  37860. light.shadow.aspect = aspect;
  37861. } else {
  37862. light.shadow.aspect = light.aspect;
  37863. }
  37864. }
  37865. /**
  37866. * Overwrites the default implementation to compute projection attenuation.
  37867. *
  37868. * @param {NodeBuilder} builder - The node builder.
  37869. * @return {Node<float>} The spot attenuation.
  37870. */
  37871. getSpotAttenuation( builder ) {
  37872. const attenuation = float( 0 );
  37873. const penumbraCos = this.penumbraCosNode;
  37874. // compute the fragment's position in the light's clip space
  37875. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  37876. // the sign of w determines whether the current fragment is in front or behind the light.
  37877. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  37878. If( spotLightCoord.w.greaterThan( 0 ), () => {
  37879. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  37880. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  37881. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  37882. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  37883. } );
  37884. return attenuation;
  37885. }
  37886. }
  37887. const _matrix41 = /*@__PURE__*/ new Matrix4();
  37888. const _matrix42 = /*@__PURE__*/ new Matrix4();
  37889. let _ltcLib = null;
  37890. /**
  37891. * Module for representing rect area lights as nodes.
  37892. *
  37893. * @augments AnalyticLightNode
  37894. */
  37895. class RectAreaLightNode extends AnalyticLightNode {
  37896. static get type() {
  37897. return 'RectAreaLightNode';
  37898. }
  37899. /**
  37900. * Constructs a new rect area light node.
  37901. *
  37902. * @param {?RectAreaLight} [light=null] - The rect area light source.
  37903. */
  37904. constructor( light = null ) {
  37905. super( light );
  37906. /**
  37907. * Uniform node representing the half height of the are light.
  37908. *
  37909. * @type {UniformNode<vec3>}
  37910. */
  37911. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  37912. /**
  37913. * Uniform node representing the half width of the are light.
  37914. *
  37915. * @type {UniformNode<vec3>}
  37916. */
  37917. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  37918. /**
  37919. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  37920. * relies on `viewMatrix` which might vary per render call.
  37921. *
  37922. * @type {string}
  37923. * @default 'render'
  37924. */
  37925. this.updateType = NodeUpdateType.RENDER;
  37926. }
  37927. /**
  37928. * Overwritten to updated rect area light specific uniforms.
  37929. *
  37930. * @param {NodeFrame} frame - A reference to the current node frame.
  37931. */
  37932. update( frame ) {
  37933. super.update( frame );
  37934. const { light } = this;
  37935. const viewMatrix = frame.camera.matrixWorldInverse;
  37936. _matrix42.identity();
  37937. _matrix41.copy( light.matrixWorld );
  37938. _matrix41.premultiply( viewMatrix );
  37939. _matrix42.extractRotation( _matrix41 );
  37940. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  37941. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  37942. this.halfWidth.value.applyMatrix4( _matrix42 );
  37943. this.halfHeight.value.applyMatrix4( _matrix42 );
  37944. }
  37945. setupDirectRectArea( builder ) {
  37946. let ltc_1, ltc_2;
  37947. if ( builder.isAvailable( 'float32Filterable' ) ) {
  37948. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  37949. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  37950. } else {
  37951. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  37952. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  37953. }
  37954. const { colorNode, light } = this;
  37955. const lightPosition = lightViewPosition( light );
  37956. return {
  37957. lightColor: colorNode,
  37958. lightPosition,
  37959. halfWidth: this.halfWidth,
  37960. halfHeight: this.halfHeight,
  37961. ltc_1,
  37962. ltc_2
  37963. };
  37964. }
  37965. /**
  37966. * Used to configure the internal BRDF approximation texture data.
  37967. *
  37968. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  37969. */
  37970. static setLTC( ltc ) {
  37971. _ltcLib = ltc;
  37972. }
  37973. }
  37974. /**
  37975. * Base class for node parsers. A derived parser must be implemented
  37976. * for each supported native shader language.
  37977. */
  37978. class NodeParser {
  37979. /**
  37980. * The method parses the given native code an returns a node function.
  37981. *
  37982. * @abstract
  37983. * @param {string} source - The native shader code.
  37984. * @return {NodeFunction} A node function.
  37985. */
  37986. parseFunction( /*source*/ ) {
  37987. warn( 'Abstract function.' );
  37988. }
  37989. }
  37990. /**
  37991. * Base class for node functions. A derived module must be implemented
  37992. * for each supported native shader language. Similar to other `Node*` modules,
  37993. * this class is only relevant during the building process and not used
  37994. * in user-level code.
  37995. */
  37996. class NodeFunction {
  37997. /**
  37998. * Constructs a new node function.
  37999. *
  38000. * @param {string} type - The node type. This type is the return type of the node function.
  38001. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  38002. * @param {string} [name=''] - The function's name.
  38003. * @param {string} [precision=''] - The precision qualifier.
  38004. */
  38005. constructor( type, inputs, name = '', precision = '' ) {
  38006. /**
  38007. * The node type. This type is the return type of the node function.
  38008. *
  38009. * @type {string}
  38010. */
  38011. this.type = type;
  38012. /**
  38013. * The function's inputs.
  38014. *
  38015. * @type {Array<NodeFunctionInput>}
  38016. */
  38017. this.inputs = inputs;
  38018. /**
  38019. * The name of the uniform.
  38020. *
  38021. * @type {string}
  38022. * @default ''
  38023. */
  38024. this.name = name;
  38025. /**
  38026. * The precision qualifier.
  38027. *
  38028. * @type {string}
  38029. * @default ''
  38030. */
  38031. this.precision = precision;
  38032. }
  38033. /**
  38034. * This method returns the native code of the node function.
  38035. *
  38036. * @abstract
  38037. * @param {string} name - The function's name.
  38038. * @return {string} A shader code.
  38039. */
  38040. getCode( /*name = this.name*/ ) {
  38041. warn( 'Abstract function.' );
  38042. }
  38043. }
  38044. NodeFunction.isNodeFunction = true;
  38045. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  38046. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  38047. const pragmaMain = '#pragma main';
  38048. const parse$1 = ( source ) => {
  38049. source = source.trim();
  38050. const pragmaMainIndex = source.indexOf( pragmaMain );
  38051. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  38052. const declaration = mainCode.match( declarationRegexp$1 );
  38053. if ( declaration !== null && declaration.length === 5 ) {
  38054. // tokenizer
  38055. const inputsCode = declaration[ 4 ];
  38056. const propsMatches = [];
  38057. let nameMatch = null;
  38058. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  38059. propsMatches.push( nameMatch );
  38060. }
  38061. // parser
  38062. const inputs = [];
  38063. let i = 0;
  38064. while ( i < propsMatches.length ) {
  38065. const isConst = propsMatches[ i ][ 0 ] === 'const';
  38066. if ( isConst === true ) {
  38067. i ++;
  38068. }
  38069. let qualifier = propsMatches[ i ][ 0 ];
  38070. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  38071. i ++;
  38072. } else {
  38073. qualifier = '';
  38074. }
  38075. const type = propsMatches[ i ++ ][ 0 ];
  38076. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  38077. if ( Number.isNaN( count ) === false ) i ++;
  38078. else count = null;
  38079. const name = propsMatches[ i ++ ][ 0 ];
  38080. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  38081. }
  38082. //
  38083. const blockCode = mainCode.substring( declaration[ 0 ].length );
  38084. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  38085. const type = declaration[ 2 ];
  38086. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  38087. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  38088. return {
  38089. type,
  38090. inputs,
  38091. name,
  38092. precision,
  38093. inputsCode,
  38094. blockCode,
  38095. headerCode
  38096. };
  38097. } else {
  38098. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  38099. }
  38100. };
  38101. /**
  38102. * This class represents a GLSL node function.
  38103. *
  38104. * @augments NodeFunction
  38105. */
  38106. class GLSLNodeFunction extends NodeFunction {
  38107. /**
  38108. * Constructs a new GLSL node function.
  38109. *
  38110. * @param {string} source - The GLSL source.
  38111. */
  38112. constructor( source ) {
  38113. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  38114. super( type, inputs, name, precision );
  38115. this.inputsCode = inputsCode;
  38116. this.blockCode = blockCode;
  38117. this.headerCode = headerCode;
  38118. }
  38119. /**
  38120. * This method returns the GLSL code of the node function.
  38121. *
  38122. * @param {string} [name=this.name] - The function's name.
  38123. * @return {string} The shader code.
  38124. */
  38125. getCode( name = this.name ) {
  38126. let code;
  38127. const blockCode = this.blockCode;
  38128. if ( blockCode !== '' ) {
  38129. const { type, inputsCode, headerCode, precision } = this;
  38130. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  38131. if ( precision !== '' ) {
  38132. declarationCode = `${ precision } ${ declarationCode }`;
  38133. }
  38134. code = headerCode + declarationCode + blockCode;
  38135. } else {
  38136. // interface function
  38137. code = '';
  38138. }
  38139. return code;
  38140. }
  38141. }
  38142. /**
  38143. * A GLSL node parser.
  38144. *
  38145. * @augments NodeParser
  38146. */
  38147. class GLSLNodeParser extends NodeParser {
  38148. /**
  38149. * The method parses the given GLSL code an returns a node function.
  38150. *
  38151. * @param {string} source - The GLSL code.
  38152. * @return {GLSLNodeFunction} A node function.
  38153. */
  38154. parseFunction( source ) {
  38155. return new GLSLNodeFunction( source );
  38156. }
  38157. }
  38158. const _outputNodeMap = new WeakMap();
  38159. const _chainKeys$1 = [];
  38160. const _cacheKeyValues = [];
  38161. /**
  38162. * This renderer module manages node-related objects and is the
  38163. * primary interface between the renderer and the node system.
  38164. *
  38165. * @private
  38166. * @augments DataMap
  38167. */
  38168. class NodeManager extends DataMap {
  38169. /**
  38170. * Constructs a new nodes management component.
  38171. *
  38172. * @param {Renderer} renderer - The renderer.
  38173. * @param {Backend} backend - The renderer's backend.
  38174. */
  38175. constructor( renderer, backend ) {
  38176. super();
  38177. /**
  38178. * The renderer.
  38179. *
  38180. * @type {Renderer}
  38181. */
  38182. this.renderer = renderer;
  38183. /**
  38184. * The renderer's backend.
  38185. *
  38186. * @type {Backend}
  38187. */
  38188. this.backend = backend;
  38189. /**
  38190. * The node frame.
  38191. *
  38192. * @type {Renderer}
  38193. */
  38194. this.nodeFrame = new NodeFrame();
  38195. /**
  38196. * A cache for managing node builder states.
  38197. *
  38198. * @type {Map<number,NodeBuilderState>}
  38199. */
  38200. this.nodeBuilderCache = new Map();
  38201. /**
  38202. * A cache for managing data cache key data.
  38203. *
  38204. * @type {ChainMap}
  38205. */
  38206. this.callHashCache = new ChainMap();
  38207. /**
  38208. * A cache for managing node uniforms group data.
  38209. *
  38210. * @type {ChainMap}
  38211. */
  38212. this.groupsData = new ChainMap();
  38213. /**
  38214. * A cache for managing node objects of
  38215. * scene properties like fog or environments.
  38216. *
  38217. * @type {Object<string,WeakMap>}
  38218. */
  38219. this.cacheLib = {};
  38220. }
  38221. /**
  38222. * Returns `true` if the given node uniforms group must be updated or not.
  38223. *
  38224. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  38225. * @return {boolean} Whether the node uniforms group requires an update or not.
  38226. */
  38227. updateGroup( nodeUniformsGroup ) {
  38228. const groupNode = nodeUniformsGroup.groupNode;
  38229. const name = groupNode.name;
  38230. // objectGroup is always updated
  38231. if ( name === objectGroup.name ) return true;
  38232. // renderGroup is updated once per render/compute call
  38233. if ( name === renderGroup.name ) {
  38234. const uniformsGroupData = this.get( nodeUniformsGroup );
  38235. const renderId = this.nodeFrame.renderId;
  38236. if ( uniformsGroupData.renderId !== renderId ) {
  38237. uniformsGroupData.renderId = renderId;
  38238. return true;
  38239. }
  38240. return false;
  38241. }
  38242. // frameGroup is updated once per frame
  38243. if ( name === frameGroup.name ) {
  38244. const uniformsGroupData = this.get( nodeUniformsGroup );
  38245. const frameId = this.nodeFrame.frameId;
  38246. if ( uniformsGroupData.frameId !== frameId ) {
  38247. uniformsGroupData.frameId = frameId;
  38248. return true;
  38249. }
  38250. return false;
  38251. }
  38252. // other groups are updated just when groupNode.needsUpdate is true
  38253. _chainKeys$1[ 0 ] = groupNode;
  38254. _chainKeys$1[ 1 ] = nodeUniformsGroup;
  38255. let groupData = this.groupsData.get( _chainKeys$1 );
  38256. if ( groupData === undefined ) this.groupsData.set( _chainKeys$1, groupData = {} );
  38257. _chainKeys$1[ 0 ] = null;
  38258. _chainKeys$1[ 1 ] = null;
  38259. if ( groupData.version !== groupNode.version ) {
  38260. groupData.version = groupNode.version;
  38261. return true;
  38262. }
  38263. return false;
  38264. }
  38265. /**
  38266. * Returns the cache key for the given render object.
  38267. *
  38268. * @param {RenderObject} renderObject - The render object.
  38269. * @return {number} The cache key.
  38270. */
  38271. getForRenderCacheKey( renderObject ) {
  38272. return renderObject.initialCacheKey;
  38273. }
  38274. /**
  38275. * Returns a node builder state for the given render object.
  38276. *
  38277. * @param {RenderObject} renderObject - The render object.
  38278. * @return {NodeBuilderState} The node builder state.
  38279. */
  38280. getForRender( renderObject ) {
  38281. const renderObjectData = this.get( renderObject );
  38282. let nodeBuilderState = renderObjectData.nodeBuilderState;
  38283. if ( nodeBuilderState === undefined ) {
  38284. const { nodeBuilderCache } = this;
  38285. const cacheKey = this.getForRenderCacheKey( renderObject );
  38286. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  38287. if ( nodeBuilderState === undefined ) {
  38288. const createNodeBuilder = ( material ) => {
  38289. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  38290. nodeBuilder.scene = renderObject.scene;
  38291. nodeBuilder.material = material;
  38292. nodeBuilder.camera = renderObject.camera;
  38293. nodeBuilder.context.material = material;
  38294. nodeBuilder.lightsNode = renderObject.lightsNode;
  38295. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  38296. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  38297. nodeBuilder.clippingContext = renderObject.clippingContext;
  38298. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  38299. nodeBuilder.enableMultiview();
  38300. }
  38301. return nodeBuilder;
  38302. };
  38303. let nodeBuilder = createNodeBuilder( renderObject.material );
  38304. try {
  38305. nodeBuilder.build();
  38306. } catch ( e ) {
  38307. nodeBuilder = createNodeBuilder( new NodeMaterial() );
  38308. nodeBuilder.build();
  38309. let stackTrace = e.stackTrace;
  38310. if ( ! stackTrace && e.stack ) {
  38311. // Capture stack trace for JavaScript errors
  38312. stackTrace = new StackTrace( e.stack );
  38313. }
  38314. error( 'TSL: ' + e, stackTrace );
  38315. }
  38316. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38317. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  38318. }
  38319. nodeBuilderState.usedTimes ++;
  38320. renderObjectData.nodeBuilderState = nodeBuilderState;
  38321. }
  38322. return nodeBuilderState;
  38323. }
  38324. /**
  38325. * Deletes the given object from the internal data map
  38326. *
  38327. * @param {any} object - The object to delete.
  38328. * @return {?Object} The deleted dictionary.
  38329. */
  38330. delete( object ) {
  38331. if ( object.isRenderObject ) {
  38332. const nodeBuilderState = this.get( object ).nodeBuilderState;
  38333. nodeBuilderState.usedTimes --;
  38334. if ( nodeBuilderState.usedTimes === 0 ) {
  38335. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  38336. }
  38337. }
  38338. return super.delete( object );
  38339. }
  38340. /**
  38341. * Returns a node builder state for the given compute node.
  38342. *
  38343. * @param {Node} computeNode - The compute node.
  38344. * @return {NodeBuilderState} The node builder state.
  38345. */
  38346. getForCompute( computeNode ) {
  38347. const computeData = this.get( computeNode );
  38348. let nodeBuilderState = computeData.nodeBuilderState;
  38349. if ( nodeBuilderState === undefined ) {
  38350. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  38351. nodeBuilder.build();
  38352. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38353. computeData.nodeBuilderState = nodeBuilderState;
  38354. }
  38355. return nodeBuilderState;
  38356. }
  38357. /**
  38358. * Creates a node builder state for the given node builder.
  38359. *
  38360. * @private
  38361. * @param {NodeBuilder} nodeBuilder - The node builder.
  38362. * @return {NodeBuilderState} The node builder state.
  38363. */
  38364. _createNodeBuilderState( nodeBuilder ) {
  38365. return new NodeBuilderState(
  38366. nodeBuilder.vertexShader,
  38367. nodeBuilder.fragmentShader,
  38368. nodeBuilder.computeShader,
  38369. nodeBuilder.getAttributesArray(),
  38370. nodeBuilder.getBindings(),
  38371. nodeBuilder.updateNodes,
  38372. nodeBuilder.updateBeforeNodes,
  38373. nodeBuilder.updateAfterNodes,
  38374. nodeBuilder.observer,
  38375. nodeBuilder.transforms
  38376. );
  38377. }
  38378. /**
  38379. * Returns an environment node for the current configured
  38380. * scene environment.
  38381. *
  38382. * @param {Scene} scene - The scene.
  38383. * @return {Node} A node representing the current scene environment.
  38384. */
  38385. getEnvironmentNode( scene ) {
  38386. this.updateEnvironment( scene );
  38387. let environmentNode = null;
  38388. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  38389. environmentNode = scene.environmentNode;
  38390. } else {
  38391. const sceneData = this.get( scene );
  38392. if ( sceneData.environmentNode ) {
  38393. environmentNode = sceneData.environmentNode;
  38394. }
  38395. }
  38396. return environmentNode;
  38397. }
  38398. /**
  38399. * Returns a background node for the current configured
  38400. * scene background.
  38401. *
  38402. * @param {Scene} scene - The scene.
  38403. * @return {Node} A node representing the current scene background.
  38404. */
  38405. getBackgroundNode( scene ) {
  38406. this.updateBackground( scene );
  38407. let backgroundNode = null;
  38408. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  38409. backgroundNode = scene.backgroundNode;
  38410. } else {
  38411. const sceneData = this.get( scene );
  38412. if ( sceneData.backgroundNode ) {
  38413. backgroundNode = sceneData.backgroundNode;
  38414. }
  38415. }
  38416. return backgroundNode;
  38417. }
  38418. /**
  38419. * Returns a fog node for the current configured scene fog.
  38420. *
  38421. * @param {Scene} scene - The scene.
  38422. * @return {Node} A node representing the current scene fog.
  38423. */
  38424. getFogNode( scene ) {
  38425. this.updateFog( scene );
  38426. return scene.fogNode || this.get( scene ).fogNode || null;
  38427. }
  38428. /**
  38429. * Returns a cache key for the given scene and lights node.
  38430. * This key is used by `RenderObject` as a part of the dynamic
  38431. * cache key (a key that must be checked every time the render
  38432. * objects is drawn).
  38433. *
  38434. * @param {Scene} scene - The scene.
  38435. * @param {LightsNode} lightsNode - The lights node.
  38436. * @return {number} The cache key.
  38437. */
  38438. getCacheKey( scene, lightsNode ) {
  38439. _chainKeys$1[ 0 ] = scene;
  38440. _chainKeys$1[ 1 ] = lightsNode;
  38441. const callId = this.renderer.info.calls;
  38442. const cacheKeyData = this.callHashCache.get( _chainKeys$1 ) || {};
  38443. if ( cacheKeyData.callId !== callId ) {
  38444. const environmentNode = this.getEnvironmentNode( scene );
  38445. const fogNode = this.getFogNode( scene );
  38446. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  38447. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  38448. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  38449. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  38450. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  38451. _cacheKeyValues.push( this.renderer.shadowMap.type );
  38452. cacheKeyData.callId = callId;
  38453. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  38454. this.callHashCache.set( _chainKeys$1, cacheKeyData );
  38455. _cacheKeyValues.length = 0;
  38456. }
  38457. _chainKeys$1[ 0 ] = null;
  38458. _chainKeys$1[ 1 ] = null;
  38459. return cacheKeyData.cacheKey;
  38460. }
  38461. /**
  38462. * A boolean that indicates whether tone mapping should be enabled
  38463. * or not.
  38464. *
  38465. * @type {boolean}
  38466. */
  38467. get isToneMappingState() {
  38468. return this.renderer.getRenderTarget() ? false : true;
  38469. }
  38470. /**
  38471. * If a scene background is configured, this method makes sure to
  38472. * represent the background with a corresponding node-based implementation.
  38473. *
  38474. * @param {Scene} scene - The scene.
  38475. */
  38476. updateBackground( scene ) {
  38477. const sceneData = this.get( scene );
  38478. const background = scene.background;
  38479. if ( background ) {
  38480. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  38481. if ( sceneData.background !== background || forceUpdate ) {
  38482. const backgroundNode = this.getCacheNode( 'background', background, () => {
  38483. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  38484. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  38485. return pmremTexture( background );
  38486. } else {
  38487. let envMap;
  38488. if ( background.isCubeTexture === true ) {
  38489. envMap = cubeTexture( background );
  38490. } else {
  38491. envMap = texture( background );
  38492. }
  38493. return cubeMapNode( envMap );
  38494. }
  38495. } else if ( background.isTexture === true ) {
  38496. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  38497. } else if ( background.isColor !== true ) {
  38498. error( 'WebGPUNodes: Unsupported background configuration.', background );
  38499. }
  38500. }, forceUpdate );
  38501. sceneData.backgroundNode = backgroundNode;
  38502. sceneData.background = background;
  38503. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  38504. }
  38505. } else if ( sceneData.backgroundNode ) {
  38506. delete sceneData.backgroundNode;
  38507. delete sceneData.background;
  38508. }
  38509. }
  38510. /**
  38511. * This method is part of the caching of nodes which are used to represents the
  38512. * scene's background, fog or environment.
  38513. *
  38514. * @param {string} type - The type of object to cache.
  38515. * @param {Object} object - The object.
  38516. * @param {Function} callback - A callback that produces a node representation for the given object.
  38517. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  38518. * @return {Node} The node representation.
  38519. */
  38520. getCacheNode( type, object, callback, forceUpdate = false ) {
  38521. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  38522. let node = nodeCache.get( object );
  38523. if ( node === undefined || forceUpdate ) {
  38524. node = callback();
  38525. nodeCache.set( object, node );
  38526. }
  38527. return node;
  38528. }
  38529. /**
  38530. * If a scene fog is configured, this method makes sure to
  38531. * represent the fog with a corresponding node-based implementation.
  38532. *
  38533. * @param {Scene} scene - The scene.
  38534. */
  38535. updateFog( scene ) {
  38536. const sceneData = this.get( scene );
  38537. const sceneFog = scene.fog;
  38538. if ( sceneFog ) {
  38539. if ( sceneData.fog !== sceneFog ) {
  38540. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  38541. if ( sceneFog.isFogExp2 ) {
  38542. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38543. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  38544. return fog( color, densityFogFactor( density ) );
  38545. } else if ( sceneFog.isFog ) {
  38546. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38547. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  38548. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  38549. return fog( color, rangeFogFactor( near, far ) );
  38550. } else {
  38551. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  38552. }
  38553. } );
  38554. sceneData.fogNode = fogNode;
  38555. sceneData.fog = sceneFog;
  38556. }
  38557. } else {
  38558. delete sceneData.fogNode;
  38559. delete sceneData.fog;
  38560. }
  38561. }
  38562. /**
  38563. * If a scene environment is configured, this method makes sure to
  38564. * represent the environment with a corresponding node-based implementation.
  38565. *
  38566. * @param {Scene} scene - The scene.
  38567. */
  38568. updateEnvironment( scene ) {
  38569. const sceneData = this.get( scene );
  38570. const environment = scene.environment;
  38571. if ( environment ) {
  38572. if ( sceneData.environment !== environment ) {
  38573. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  38574. if ( environment.isCubeTexture === true ) {
  38575. return cubeTexture( environment );
  38576. } else if ( environment.isTexture === true ) {
  38577. return texture( environment );
  38578. } else {
  38579. error( 'Nodes: Unsupported environment configuration.', environment );
  38580. }
  38581. } );
  38582. sceneData.environmentNode = environmentNode;
  38583. sceneData.environment = environment;
  38584. }
  38585. } else if ( sceneData.environmentNode ) {
  38586. delete sceneData.environmentNode;
  38587. delete sceneData.environment;
  38588. }
  38589. }
  38590. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  38591. const nodeFrame = this.nodeFrame;
  38592. nodeFrame.renderer = renderer;
  38593. nodeFrame.scene = scene;
  38594. nodeFrame.object = object;
  38595. nodeFrame.camera = camera;
  38596. nodeFrame.material = material;
  38597. return nodeFrame;
  38598. }
  38599. getNodeFrameForRender( renderObject ) {
  38600. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  38601. }
  38602. /**
  38603. * Returns the current output cache key.
  38604. *
  38605. * @return {string} The output cache key.
  38606. */
  38607. getOutputCacheKey() {
  38608. const renderer = this.renderer;
  38609. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  38610. }
  38611. /**
  38612. * Checks if the output configuration (tone mapping and color space) for
  38613. * the given target has changed.
  38614. *
  38615. * @param {Texture} outputTarget - The output target.
  38616. * @return {boolean} Whether the output configuration has changed or not.
  38617. */
  38618. hasOutputChange( outputTarget ) {
  38619. const cacheKey = _outputNodeMap.get( outputTarget );
  38620. return cacheKey !== this.getOutputCacheKey();
  38621. }
  38622. /**
  38623. * Returns a node that represents the output configuration (tone mapping and
  38624. * color space) for the current target.
  38625. *
  38626. * @param {Texture} outputTarget - The output target.
  38627. * @return {Node} The output node.
  38628. */
  38629. getOutputNode( outputTarget ) {
  38630. const renderer = this.renderer;
  38631. const cacheKey = this.getOutputCacheKey();
  38632. const output = outputTarget.isArrayTexture ?
  38633. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  38634. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  38635. _outputNodeMap.set( outputTarget, cacheKey );
  38636. return output;
  38637. }
  38638. /**
  38639. * Triggers the call of `updateBefore()` methods
  38640. * for all nodes of the given render object.
  38641. *
  38642. * @param {RenderObject} renderObject - The render object.
  38643. */
  38644. updateBefore( renderObject ) {
  38645. const nodeBuilder = renderObject.getNodeBuilderState();
  38646. for ( const node of nodeBuilder.updateBeforeNodes ) {
  38647. // update frame state for each node
  38648. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  38649. }
  38650. }
  38651. /**
  38652. * Triggers the call of `updateAfter()` methods
  38653. * for all nodes of the given render object.
  38654. *
  38655. * @param {RenderObject} renderObject - The render object.
  38656. */
  38657. updateAfter( renderObject ) {
  38658. const nodeBuilder = renderObject.getNodeBuilderState();
  38659. for ( const node of nodeBuilder.updateAfterNodes ) {
  38660. // update frame state for each node
  38661. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  38662. }
  38663. }
  38664. /**
  38665. * Triggers the call of `update()` methods
  38666. * for all nodes of the given compute node.
  38667. *
  38668. * @param {Node} computeNode - The compute node.
  38669. */
  38670. updateForCompute( computeNode ) {
  38671. const nodeFrame = this.getNodeFrame();
  38672. const nodeBuilder = this.getForCompute( computeNode );
  38673. for ( const node of nodeBuilder.updateNodes ) {
  38674. nodeFrame.updateNode( node );
  38675. }
  38676. }
  38677. /**
  38678. * Triggers the call of `update()` methods
  38679. * for all nodes of the given compute node.
  38680. *
  38681. * @param {RenderObject} renderObject - The render object.
  38682. */
  38683. updateForRender( renderObject ) {
  38684. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38685. const nodeBuilder = renderObject.getNodeBuilderState();
  38686. for ( const node of nodeBuilder.updateNodes ) {
  38687. nodeFrame.updateNode( node );
  38688. }
  38689. }
  38690. /**
  38691. * Returns `true` if the given render object requires a refresh.
  38692. *
  38693. * @param {RenderObject} renderObject - The render object.
  38694. * @return {boolean} Whether the given render object requires a refresh or not.
  38695. */
  38696. needsRefresh( renderObject ) {
  38697. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38698. const monitor = renderObject.getMonitor();
  38699. return monitor.needsRefresh( renderObject, nodeFrame );
  38700. }
  38701. /**
  38702. * Frees the internal resources.
  38703. */
  38704. dispose() {
  38705. super.dispose();
  38706. this.nodeFrame = new NodeFrame();
  38707. this.nodeBuilderCache = new Map();
  38708. this.cacheLib = {};
  38709. }
  38710. }
  38711. const _plane = /*@__PURE__*/ new Plane();
  38712. /**
  38713. * Represents the state that is used to perform clipping via clipping planes.
  38714. * There is a default clipping context for each render context. When the
  38715. * scene holds instances of `ClippingGroup`, there will be a context for each
  38716. * group.
  38717. *
  38718. * @private
  38719. */
  38720. class ClippingContext {
  38721. /**
  38722. * Constructs a new clipping context.
  38723. *
  38724. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  38725. */
  38726. constructor( parentContext = null ) {
  38727. /**
  38728. * The clipping context's version.
  38729. *
  38730. * @type {number}
  38731. * @readonly
  38732. */
  38733. this.version = 0;
  38734. /**
  38735. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  38736. *
  38737. * @type {?boolean}
  38738. * @default null
  38739. */
  38740. this.clipIntersection = null;
  38741. /**
  38742. * The clipping context's cache key.
  38743. *
  38744. * @type {string}
  38745. */
  38746. this.cacheKey = '';
  38747. /**
  38748. * Whether the shadow pass is active or not.
  38749. *
  38750. * @type {boolean}
  38751. * @default false
  38752. */
  38753. this.shadowPass = false;
  38754. /**
  38755. * The view normal matrix.
  38756. *
  38757. * @type {Matrix3}
  38758. */
  38759. this.viewNormalMatrix = new Matrix3();
  38760. /**
  38761. * Internal cache for maintaining clipping contexts.
  38762. *
  38763. * @type {WeakMap<ClippingGroup,ClippingContext>}
  38764. */
  38765. this.clippingGroupContexts = new WeakMap();
  38766. /**
  38767. * The intersection planes.
  38768. *
  38769. * @type {Array<Vector4>}
  38770. */
  38771. this.intersectionPlanes = [];
  38772. /**
  38773. * The intersection planes.
  38774. *
  38775. * @type {Array<Vector4>}
  38776. */
  38777. this.unionPlanes = [];
  38778. /**
  38779. * The version of the clipping context's parent context.
  38780. *
  38781. * @type {?number}
  38782. * @readonly
  38783. */
  38784. this.parentVersion = null;
  38785. if ( parentContext !== null ) {
  38786. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  38787. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  38788. this.shadowPass = parentContext.shadowPass;
  38789. this.viewMatrix = parentContext.viewMatrix;
  38790. }
  38791. }
  38792. /**
  38793. * Projects the given source clipping planes and writes the result into the
  38794. * destination array.
  38795. *
  38796. * @param {Array<Plane>} source - The source clipping planes.
  38797. * @param {Array<Vector4>} destination - The destination.
  38798. * @param {number} offset - The offset.
  38799. */
  38800. projectPlanes( source, destination, offset ) {
  38801. const l = source.length;
  38802. for ( let i = 0; i < l; i ++ ) {
  38803. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  38804. const v = destination[ offset + i ];
  38805. const normal = _plane.normal;
  38806. v.x = - normal.x;
  38807. v.y = - normal.y;
  38808. v.z = - normal.z;
  38809. v.w = _plane.constant;
  38810. }
  38811. }
  38812. /**
  38813. * Updates the root clipping context of a scene.
  38814. *
  38815. * @param {Scene} scene - The scene.
  38816. * @param {Camera} camera - The camera that is used to render the scene.
  38817. */
  38818. updateGlobal( scene, camera ) {
  38819. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  38820. this.viewMatrix = camera.matrixWorldInverse;
  38821. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  38822. }
  38823. /**
  38824. * Updates the clipping context.
  38825. *
  38826. * @param {ClippingContext} parentContext - The parent context.
  38827. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  38828. */
  38829. update( parentContext, clippingGroup ) {
  38830. let update = false;
  38831. if ( parentContext.version !== this.parentVersion ) {
  38832. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  38833. this.unionPlanes = Array.from( parentContext.unionPlanes );
  38834. this.parentVersion = parentContext.version;
  38835. }
  38836. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  38837. this.clipIntersection = clippingGroup.clipIntersection;
  38838. if ( this.clipIntersection ) {
  38839. this.unionPlanes.length = parentContext.unionPlanes.length;
  38840. } else {
  38841. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  38842. }
  38843. }
  38844. const srcClippingPlanes = clippingGroup.clippingPlanes;
  38845. const l = srcClippingPlanes.length;
  38846. let dstClippingPlanes;
  38847. let offset;
  38848. if ( this.clipIntersection ) {
  38849. dstClippingPlanes = this.intersectionPlanes;
  38850. offset = parentContext.intersectionPlanes.length;
  38851. } else {
  38852. dstClippingPlanes = this.unionPlanes;
  38853. offset = parentContext.unionPlanes.length;
  38854. }
  38855. if ( dstClippingPlanes.length !== offset + l ) {
  38856. dstClippingPlanes.length = offset + l;
  38857. for ( let i = 0; i < l; i ++ ) {
  38858. dstClippingPlanes[ offset + i ] = new Vector4();
  38859. }
  38860. update = true;
  38861. }
  38862. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  38863. if ( update ) {
  38864. this.version ++;
  38865. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  38866. }
  38867. }
  38868. /**
  38869. * Returns a clipping context for the given clipping group.
  38870. *
  38871. * @param {ClippingGroup} clippingGroup - The clipping group.
  38872. * @return {ClippingContext} The clipping context.
  38873. */
  38874. getGroupContext( clippingGroup ) {
  38875. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  38876. let context = this.clippingGroupContexts.get( clippingGroup );
  38877. if ( context === undefined ) {
  38878. context = new ClippingContext( this );
  38879. this.clippingGroupContexts.set( clippingGroup, context );
  38880. }
  38881. context.update( this, clippingGroup );
  38882. return context;
  38883. }
  38884. /**
  38885. * The count of union clipping planes.
  38886. *
  38887. * @type {number}
  38888. * @readonly
  38889. */
  38890. get unionClippingCount() {
  38891. return this.unionPlanes.length;
  38892. }
  38893. }
  38894. /**
  38895. * This module is used to represent render bundles inside the renderer
  38896. * for further processing.
  38897. *
  38898. * @private
  38899. */
  38900. class RenderBundle {
  38901. /**
  38902. * Constructs a new bundle group.
  38903. *
  38904. * @param {BundleGroup} bundleGroup - The bundle group.
  38905. * @param {Camera} camera - The camera the bundle group is rendered with.
  38906. */
  38907. constructor( bundleGroup, camera ) {
  38908. this.bundleGroup = bundleGroup;
  38909. this.camera = camera;
  38910. }
  38911. }
  38912. const _chainKeys = [];
  38913. /**
  38914. * This renderer module manages render bundles.
  38915. *
  38916. * @private
  38917. */
  38918. class RenderBundles {
  38919. /**
  38920. * Constructs a new render bundle management component.
  38921. */
  38922. constructor() {
  38923. /**
  38924. * A chain map for maintaining the render bundles.
  38925. *
  38926. * @type {ChainMap}
  38927. */
  38928. this.bundles = new ChainMap();
  38929. }
  38930. /**
  38931. * Returns a render bundle for the given bundle group and camera.
  38932. *
  38933. * @param {BundleGroup} bundleGroup - The bundle group.
  38934. * @param {Camera} camera - The camera the bundle group is rendered with.
  38935. * @return {RenderBundle} The render bundle.
  38936. */
  38937. get( bundleGroup, camera ) {
  38938. const bundles = this.bundles;
  38939. _chainKeys[ 0 ] = bundleGroup;
  38940. _chainKeys[ 1 ] = camera;
  38941. let bundle = bundles.get( _chainKeys );
  38942. if ( bundle === undefined ) {
  38943. bundle = new RenderBundle( bundleGroup, camera );
  38944. bundles.set( _chainKeys, bundle );
  38945. }
  38946. _chainKeys[ 0 ] = null;
  38947. _chainKeys[ 1 ] = null;
  38948. return bundle;
  38949. }
  38950. /**
  38951. * Frees all internal resources.
  38952. */
  38953. dispose() {
  38954. this.bundles = new ChainMap();
  38955. }
  38956. }
  38957. /**
  38958. * The purpose of a node library is to assign node implementations
  38959. * to existing library features. In `WebGPURenderer` lights, materials
  38960. * which are not based on `NodeMaterial` as well as tone mapping techniques
  38961. * are implemented with node-based modules.
  38962. *
  38963. * @private
  38964. */
  38965. class NodeLibrary {
  38966. /**
  38967. * Constructs a new node library.
  38968. */
  38969. constructor() {
  38970. /**
  38971. * A weak map that maps lights to light nodes.
  38972. *
  38973. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  38974. */
  38975. this.lightNodes = new WeakMap();
  38976. /**
  38977. * A map that maps materials to node materials.
  38978. *
  38979. * @type {Map<string,NodeMaterial.constructor>}
  38980. */
  38981. this.materialNodes = new Map();
  38982. /**
  38983. * A map that maps tone mapping techniques (constants)
  38984. * to tone mapping node functions.
  38985. *
  38986. * @type {Map<number,Function>}
  38987. */
  38988. this.toneMappingNodes = new Map();
  38989. }
  38990. /**
  38991. * Returns a matching node material instance for the given material object.
  38992. *
  38993. * This method also assigns/copies the properties of the given material object
  38994. * to the node material. This is done to make sure the current material
  38995. * configuration carries over to the node version.
  38996. *
  38997. * @param {Material} material - A material.
  38998. * @return {NodeMaterial} The corresponding node material.
  38999. */
  39000. fromMaterial( material ) {
  39001. if ( material.isNodeMaterial ) return material;
  39002. let nodeMaterial = null;
  39003. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  39004. if ( nodeMaterialClass !== null ) {
  39005. nodeMaterial = new nodeMaterialClass();
  39006. for ( const key in material ) {
  39007. nodeMaterial[ key ] = material[ key ];
  39008. }
  39009. }
  39010. return nodeMaterial;
  39011. }
  39012. /**
  39013. * Adds a tone mapping node function for a tone mapping technique (constant).
  39014. *
  39015. * @param {Function} toneMappingNode - The tone mapping node function.
  39016. * @param {number} toneMapping - The tone mapping.
  39017. */
  39018. addToneMapping( toneMappingNode, toneMapping ) {
  39019. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  39020. }
  39021. /**
  39022. * Returns a tone mapping node function for a tone mapping technique (constant).
  39023. *
  39024. * @param {number} toneMapping - The tone mapping.
  39025. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  39026. */
  39027. getToneMappingFunction( toneMapping ) {
  39028. return this.toneMappingNodes.get( toneMapping ) || null;
  39029. }
  39030. /**
  39031. * Returns a node material class definition for a material type.
  39032. *
  39033. * @param {string} materialType - The material type.
  39034. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  39035. */
  39036. getMaterialNodeClass( materialType ) {
  39037. return this.materialNodes.get( materialType ) || null;
  39038. }
  39039. /**
  39040. * Adds a node material class definition for a given material type.
  39041. *
  39042. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  39043. * @param {string} materialClassType - The material type.
  39044. */
  39045. addMaterial( materialNodeClass, materialClassType ) {
  39046. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  39047. }
  39048. /**
  39049. * Returns a light node class definition for a light class definition.
  39050. *
  39051. * @param {Light.constructor} light - The light class definition.
  39052. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  39053. */
  39054. getLightNodeClass( light ) {
  39055. return this.lightNodes.get( light ) || null;
  39056. }
  39057. /**
  39058. * Adds a light node class definition for a given light class definition.
  39059. *
  39060. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  39061. * @param {Light.constructor} lightClass - The light class definition.
  39062. */
  39063. addLight( lightNodeClass, lightClass ) {
  39064. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  39065. }
  39066. /**
  39067. * Adds a node class definition for the given type to the provided type library.
  39068. *
  39069. * @param {Node.constructor} nodeClass - The node class definition.
  39070. * @param {number|string} type - The object type.
  39071. * @param {Map<number|string,Node.constructor>} library - The type library.
  39072. */
  39073. addType( nodeClass, type, library ) {
  39074. if ( library.has( type ) ) {
  39075. warn( `Redefinition of node ${ type }` );
  39076. return;
  39077. }
  39078. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39079. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  39080. library.set( type, nodeClass );
  39081. }
  39082. /**
  39083. * Adds a node class definition for the given class definition to the provided type library.
  39084. *
  39085. * @param {Node.constructor} nodeClass - The node class definition.
  39086. * @param {Node.constructor} baseClass - The class definition.
  39087. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  39088. */
  39089. addClass( nodeClass, baseClass, library ) {
  39090. if ( library.has( baseClass ) ) {
  39091. warn( `Redefinition of node ${ baseClass.name }` );
  39092. return;
  39093. }
  39094. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39095. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  39096. library.set( baseClass, nodeClass );
  39097. }
  39098. }
  39099. const _defaultLights = /*@__PURE__*/ new LightsNode();
  39100. const _weakMap = /*@__PURE__*/ new WeakMap();
  39101. /**
  39102. * This renderer module manages the lights nodes which are unique
  39103. * per scene and camera combination.
  39104. *
  39105. * The lights node itself is later configured in the render list
  39106. * with the actual lights from the scene.
  39107. *
  39108. * @private
  39109. */
  39110. class Lighting {
  39111. /**
  39112. * Creates a new lights node for the given array of lights.
  39113. *
  39114. * @param {Array<Light>} lights - The render object.
  39115. * @return {LightsNode} The lights node.
  39116. */
  39117. createNode( lights = [] ) {
  39118. return new LightsNode().setLights( lights );
  39119. }
  39120. /**
  39121. * Returns a lights node for the given scene and camera.
  39122. *
  39123. * @param {Scene} scene - The scene.
  39124. * @param {Camera} camera - The camera.
  39125. * @return {LightsNode} The lights node.
  39126. */
  39127. getNode( scene ) {
  39128. // ignore post-processing
  39129. if ( scene.isQuadMesh ) return _defaultLights;
  39130. let node = _weakMap.get( scene );
  39131. if ( node === undefined ) {
  39132. node = this.createNode();
  39133. _weakMap.set( scene, node );
  39134. }
  39135. return node;
  39136. }
  39137. }
  39138. /**
  39139. * A special type of render target that is used when rendering
  39140. * with the WebXR Device API.
  39141. *
  39142. * @private
  39143. * @augments RenderTarget
  39144. */
  39145. class XRRenderTarget extends RenderTarget {
  39146. /**
  39147. * Constructs a new XR render target.
  39148. *
  39149. * @param {number} [width=1] - The width of the render target.
  39150. * @param {number} [height=1] - The height of the render target.
  39151. * @param {Object} [options={}] - The configuration options.
  39152. */
  39153. constructor( width = 1, height = 1, options = {} ) {
  39154. super( width, height, options );
  39155. /**
  39156. * This flag can be used for type testing.
  39157. *
  39158. * @type {boolean}
  39159. * @readonly
  39160. * @default true
  39161. */
  39162. this.isXRRenderTarget = true;
  39163. /**
  39164. * Whether the attachments of the render target
  39165. * are defined by external textures. This flag is
  39166. * set to `true` when using the WebXR Layers API.
  39167. *
  39168. * @private
  39169. * @type {boolean}
  39170. * @default false
  39171. */
  39172. this._hasExternalTextures = false;
  39173. /**
  39174. * Whether a depth buffer should automatically be allocated
  39175. * for this XR render target or not.
  39176. *
  39177. * Allocating a depth buffer is the default behavior of XR render
  39178. * targets. However, when using the WebXR Layers API, this flag
  39179. * must be set to `false` when the `ignoreDepthValues` property of
  39180. * the projection layers evaluates to `false`.
  39181. *
  39182. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  39183. *
  39184. * @private
  39185. * @type {boolean}
  39186. * @default true
  39187. */
  39188. this._autoAllocateDepthBuffer = true;
  39189. /**
  39190. * Whether this render target is associated with a XRWebGLLayer.
  39191. *
  39192. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  39193. * this means that you don't have access to its bound color,
  39194. * stencil and depth buffers. We need to handle this framebuffer
  39195. * differently since its textures are always bound.
  39196. *
  39197. * @private
  39198. * @type {boolean}
  39199. * @default false
  39200. * */
  39201. this._isOpaqueFramebuffer = false;
  39202. }
  39203. copy( source ) {
  39204. super.copy( source );
  39205. this._hasExternalTextures = source._hasExternalTextures;
  39206. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  39207. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  39208. return this;
  39209. }
  39210. }
  39211. const _cameraLPos = /*@__PURE__*/ new Vector3();
  39212. const _cameraRPos = /*@__PURE__*/ new Vector3();
  39213. /**
  39214. * The XR manager is built on top of the WebXR Device API to
  39215. * manage XR sessions with `WebGPURenderer`.
  39216. *
  39217. * XR is currently only supported with a WebGL 2 backend.
  39218. *
  39219. * @augments EventDispatcher
  39220. */
  39221. class XRManager extends EventDispatcher {
  39222. /**
  39223. * Constructs a new XR manager.
  39224. *
  39225. * @param {Renderer} renderer - The renderer.
  39226. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  39227. */
  39228. constructor( renderer, multiview = false ) {
  39229. super();
  39230. /**
  39231. * This flag globally enables XR rendering.
  39232. *
  39233. * @type {boolean}
  39234. * @default false
  39235. */
  39236. this.enabled = false;
  39237. /**
  39238. * Whether the XR device is currently presenting or not.
  39239. *
  39240. * @type {boolean}
  39241. * @default false
  39242. * @readonly
  39243. */
  39244. this.isPresenting = false;
  39245. /**
  39246. * Whether the XR camera should automatically be updated or not.
  39247. *
  39248. * @type {boolean}
  39249. * @default true
  39250. */
  39251. this.cameraAutoUpdate = true;
  39252. /**
  39253. * The renderer.
  39254. *
  39255. * @private
  39256. * @type {Renderer}
  39257. */
  39258. this._renderer = renderer;
  39259. // camera
  39260. /**
  39261. * Represents the camera for the left eye.
  39262. *
  39263. * @private
  39264. * @type {PerspectiveCamera}
  39265. */
  39266. this._cameraL = new PerspectiveCamera();
  39267. this._cameraL.viewport = new Vector4();
  39268. /**
  39269. * Represents the camera for the right eye.
  39270. *
  39271. * @private
  39272. * @type {PerspectiveCamera}
  39273. */
  39274. this._cameraR = new PerspectiveCamera();
  39275. this._cameraR.viewport = new Vector4();
  39276. /**
  39277. * A list of cameras used for rendering the XR views.
  39278. *
  39279. * @private
  39280. * @type {Array<Camera>}
  39281. */
  39282. this._cameras = [ this._cameraL, this._cameraR ];
  39283. /**
  39284. * The main XR camera.
  39285. *
  39286. * @private
  39287. * @type {ArrayCamera}
  39288. */
  39289. this._cameraXR = new ArrayCamera();
  39290. /**
  39291. * The current near value of the XR camera.
  39292. *
  39293. * @private
  39294. * @type {?number}
  39295. * @default null
  39296. */
  39297. this._currentDepthNear = null;
  39298. /**
  39299. * The current far value of the XR camera.
  39300. *
  39301. * @private
  39302. * @type {?number}
  39303. * @default null
  39304. */
  39305. this._currentDepthFar = null;
  39306. /**
  39307. * A list of WebXR controllers requested by the application.
  39308. *
  39309. * @private
  39310. * @type {Array<WebXRController>}
  39311. */
  39312. this._controllers = [];
  39313. /**
  39314. * A list of XR input source. Each input source belongs to
  39315. * an instance of WebXRController.
  39316. *
  39317. * @private
  39318. * @type {Array<XRInputSource?>}
  39319. */
  39320. this._controllerInputSources = [];
  39321. /**
  39322. * The XR render target that represents the rendering destination
  39323. * during an active XR session.
  39324. *
  39325. * @private
  39326. * @type {?RenderTarget}
  39327. * @default null
  39328. */
  39329. this._xrRenderTarget = null;
  39330. /**
  39331. * An array holding all the non-projection layers
  39332. *
  39333. * @private
  39334. * @type {Array<Object>}
  39335. * @default []
  39336. */
  39337. this._layers = [];
  39338. /**
  39339. * Whether the XR session uses layers.
  39340. *
  39341. * @private
  39342. * @type {boolean}
  39343. * @default false
  39344. */
  39345. this._sessionUsesLayers = false;
  39346. /**
  39347. * Whether the device supports binding gl objects.
  39348. *
  39349. * @private
  39350. * @type {boolean}
  39351. * @readonly
  39352. */
  39353. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  39354. this._frameBufferTargets = null;
  39355. /**
  39356. * Helper function to create native WebXR Layer.
  39357. *
  39358. * @private
  39359. * @type {Function}
  39360. */
  39361. this._createXRLayer = createXRLayer.bind( this );
  39362. /**
  39363. * The current WebGL context.
  39364. *
  39365. * @private
  39366. * @type {?WebGL2RenderingContext}
  39367. * @default null
  39368. */
  39369. this._gl = null;
  39370. /**
  39371. * The current animation context.
  39372. *
  39373. * @private
  39374. * @type {?Window}
  39375. * @default null
  39376. */
  39377. this._currentAnimationContext = null;
  39378. /**
  39379. * The current animation loop.
  39380. *
  39381. * @private
  39382. * @type {?Function}
  39383. * @default null
  39384. */
  39385. this._currentAnimationLoop = null;
  39386. /**
  39387. * The current pixel ratio.
  39388. *
  39389. * @private
  39390. * @type {?number}
  39391. * @default null
  39392. */
  39393. this._currentPixelRatio = null;
  39394. /**
  39395. * The current size of the renderer's canvas
  39396. * in logical pixel unit.
  39397. *
  39398. * @private
  39399. * @type {Vector2}
  39400. */
  39401. this._currentSize = new Vector2();
  39402. /**
  39403. * The default event listener for handling events inside a XR session.
  39404. *
  39405. * @private
  39406. * @type {Function}
  39407. */
  39408. this._onSessionEvent = onSessionEvent.bind( this );
  39409. /**
  39410. * The event listener for handling the end of a XR session.
  39411. *
  39412. * @private
  39413. * @type {Function}
  39414. */
  39415. this._onSessionEnd = onSessionEnd.bind( this );
  39416. /**
  39417. * The event listener for handling the `inputsourceschange` event.
  39418. *
  39419. * @private
  39420. * @type {Function}
  39421. */
  39422. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  39423. /**
  39424. * The animation loop which is used as a replacement for the default
  39425. * animation loop of the application. It is only used when a XR session
  39426. * is active.
  39427. *
  39428. * @private
  39429. * @type {Function}
  39430. */
  39431. this._onAnimationFrame = onAnimationFrame.bind( this );
  39432. /**
  39433. * The current XR reference space.
  39434. *
  39435. * @private
  39436. * @type {?XRReferenceSpace}
  39437. * @default null
  39438. */
  39439. this._referenceSpace = null;
  39440. /**
  39441. * The current XR reference space type.
  39442. *
  39443. * @private
  39444. * @type {XRReferenceSpaceType}
  39445. * @default 'local-floor'
  39446. */
  39447. this._referenceSpaceType = 'local-floor';
  39448. /**
  39449. * A custom reference space defined by the application.
  39450. *
  39451. * @private
  39452. * @type {?XRReferenceSpace}
  39453. * @default null
  39454. */
  39455. this._customReferenceSpace = null;
  39456. /**
  39457. * The framebuffer scale factor.
  39458. *
  39459. * @private
  39460. * @type {number}
  39461. * @default 1
  39462. */
  39463. this._framebufferScaleFactor = 1;
  39464. /**
  39465. * The foveation factor.
  39466. *
  39467. * @private
  39468. * @type {number}
  39469. * @default 1
  39470. */
  39471. this._foveation = 1.0;
  39472. /**
  39473. * A reference to the current XR session.
  39474. *
  39475. * @private
  39476. * @type {?XRSession}
  39477. * @default null
  39478. */
  39479. this._session = null;
  39480. /**
  39481. * A reference to the current XR base layer.
  39482. *
  39483. * @private
  39484. * @type {?XRWebGLLayer}
  39485. * @default null
  39486. */
  39487. this._glBaseLayer = null;
  39488. /**
  39489. * A reference to the current XR binding.
  39490. *
  39491. * @private
  39492. * @type {?XRWebGLBinding}
  39493. * @default null
  39494. */
  39495. this._glBinding = null;
  39496. /**
  39497. * A reference to the current XR projection layer.
  39498. *
  39499. * @private
  39500. * @type {?XRProjectionLayer}
  39501. * @default null
  39502. */
  39503. this._glProjLayer = null;
  39504. /**
  39505. * A reference to the current XR frame.
  39506. *
  39507. * @private
  39508. * @type {?XRFrame}
  39509. * @default null
  39510. */
  39511. this._xrFrame = null;
  39512. /**
  39513. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  39514. *
  39515. * Note: this does not represent XRSession explicitly requesting
  39516. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  39517. *
  39518. * @private
  39519. * @type {boolean}
  39520. * @readonly
  39521. */
  39522. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  39523. /**
  39524. * Whether the usage of multiview has been requested by the application or not.
  39525. *
  39526. * @private
  39527. * @type {boolean}
  39528. * @default false
  39529. * @readonly
  39530. */
  39531. this._useMultiviewIfPossible = multiview;
  39532. /**
  39533. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  39534. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  39535. *
  39536. * @private
  39537. * @type {boolean}
  39538. * @readonly
  39539. */
  39540. this._useMultiview = false;
  39541. }
  39542. /**
  39543. * Returns an instance of `THREE.Group` that represents the transformation
  39544. * of a XR controller in target ray space. The requested controller is defined
  39545. * by the given index.
  39546. *
  39547. * @param {number} index - The index of the XR controller.
  39548. * @return {Group} A group that represents the controller's transformation.
  39549. */
  39550. getController( index ) {
  39551. const controller = this._getController( index );
  39552. return controller.getTargetRaySpace();
  39553. }
  39554. /**
  39555. * Returns an instance of `THREE.Group` that represents the transformation
  39556. * of a XR controller in grip space. The requested controller is defined
  39557. * by the given index.
  39558. *
  39559. * @param {number} index - The index of the XR controller.
  39560. * @return {Group} A group that represents the controller's transformation.
  39561. */
  39562. getControllerGrip( index ) {
  39563. const controller = this._getController( index );
  39564. return controller.getGripSpace();
  39565. }
  39566. /**
  39567. * Returns an instance of `THREE.Group` that represents the transformation
  39568. * of a XR controller in hand space. The requested controller is defined
  39569. * by the given index.
  39570. *
  39571. * @param {number} index - The index of the XR controller.
  39572. * @return {Group} A group that represents the controller's transformation.
  39573. */
  39574. getHand( index ) {
  39575. const controller = this._getController( index );
  39576. return controller.getHandSpace();
  39577. }
  39578. /**
  39579. * Returns the foveation value.
  39580. *
  39581. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  39582. */
  39583. getFoveation() {
  39584. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  39585. return undefined;
  39586. }
  39587. return this._foveation;
  39588. }
  39589. /**
  39590. * Sets the foveation value.
  39591. *
  39592. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  39593. * and `1` means maximum foveation (the edges render at lower resolution).
  39594. */
  39595. setFoveation( foveation ) {
  39596. this._foveation = foveation;
  39597. if ( this._glProjLayer !== null ) {
  39598. this._glProjLayer.fixedFoveation = foveation;
  39599. }
  39600. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  39601. this._glBaseLayer.fixedFoveation = foveation;
  39602. }
  39603. }
  39604. /**
  39605. * Returns the framebuffer scale factor.
  39606. *
  39607. * @return {number} The framebuffer scale factor.
  39608. */
  39609. getFramebufferScaleFactor() {
  39610. return this._framebufferScaleFactor;
  39611. }
  39612. /**
  39613. * Sets the framebuffer scale factor.
  39614. *
  39615. * This method can not be used during a XR session.
  39616. *
  39617. * @param {number} factor - The framebuffer scale factor.
  39618. */
  39619. setFramebufferScaleFactor( factor ) {
  39620. this._framebufferScaleFactor = factor;
  39621. if ( this.isPresenting === true ) {
  39622. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  39623. }
  39624. }
  39625. /**
  39626. * Returns the reference space type.
  39627. *
  39628. * @return {XRReferenceSpaceType} The reference space type.
  39629. */
  39630. getReferenceSpaceType() {
  39631. return this._referenceSpaceType;
  39632. }
  39633. /**
  39634. * Sets the reference space type.
  39635. *
  39636. * This method can not be used during a XR session.
  39637. *
  39638. * @param {XRReferenceSpaceType} type - The reference space type.
  39639. */
  39640. setReferenceSpaceType( type ) {
  39641. this._referenceSpaceType = type;
  39642. if ( this.isPresenting === true ) {
  39643. warn( 'XRManager: Cannot change reference space type while presenting.' );
  39644. }
  39645. }
  39646. /**
  39647. * Returns the XR reference space.
  39648. *
  39649. * @return {XRReferenceSpace} The XR reference space.
  39650. */
  39651. getReferenceSpace() {
  39652. return this._customReferenceSpace || this._referenceSpace;
  39653. }
  39654. /**
  39655. * Sets a custom XR reference space.
  39656. *
  39657. * @param {XRReferenceSpace} space - The XR reference space.
  39658. */
  39659. setReferenceSpace( space ) {
  39660. this._customReferenceSpace = space;
  39661. }
  39662. /**
  39663. * Returns the XR camera.
  39664. *
  39665. * @return {ArrayCamera} The XR camera.
  39666. */
  39667. getCamera() {
  39668. return this._cameraXR;
  39669. }
  39670. /**
  39671. * Returns the environment blend mode from the current XR session.
  39672. *
  39673. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  39674. */
  39675. getEnvironmentBlendMode() {
  39676. if ( this._session !== null ) {
  39677. return this._session.environmentBlendMode;
  39678. }
  39679. }
  39680. /**
  39681. * Returns the current XR binding.
  39682. *
  39683. * Creates a new binding if needed and the browser is
  39684. * capable of doing so.
  39685. *
  39686. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  39687. */
  39688. getBinding() {
  39689. if ( this._glBinding === null && this._supportsGlBinding ) {
  39690. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  39691. }
  39692. return this._glBinding;
  39693. }
  39694. /**
  39695. * Returns the current XR frame.
  39696. *
  39697. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  39698. */
  39699. getFrame() {
  39700. return this._xrFrame;
  39701. }
  39702. /**
  39703. * Returns `true` if the engine renders to a multiview target.
  39704. *
  39705. * @return {boolean} Whether the engine renders to a multiview render target or not.
  39706. */
  39707. useMultiview() {
  39708. return this._useMultiview;
  39709. }
  39710. /**
  39711. * This method can be used in XR applications to create a quadratic layer that presents a separate
  39712. * rendered scene.
  39713. *
  39714. * @param {number} width - The width of the layer plane in world units.
  39715. * @param {number} height - The height of the layer plane in world units.
  39716. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  39717. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  39718. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  39719. * @param {number} pixelheight - The height of the layer's render target in pixels.
  39720. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  39721. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  39722. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  39723. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  39724. */
  39725. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  39726. const geometry = new PlaneGeometry( width, height );
  39727. const renderTarget = new XRRenderTarget(
  39728. pixelwidth,
  39729. pixelheight,
  39730. {
  39731. format: RGBAFormat,
  39732. type: UnsignedByteType,
  39733. depthTexture: new DepthTexture(
  39734. pixelwidth,
  39735. pixelheight,
  39736. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  39737. undefined,
  39738. undefined,
  39739. undefined,
  39740. undefined,
  39741. undefined,
  39742. undefined,
  39743. attributes.stencil ? DepthStencilFormat : DepthFormat
  39744. ),
  39745. stencilBuffer: attributes.stencil,
  39746. resolveDepthBuffer: false,
  39747. resolveStencilBuffer: false
  39748. } );
  39749. renderTarget._autoAllocateDepthBuffer = true;
  39750. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  39751. material.map = renderTarget.texture;
  39752. material.map.offset.y = 1;
  39753. material.map.repeat.y = -1;
  39754. const plane = new Mesh( geometry, material );
  39755. plane.position.copy( translation );
  39756. plane.quaternion.copy( quaternion );
  39757. const layer = {
  39758. type: 'quad',
  39759. width: width,
  39760. height: height,
  39761. translation: translation,
  39762. quaternion: quaternion,
  39763. pixelwidth: pixelwidth,
  39764. pixelheight: pixelheight,
  39765. plane: plane,
  39766. material: material,
  39767. rendercall: rendercall,
  39768. renderTarget: renderTarget };
  39769. this._layers.push( layer );
  39770. if ( this._session !== null ) {
  39771. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  39772. layer.plane.material.blending = CustomBlending;
  39773. layer.plane.material.blendEquation = AddEquation;
  39774. layer.plane.material.blendSrc = ZeroFactor;
  39775. layer.plane.material.blendDst = ZeroFactor;
  39776. layer.xrlayer = this._createXRLayer( layer );
  39777. const xrlayers = this._session.renderState.layers;
  39778. xrlayers.unshift( layer.xrlayer );
  39779. this._session.updateRenderState( { layers: xrlayers } );
  39780. } else {
  39781. renderTarget.isXRRenderTarget = false;
  39782. }
  39783. return plane;
  39784. }
  39785. /**
  39786. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  39787. * rendered scene.
  39788. *
  39789. * @param {number} radius - The radius of the cylinder in world units.
  39790. * @param {number} centralAngle - The central angle of the cylinder in radians.
  39791. * @param {number} aspectratio - The aspect ratio.
  39792. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  39793. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  39794. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  39795. * @param {number} pixelheight - The height of the layer's render target in pixels.
  39796. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  39797. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  39798. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  39799. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  39800. */
  39801. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  39802. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  39803. const renderTarget = new XRRenderTarget(
  39804. pixelwidth,
  39805. pixelheight,
  39806. {
  39807. format: RGBAFormat,
  39808. type: UnsignedByteType,
  39809. depthTexture: new DepthTexture(
  39810. pixelwidth,
  39811. pixelheight,
  39812. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  39813. undefined,
  39814. undefined,
  39815. undefined,
  39816. undefined,
  39817. undefined,
  39818. undefined,
  39819. attributes.stencil ? DepthStencilFormat : DepthFormat
  39820. ),
  39821. stencilBuffer: attributes.stencil,
  39822. resolveDepthBuffer: false,
  39823. resolveStencilBuffer: false
  39824. } );
  39825. renderTarget._autoAllocateDepthBuffer = true;
  39826. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  39827. material.map = renderTarget.texture;
  39828. material.map.offset.y = 1;
  39829. material.map.repeat.y = -1;
  39830. const plane = new Mesh( geometry, material );
  39831. plane.position.copy( translation );
  39832. plane.quaternion.copy( quaternion );
  39833. const layer = {
  39834. type: 'cylinder',
  39835. radius: radius,
  39836. centralAngle: centralAngle,
  39837. aspectratio: aspectratio,
  39838. translation: translation,
  39839. quaternion: quaternion,
  39840. pixelwidth: pixelwidth,
  39841. pixelheight: pixelheight,
  39842. plane: plane,
  39843. material: material,
  39844. rendercall: rendercall,
  39845. renderTarget: renderTarget };
  39846. this._layers.push( layer );
  39847. if ( this._session !== null ) {
  39848. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  39849. layer.plane.material.blending = CustomBlending;
  39850. layer.plane.material.blendEquation = AddEquation;
  39851. layer.plane.material.blendSrc = ZeroFactor;
  39852. layer.plane.material.blendDst = ZeroFactor;
  39853. layer.xrlayer = this._createXRLayer( layer );
  39854. const xrlayers = this._session.renderState.layers;
  39855. xrlayers.unshift( layer.xrlayer );
  39856. this._session.updateRenderState( { layers: xrlayers } );
  39857. } else {
  39858. renderTarget.isXRRenderTarget = false;
  39859. }
  39860. return plane;
  39861. }
  39862. /**
  39863. * Renders the XR layers that have been previously added to the scene.
  39864. *
  39865. * This method is usually called in your animation loop before rendering
  39866. * the actual scene via `renderer.render( scene, camera );`.
  39867. */
  39868. renderLayers( ) {
  39869. const translationObject = new Vector3();
  39870. const quaternionObject = new Quaternion();
  39871. const renderer = this._renderer;
  39872. const wasPresenting = this.isPresenting;
  39873. const rendererOutputTarget = renderer.getOutputRenderTarget();
  39874. const rendererFramebufferTarget = renderer._frameBufferTarget;
  39875. this.isPresenting = false;
  39876. const rendererSize = new Vector2();
  39877. renderer.getSize( rendererSize );
  39878. const rendererQuad = renderer._quad;
  39879. for ( const layer of this._layers ) {
  39880. layer.renderTarget.isXRRenderTarget = this._session !== null;
  39881. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  39882. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  39883. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  39884. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  39885. renderer.backend.setXRRenderTargetTextures(
  39886. layer.renderTarget,
  39887. glSubImage.colorTexture,
  39888. undefined );
  39889. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  39890. renderer.setOutputRenderTarget( layer.renderTarget );
  39891. renderer.setRenderTarget( null );
  39892. renderer._frameBufferTarget = null;
  39893. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  39894. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  39895. if ( ! frameBufferTarget ) {
  39896. renderer._quad = new QuadMesh( new NodeMaterial() );
  39897. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  39898. } else {
  39899. renderer._frameBufferTarget = frameBufferTarget;
  39900. renderer._quad = quad;
  39901. }
  39902. layer.rendercall();
  39903. renderer._frameBufferTarget = null;
  39904. } else {
  39905. renderer.setRenderTarget( layer.renderTarget );
  39906. layer.rendercall();
  39907. }
  39908. }
  39909. renderer.setRenderTarget( null );
  39910. renderer.setOutputRenderTarget( rendererOutputTarget );
  39911. renderer._frameBufferTarget = rendererFramebufferTarget;
  39912. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  39913. renderer._quad = rendererQuad;
  39914. this.isPresenting = wasPresenting;
  39915. }
  39916. /**
  39917. * Returns the current XR session.
  39918. *
  39919. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  39920. */
  39921. getSession() {
  39922. return this._session;
  39923. }
  39924. /**
  39925. * After a XR session has been requested usually with one of the `*Button` modules, it
  39926. * is injected into the renderer with this method. This method triggers the start of
  39927. * the actual XR rendering.
  39928. *
  39929. * @async
  39930. * @param {XRSession} session - The XR session to set.
  39931. * @return {Promise} A Promise that resolves when the session has been set.
  39932. */
  39933. async setSession( session ) {
  39934. const renderer = this._renderer;
  39935. const backend = renderer.backend;
  39936. this._gl = renderer.getContext();
  39937. const gl = this._gl;
  39938. const attributes = gl.getContextAttributes();
  39939. this._session = session;
  39940. if ( session !== null ) {
  39941. 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.' );
  39942. session.addEventListener( 'select', this._onSessionEvent );
  39943. session.addEventListener( 'selectstart', this._onSessionEvent );
  39944. session.addEventListener( 'selectend', this._onSessionEvent );
  39945. session.addEventListener( 'squeeze', this._onSessionEvent );
  39946. session.addEventListener( 'squeezestart', this._onSessionEvent );
  39947. session.addEventListener( 'squeezeend', this._onSessionEvent );
  39948. session.addEventListener( 'end', this._onSessionEnd );
  39949. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  39950. await backend.makeXRCompatible();
  39951. this._currentPixelRatio = renderer.getPixelRatio();
  39952. renderer.getSize( this._currentSize );
  39953. this._currentAnimationContext = renderer._animation.getContext();
  39954. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  39955. renderer._animation.stop();
  39956. //
  39957. if ( this._supportsLayers === true ) {
  39958. // default path using XRProjectionLayer
  39959. let depthFormat = null;
  39960. let depthType = null;
  39961. let glDepthFormat = null;
  39962. if ( renderer.depth ) {
  39963. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  39964. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  39965. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  39966. }
  39967. const projectionlayerInit = {
  39968. colorFormat: gl.RGBA8,
  39969. depthFormat: glDepthFormat,
  39970. scaleFactor: this._framebufferScaleFactor,
  39971. clearOnAccess: false
  39972. };
  39973. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  39974. projectionlayerInit.textureType = 'texture-array';
  39975. this._useMultiview = true;
  39976. }
  39977. this._glBinding = this.getBinding();
  39978. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  39979. const layersArray = [ glProjLayer ];
  39980. this._glProjLayer = glProjLayer;
  39981. renderer.setPixelRatio( 1 );
  39982. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  39983. const depth = this._useMultiview ? 2 : 1;
  39984. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  39985. this._xrRenderTarget = new XRRenderTarget(
  39986. glProjLayer.textureWidth,
  39987. glProjLayer.textureHeight,
  39988. {
  39989. format: RGBAFormat,
  39990. type: UnsignedByteType,
  39991. colorSpace: renderer.outputColorSpace,
  39992. depthTexture: depthTexture,
  39993. stencilBuffer: renderer.stencil,
  39994. samples: attributes.antialias ? 4 : 0,
  39995. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  39996. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  39997. depth: this._useMultiview ? 2 : 1,
  39998. multiview: this._useMultiview
  39999. } );
  40000. this._xrRenderTarget._hasExternalTextures = true;
  40001. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  40002. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  40003. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40004. if ( this._sessionUsesLayers ) {
  40005. // switch layers to native
  40006. for ( const layer of this._layers ) {
  40007. // change material so it "punches" out a hole to show the XR Layer.
  40008. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  40009. layer.plane.material.blending = CustomBlending;
  40010. layer.plane.material.blendEquation = AddEquation;
  40011. layer.plane.material.blendSrc = ZeroFactor;
  40012. layer.plane.material.blendDst = ZeroFactor;
  40013. layer.xrlayer = this._createXRLayer( layer );
  40014. layersArray.unshift( layer.xrlayer );
  40015. }
  40016. }
  40017. session.updateRenderState( { layers: layersArray } );
  40018. } else {
  40019. // fallback to XRWebGLLayer
  40020. const layerInit = {
  40021. antialias: renderer.currentSamples > 0,
  40022. alpha: true,
  40023. depth: renderer.depth,
  40024. stencil: renderer.stencil,
  40025. framebufferScaleFactor: this.getFramebufferScaleFactor()
  40026. };
  40027. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  40028. this._glBaseLayer = glBaseLayer;
  40029. session.updateRenderState( { baseLayer: glBaseLayer } );
  40030. renderer.setPixelRatio( 1 );
  40031. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  40032. this._xrRenderTarget = new XRRenderTarget(
  40033. glBaseLayer.framebufferWidth,
  40034. glBaseLayer.framebufferHeight,
  40035. {
  40036. format: RGBAFormat,
  40037. type: UnsignedByteType,
  40038. colorSpace: renderer.outputColorSpace,
  40039. stencilBuffer: renderer.stencil,
  40040. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40041. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40042. }
  40043. );
  40044. this._xrRenderTarget._isOpaqueFramebuffer = true;
  40045. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40046. }
  40047. //
  40048. this.setFoveation( this.getFoveation() );
  40049. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  40050. renderer._animation.setContext( session );
  40051. renderer._animation.start();
  40052. this.isPresenting = true;
  40053. this.dispatchEvent( { type: 'sessionstart' } );
  40054. }
  40055. }
  40056. /**
  40057. * This method is called by the renderer per frame and updates the XR camera
  40058. * and it sub cameras based on the given camera. The given camera is the "user"
  40059. * camera created on application level and used for non-XR rendering.
  40060. *
  40061. * @param {PerspectiveCamera} camera - The camera.
  40062. */
  40063. updateCamera( camera ) {
  40064. const session = this._session;
  40065. if ( session === null ) return;
  40066. const depthNear = camera.near;
  40067. const depthFar = camera.far;
  40068. const cameraXR = this._cameraXR;
  40069. const cameraL = this._cameraL;
  40070. const cameraR = this._cameraR;
  40071. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  40072. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  40073. cameraXR.isMultiViewCamera = this._useMultiview;
  40074. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  40075. // Note that the new renderState won't apply until the next frame. See #18320
  40076. session.updateRenderState( {
  40077. depthNear: cameraXR.near,
  40078. depthFar: cameraXR.far
  40079. } );
  40080. this._currentDepthNear = cameraXR.near;
  40081. this._currentDepthFar = cameraXR.far;
  40082. }
  40083. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  40084. cameraXR.layers.mask = camera.layers.mask | 0b110;
  40085. cameraL.layers.mask = cameraXR.layers.mask & -5;
  40086. cameraR.layers.mask = cameraXR.layers.mask & -3;
  40087. const parent = camera.parent;
  40088. const cameras = cameraXR.cameras;
  40089. updateCamera( cameraXR, parent );
  40090. for ( let i = 0; i < cameras.length; i ++ ) {
  40091. updateCamera( cameras[ i ], parent );
  40092. }
  40093. // update projection matrix for proper view frustum culling
  40094. if ( cameras.length === 2 ) {
  40095. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  40096. } else {
  40097. // assume single camera setup (AR)
  40098. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  40099. }
  40100. // update user camera and its children
  40101. updateUserCamera( camera, cameraXR, parent );
  40102. }
  40103. /**
  40104. * Returns a WebXR controller for the given controller index.
  40105. *
  40106. * @private
  40107. * @param {number} index - The controller index.
  40108. * @return {WebXRController} The XR controller.
  40109. */
  40110. _getController( index ) {
  40111. let controller = this._controllers[ index ];
  40112. if ( controller === undefined ) {
  40113. controller = new WebXRController();
  40114. this._controllers[ index ] = controller;
  40115. }
  40116. return controller;
  40117. }
  40118. }
  40119. /**
  40120. * Assumes 2 cameras that are parallel and share an X-axis, and that
  40121. * the cameras' projection and world matrices have already been set.
  40122. * And that near and far planes are identical for both cameras.
  40123. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  40124. *
  40125. * @param {ArrayCamera} camera - The camera to update.
  40126. * @param {PerspectiveCamera} cameraL - The left camera.
  40127. * @param {PerspectiveCamera} cameraR - The right camera.
  40128. */
  40129. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  40130. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  40131. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  40132. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  40133. const projL = cameraL.projectionMatrix.elements;
  40134. const projR = cameraR.projectionMatrix.elements;
  40135. // VR systems will have identical far and near planes, and
  40136. // most likely identical top and bottom frustum extents.
  40137. // Use the left camera for these values.
  40138. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  40139. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  40140. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  40141. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  40142. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  40143. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  40144. const left = near * leftFov;
  40145. const right = near * rightFov;
  40146. // Calculate the new camera's position offset from the
  40147. // left camera. xOffset should be roughly half `ipd`.
  40148. const zOffset = ipd / ( - leftFov + rightFov );
  40149. const xOffset = zOffset * - leftFov;
  40150. // TODO: Better way to apply this offset?
  40151. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  40152. camera.translateX( xOffset );
  40153. camera.translateZ( zOffset );
  40154. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  40155. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40156. // Check if the projection uses an infinite far plane.
  40157. if ( projL[ 10 ] === -1 ) {
  40158. // Use the projection matrix from the left eye.
  40159. // The camera offset is sufficient to include the view volumes
  40160. // of both eyes (assuming symmetric projections).
  40161. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  40162. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  40163. } else {
  40164. // Find the union of the frustum values of the cameras and scale
  40165. // the values so that the near plane's position does not change in world space,
  40166. // although must now be relative to the new union camera.
  40167. const near2 = near + zOffset;
  40168. const far2 = far + zOffset;
  40169. const left2 = left - xOffset;
  40170. const right2 = right + ( ipd - xOffset );
  40171. const top2 = topFov * far / far2 * near2;
  40172. const bottom2 = bottomFov * far / far2 * near2;
  40173. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  40174. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40175. }
  40176. }
  40177. /**
  40178. * Updates the world matrices for the given camera based on the parent 3D object.
  40179. *
  40180. * @inner
  40181. * @param {Camera} camera - The camera to update.
  40182. * @param {Object3D} parent - The parent 3D object.
  40183. */
  40184. function updateCamera( camera, parent ) {
  40185. if ( parent === null ) {
  40186. camera.matrixWorld.copy( camera.matrix );
  40187. } else {
  40188. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  40189. }
  40190. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40191. }
  40192. /**
  40193. * Updates the given camera with the transformation of the XR camera and parent object.
  40194. *
  40195. * @inner
  40196. * @param {Camera} camera - The camera to update.
  40197. * @param {ArrayCamera} cameraXR - The XR camera.
  40198. * @param {Object3D} parent - The parent 3D object.
  40199. */
  40200. function updateUserCamera( camera, cameraXR, parent ) {
  40201. if ( parent === null ) {
  40202. camera.matrix.copy( cameraXR.matrixWorld );
  40203. } else {
  40204. camera.matrix.copy( parent.matrixWorld );
  40205. camera.matrix.invert();
  40206. camera.matrix.multiply( cameraXR.matrixWorld );
  40207. }
  40208. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40209. camera.updateMatrixWorld( true );
  40210. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  40211. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  40212. if ( camera.isPerspectiveCamera ) {
  40213. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  40214. camera.zoom = 1;
  40215. }
  40216. }
  40217. function onSessionEvent( event ) {
  40218. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  40219. if ( controllerIndex === -1 ) {
  40220. return;
  40221. }
  40222. const controller = this._controllers[ controllerIndex ];
  40223. if ( controller !== undefined ) {
  40224. const referenceSpace = this.getReferenceSpace();
  40225. controller.update( event.inputSource, event.frame, referenceSpace );
  40226. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  40227. }
  40228. }
  40229. function onSessionEnd() {
  40230. const session = this._session;
  40231. const renderer = this._renderer;
  40232. session.removeEventListener( 'select', this._onSessionEvent );
  40233. session.removeEventListener( 'selectstart', this._onSessionEvent );
  40234. session.removeEventListener( 'selectend', this._onSessionEvent );
  40235. session.removeEventListener( 'squeeze', this._onSessionEvent );
  40236. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  40237. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  40238. session.removeEventListener( 'end', this._onSessionEnd );
  40239. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40240. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40241. const inputSource = this._controllerInputSources[ i ];
  40242. if ( inputSource === null ) continue;
  40243. this._controllerInputSources[ i ] = null;
  40244. this._controllers[ i ].disconnect( inputSource );
  40245. }
  40246. this._currentDepthNear = null;
  40247. this._currentDepthFar = null;
  40248. // restore framebuffer/rendering state
  40249. renderer._resetXRState();
  40250. this._session = null;
  40251. this._xrRenderTarget = null;
  40252. this._glBinding = null;
  40253. this._glBaseLayer = null;
  40254. this._glProjLayer = null;
  40255. // switch layers back to emulated
  40256. if ( this._sessionUsesLayers === true ) {
  40257. for ( const layer of this._layers ) {
  40258. // Recreate layer render target to reset state
  40259. layer.renderTarget = new XRRenderTarget(
  40260. layer.pixelwidth,
  40261. layer.pixelheight,
  40262. {
  40263. format: RGBAFormat,
  40264. type: UnsignedByteType,
  40265. depthTexture: new DepthTexture(
  40266. layer.pixelwidth,
  40267. layer.pixelheight,
  40268. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  40269. undefined,
  40270. undefined,
  40271. undefined,
  40272. undefined,
  40273. undefined,
  40274. undefined,
  40275. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  40276. ),
  40277. stencilBuffer: layer.stencilBuffer,
  40278. resolveDepthBuffer: false,
  40279. resolveStencilBuffer: false
  40280. } );
  40281. layer.renderTarget.isXRRenderTarget = false;
  40282. layer.plane.material = layer.material;
  40283. layer.material.map = layer.renderTarget.texture;
  40284. layer.material.map.offset.y = 1;
  40285. layer.material.map.repeat.y = -1;
  40286. delete layer.xrlayer;
  40287. }
  40288. }
  40289. //
  40290. this.isPresenting = false;
  40291. this._useMultiview = false;
  40292. renderer._animation.stop();
  40293. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  40294. renderer._animation.setContext( this._currentAnimationContext );
  40295. renderer._animation.start();
  40296. renderer.setPixelRatio( this._currentPixelRatio );
  40297. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  40298. this.dispatchEvent( { type: 'sessionend' } );
  40299. }
  40300. function onInputSourcesChange( event ) {
  40301. const controllers = this._controllers;
  40302. const controllerInputSources = this._controllerInputSources;
  40303. // Notify disconnected
  40304. for ( let i = 0; i < event.removed.length; i ++ ) {
  40305. const inputSource = event.removed[ i ];
  40306. const index = controllerInputSources.indexOf( inputSource );
  40307. if ( index >= 0 ) {
  40308. controllerInputSources[ index ] = null;
  40309. controllers[ index ].disconnect( inputSource );
  40310. }
  40311. }
  40312. // Notify connected
  40313. for ( let i = 0; i < event.added.length; i ++ ) {
  40314. const inputSource = event.added[ i ];
  40315. let controllerIndex = controllerInputSources.indexOf( inputSource );
  40316. if ( controllerIndex === -1 ) {
  40317. // Assign input source a controller that currently has no input source
  40318. for ( let i = 0; i < controllers.length; i ++ ) {
  40319. if ( i >= controllerInputSources.length ) {
  40320. controllerInputSources.push( inputSource );
  40321. controllerIndex = i;
  40322. break;
  40323. } else if ( controllerInputSources[ i ] === null ) {
  40324. controllerInputSources[ i ] = inputSource;
  40325. controllerIndex = i;
  40326. break;
  40327. }
  40328. }
  40329. // If all controllers do currently receive input we ignore new ones
  40330. if ( controllerIndex === -1 ) break;
  40331. }
  40332. const controller = controllers[ controllerIndex ];
  40333. if ( controller ) {
  40334. controller.connect( inputSource );
  40335. }
  40336. }
  40337. }
  40338. // Creation method for native WebXR layers
  40339. function createXRLayer( layer ) {
  40340. if ( layer.type === 'quad' ) {
  40341. return this._glBinding.createQuadLayer( {
  40342. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40343. width: layer.width / 2,
  40344. height: layer.height / 2,
  40345. space: this._referenceSpace,
  40346. viewPixelWidth: layer.pixelwidth,
  40347. viewPixelHeight: layer.pixelheight,
  40348. clearOnAccess: false
  40349. } );
  40350. } else {
  40351. return this._glBinding.createCylinderLayer( {
  40352. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40353. radius: layer.radius,
  40354. centralAngle: layer.centralAngle,
  40355. aspectRatio: layer.aspectRatio,
  40356. space: this._referenceSpace,
  40357. viewPixelWidth: layer.pixelwidth,
  40358. viewPixelHeight: layer.pixelheight,
  40359. clearOnAccess: false
  40360. } );
  40361. }
  40362. }
  40363. // Animation Loop
  40364. function onAnimationFrame( time, frame ) {
  40365. if ( frame === undefined ) return;
  40366. const cameraXR = this._cameraXR;
  40367. const renderer = this._renderer;
  40368. const backend = renderer.backend;
  40369. const glBaseLayer = this._glBaseLayer;
  40370. const referenceSpace = this.getReferenceSpace();
  40371. const pose = frame.getViewerPose( referenceSpace );
  40372. this._xrFrame = frame;
  40373. if ( pose !== null ) {
  40374. const views = pose.views;
  40375. if ( this._glBaseLayer !== null ) {
  40376. backend.setXRTarget( glBaseLayer.framebuffer );
  40377. }
  40378. let cameraXRNeedsUpdate = false;
  40379. // check if it's necessary to rebuild cameraXR's camera list
  40380. if ( views.length !== cameraXR.cameras.length ) {
  40381. cameraXR.cameras.length = 0;
  40382. cameraXRNeedsUpdate = true;
  40383. }
  40384. for ( let i = 0; i < views.length; i ++ ) {
  40385. const view = views[ i ];
  40386. let viewport;
  40387. if ( this._supportsLayers === true ) {
  40388. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  40389. viewport = glSubImage.viewport;
  40390. // For side-by-side projection, we only produce a single texture for both eyes.
  40391. if ( i === 0 ) {
  40392. backend.setXRRenderTargetTextures(
  40393. this._xrRenderTarget,
  40394. glSubImage.colorTexture,
  40395. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  40396. );
  40397. }
  40398. } else {
  40399. viewport = glBaseLayer.getViewport( view );
  40400. }
  40401. let camera = this._cameras[ i ];
  40402. if ( camera === undefined ) {
  40403. camera = new PerspectiveCamera();
  40404. camera.layers.enable( i );
  40405. camera.viewport = new Vector4();
  40406. this._cameras[ i ] = camera;
  40407. }
  40408. camera.matrix.fromArray( view.transform.matrix );
  40409. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40410. camera.projectionMatrix.fromArray( view.projectionMatrix );
  40411. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40412. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  40413. if ( i === 0 ) {
  40414. cameraXR.matrix.copy( camera.matrix );
  40415. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  40416. }
  40417. if ( cameraXRNeedsUpdate === true ) {
  40418. cameraXR.cameras.push( camera );
  40419. }
  40420. }
  40421. renderer.setOutputRenderTarget( this._xrRenderTarget );
  40422. }
  40423. //
  40424. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40425. const inputSource = this._controllerInputSources[ i ];
  40426. const controller = this._controllers[ i ];
  40427. if ( inputSource !== null && controller !== undefined ) {
  40428. controller.update( inputSource, frame, referenceSpace );
  40429. }
  40430. }
  40431. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  40432. if ( frame.detectedPlanes ) {
  40433. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  40434. }
  40435. this._xrFrame = null;
  40436. }
  40437. /**
  40438. * CanvasTarget is a class that represents the final output destination of the renderer.
  40439. *
  40440. * @augments EventDispatcher
  40441. */
  40442. class CanvasTarget extends EventDispatcher {
  40443. /**
  40444. * Constructs a new CanvasTarget.
  40445. *
  40446. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  40447. */
  40448. constructor( domElement ) {
  40449. super();
  40450. /**
  40451. * A reference to the canvas element the renderer is drawing to.
  40452. * This value of this property will automatically be created by
  40453. * the renderer.
  40454. *
  40455. * @type {HTMLCanvasElement|OffscreenCanvas}
  40456. */
  40457. this.domElement = domElement;
  40458. /**
  40459. * The renderer's pixel ratio.
  40460. *
  40461. * @private
  40462. * @type {number}
  40463. * @default 1
  40464. */
  40465. this._pixelRatio = 1;
  40466. /**
  40467. * The width of the renderer's default framebuffer in logical pixel unit.
  40468. *
  40469. * @private
  40470. * @type {number}
  40471. */
  40472. this._width = this.domElement.width;
  40473. /**
  40474. * The height of the renderer's default framebuffer in logical pixel unit.
  40475. *
  40476. * @private
  40477. * @type {number}
  40478. */
  40479. this._height = this.domElement.height;
  40480. /**
  40481. * The viewport of the renderer in logical pixel unit.
  40482. *
  40483. * @private
  40484. * @type {Vector4}
  40485. */
  40486. this._viewport = new Vector4( 0, 0, this._width, this._height );
  40487. /**
  40488. * The scissor rectangle of the renderer in logical pixel unit.
  40489. *
  40490. * @private
  40491. * @type {Vector4}
  40492. */
  40493. this._scissor = new Vector4( 0, 0, this._width, this._height );
  40494. /**
  40495. * Whether the scissor test should be enabled or not.
  40496. *
  40497. * @private
  40498. * @type {boolean}
  40499. */
  40500. this._scissorTest = false;
  40501. /**
  40502. * The color texture of the default framebuffer.
  40503. *
  40504. * @type {FramebufferTexture}
  40505. */
  40506. this.colorTexture = new FramebufferTexture();
  40507. /**
  40508. * The depth texture of the default framebuffer.
  40509. *
  40510. * @type {DepthTexture}
  40511. */
  40512. this.depthTexture = new DepthTexture();
  40513. }
  40514. /**
  40515. * Returns the pixel ratio.
  40516. *
  40517. * @return {number} The pixel ratio.
  40518. */
  40519. getPixelRatio() {
  40520. return this._pixelRatio;
  40521. }
  40522. /**
  40523. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  40524. *
  40525. * @param {Vector2} target - The method writes the result in this target object.
  40526. * @return {Vector2} The drawing buffer size.
  40527. */
  40528. getDrawingBufferSize( target ) {
  40529. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  40530. }
  40531. /**
  40532. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  40533. *
  40534. * @param {Vector2} target - The method writes the result in this target object.
  40535. * @return {Vector2} The renderer's size in logical pixels.
  40536. */
  40537. getSize( target ) {
  40538. return target.set( this._width, this._height );
  40539. }
  40540. /**
  40541. * Sets the given pixel ratio and resizes the canvas if necessary.
  40542. *
  40543. * @param {number} [value=1] - The pixel ratio.
  40544. */
  40545. setPixelRatio( value = 1 ) {
  40546. if ( this._pixelRatio === value ) return;
  40547. this._pixelRatio = value;
  40548. this.setSize( this._width, this._height, false );
  40549. }
  40550. /**
  40551. * This method allows to define the drawing buffer size by specifying
  40552. * width, height and pixel ratio all at once. The size of the drawing
  40553. * buffer is computed with this formula:
  40554. * ```js
  40555. * size.x = width * pixelRatio;
  40556. * size.y = height * pixelRatio;
  40557. * ```
  40558. *
  40559. * @param {number} width - The width in logical pixels.
  40560. * @param {number} height - The height in logical pixels.
  40561. * @param {number} pixelRatio - The pixel ratio.
  40562. */
  40563. setDrawingBufferSize( width, height, pixelRatio ) {
  40564. // Renderer can't be resized while presenting in XR.
  40565. if ( this.xr && this.xr.isPresenting ) return;
  40566. this._width = width;
  40567. this._height = height;
  40568. this._pixelRatio = pixelRatio;
  40569. this.domElement.width = Math.floor( width * pixelRatio );
  40570. this.domElement.height = Math.floor( height * pixelRatio );
  40571. this.setViewport( 0, 0, width, height );
  40572. this._dispatchResize();
  40573. }
  40574. /**
  40575. * Sets the size of the renderer.
  40576. *
  40577. * @param {number} width - The width in logical pixels.
  40578. * @param {number} height - The height in logical pixels.
  40579. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  40580. */
  40581. setSize( width, height, updateStyle = true ) {
  40582. // Renderer can't be resized while presenting in XR.
  40583. if ( this.xr && this.xr.isPresenting ) return;
  40584. this._width = width;
  40585. this._height = height;
  40586. this.domElement.width = Math.floor( width * this._pixelRatio );
  40587. this.domElement.height = Math.floor( height * this._pixelRatio );
  40588. if ( updateStyle === true ) {
  40589. this.domElement.style.width = width + 'px';
  40590. this.domElement.style.height = height + 'px';
  40591. }
  40592. this.setViewport( 0, 0, width, height );
  40593. this._dispatchResize();
  40594. }
  40595. /**
  40596. * Returns the scissor rectangle.
  40597. *
  40598. * @param {Vector4} target - The method writes the result in this target object.
  40599. * @return {Vector4} The scissor rectangle.
  40600. */
  40601. getScissor( target ) {
  40602. const scissor = this._scissor;
  40603. target.x = scissor.x;
  40604. target.y = scissor.y;
  40605. target.width = scissor.width;
  40606. target.height = scissor.height;
  40607. return target;
  40608. }
  40609. /**
  40610. * Defines the scissor rectangle.
  40611. *
  40612. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  40613. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  40614. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  40615. * @param {number} width - The width of the scissor box in logical pixel unit.
  40616. * @param {number} height - The height of the scissor box in logical pixel unit.
  40617. */
  40618. setScissor( x, y, width, height ) {
  40619. const scissor = this._scissor;
  40620. if ( x.isVector4 ) {
  40621. scissor.copy( x );
  40622. } else {
  40623. scissor.set( x, y, width, height );
  40624. }
  40625. }
  40626. /**
  40627. * Returns the scissor test value.
  40628. *
  40629. * @return {boolean} Whether the scissor test should be enabled or not.
  40630. */
  40631. getScissorTest() {
  40632. return this._scissorTest;
  40633. }
  40634. /**
  40635. * Defines the scissor test.
  40636. *
  40637. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40638. */
  40639. setScissorTest( boolean ) {
  40640. this._scissorTest = boolean;
  40641. }
  40642. /**
  40643. * Returns the viewport definition.
  40644. *
  40645. * @param {Vector4} target - The method writes the result in this target object.
  40646. * @return {Vector4} The viewport definition.
  40647. */
  40648. getViewport( target ) {
  40649. return target.copy( this._viewport );
  40650. }
  40651. /**
  40652. * Defines the viewport.
  40653. *
  40654. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40655. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40656. * @param {number} width - The width of the viewport in logical pixel unit.
  40657. * @param {number} height - The height of the viewport in logical pixel unit.
  40658. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  40659. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  40660. */
  40661. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  40662. const viewport = this._viewport;
  40663. if ( x.isVector4 ) {
  40664. viewport.copy( x );
  40665. } else {
  40666. viewport.set( x, y, width, height );
  40667. }
  40668. viewport.minDepth = minDepth;
  40669. viewport.maxDepth = maxDepth;
  40670. }
  40671. /**
  40672. * Dispatches the resize event.
  40673. *
  40674. * @private
  40675. */
  40676. _dispatchResize() {
  40677. this.dispatchEvent( { type: 'resize' } );
  40678. }
  40679. /**
  40680. * Frees the GPU-related resources allocated by this instance. Call this
  40681. * method whenever this instance is no longer used in your app.
  40682. *
  40683. * @fires RenderTarget#dispose
  40684. */
  40685. dispose() {
  40686. this.dispatchEvent( { type: 'dispose' } );
  40687. }
  40688. }
  40689. const _scene = /*@__PURE__*/ new Scene();
  40690. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  40691. const _screen = /*@__PURE__*/ new Vector4();
  40692. const _frustum = /*@__PURE__*/ new Frustum();
  40693. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  40694. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  40695. const _vector4 = /*@__PURE__*/ new Vector4();
  40696. const _shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  40697. /**
  40698. * Base class for renderers.
  40699. */
  40700. class Renderer {
  40701. /**
  40702. * Renderer options.
  40703. *
  40704. * @typedef {Object} Renderer~Options
  40705. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  40706. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  40707. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  40708. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  40709. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  40710. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  40711. * @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
  40712. * to overwrite the default.
  40713. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  40714. * @property {number} [outputBufferType=HalfFloatType] - Defines the type of output buffers. The default `HalfFloatType` is recommend for best
  40715. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  40716. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  40717. */
  40718. /**
  40719. * Constructs a new renderer.
  40720. *
  40721. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  40722. * @param {Renderer~Options} [parameters] - The configuration parameter.
  40723. */
  40724. constructor( backend, parameters = {} ) {
  40725. /**
  40726. * This flag can be used for type testing.
  40727. *
  40728. * @type {boolean}
  40729. * @readonly
  40730. * @default true
  40731. */
  40732. this.isRenderer = true;
  40733. //
  40734. const {
  40735. logarithmicDepthBuffer = false,
  40736. reversedDepthBuffer = false,
  40737. alpha = true,
  40738. depth = true,
  40739. stencil = false,
  40740. antialias = false,
  40741. samples = 0,
  40742. getFallback = null,
  40743. outputBufferType = HalfFloatType,
  40744. multiview = false
  40745. } = parameters;
  40746. /**
  40747. * A reference to the current backend.
  40748. *
  40749. * @type {Backend}
  40750. */
  40751. this.backend = backend;
  40752. /**
  40753. * Whether the renderer should automatically clear the current rendering target
  40754. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  40755. * or the current bound render target (custom framebuffer).
  40756. *
  40757. * @type {boolean}
  40758. * @default true
  40759. */
  40760. this.autoClear = true;
  40761. /**
  40762. * When `autoClear` is set to `true`, this property defines whether the renderer
  40763. * should clear the color buffer.
  40764. *
  40765. * @type {boolean}
  40766. * @default true
  40767. */
  40768. this.autoClearColor = true;
  40769. /**
  40770. * When `autoClear` is set to `true`, this property defines whether the renderer
  40771. * should clear the depth buffer.
  40772. *
  40773. * @type {boolean}
  40774. * @default true
  40775. */
  40776. this.autoClearDepth = true;
  40777. /**
  40778. * When `autoClear` is set to `true`, this property defines whether the renderer
  40779. * should clear the stencil buffer.
  40780. *
  40781. * @type {boolean}
  40782. * @default true
  40783. */
  40784. this.autoClearStencil = true;
  40785. /**
  40786. * Whether the default framebuffer should be transparent or opaque.
  40787. *
  40788. * @type {boolean}
  40789. * @default true
  40790. */
  40791. this.alpha = alpha;
  40792. /**
  40793. * Whether logarithmic depth buffer is enabled or not.
  40794. *
  40795. * @type {boolean}
  40796. * @default false
  40797. * @readonly
  40798. */
  40799. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  40800. /**
  40801. * Whether reversed depth buffer is enabled or not.
  40802. *
  40803. * @type {boolean}
  40804. * @default false
  40805. * @readonly
  40806. */
  40807. this.reversedDepthBuffer = reversedDepthBuffer;
  40808. /**
  40809. * Defines the output color space of the renderer.
  40810. *
  40811. * @type {string}
  40812. * @default SRGBColorSpace
  40813. */
  40814. this.outputColorSpace = SRGBColorSpace;
  40815. /**
  40816. * Defines the tone mapping of the renderer.
  40817. *
  40818. * @type {number}
  40819. * @default NoToneMapping
  40820. */
  40821. this.toneMapping = NoToneMapping;
  40822. /**
  40823. * Defines the tone mapping exposure.
  40824. *
  40825. * @type {number}
  40826. * @default 1
  40827. */
  40828. this.toneMappingExposure = 1.0;
  40829. /**
  40830. * Whether the renderer should sort its render lists or not.
  40831. *
  40832. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  40833. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  40834. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  40835. * e.g. manually determining each object's rendering order.
  40836. *
  40837. * @type {boolean}
  40838. * @default true
  40839. */
  40840. this.sortObjects = true;
  40841. /**
  40842. * Whether the default framebuffer should have a depth buffer or not.
  40843. *
  40844. * @type {boolean}
  40845. * @default true
  40846. */
  40847. this.depth = depth;
  40848. /**
  40849. * Whether the default framebuffer should have a stencil buffer or not.
  40850. *
  40851. * @type {boolean}
  40852. * @default false
  40853. */
  40854. this.stencil = stencil;
  40855. /**
  40856. * Holds a series of statistical information about the GPU memory
  40857. * and the rendering process. Useful for debugging and monitoring.
  40858. *
  40859. * @type {Info}
  40860. */
  40861. this.info = new Info();
  40862. /**
  40863. * A global context node that stores override nodes for specific transformations or calculations.
  40864. * These nodes can be used to replace default behavior in the rendering pipeline.
  40865. *
  40866. * @type {ContextNode}
  40867. * @property {Object} value - The context value object.
  40868. */
  40869. this.contextNode = context();
  40870. /**
  40871. * The node library defines how certain library objects like materials, lights
  40872. * or tone mapping functions are mapped to node types. This is required since
  40873. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  40874. * be part of the scene graph, they are internally represented as nodes for
  40875. * further processing.
  40876. *
  40877. * @type {NodeLibrary}
  40878. */
  40879. this.library = new NodeLibrary();
  40880. /**
  40881. * A map-like data structure for managing lights.
  40882. *
  40883. * @type {Lighting}
  40884. */
  40885. this.lighting = new Lighting();
  40886. // internals
  40887. /**
  40888. * The number of MSAA samples.
  40889. *
  40890. * @private
  40891. * @type {number}
  40892. * @default 0
  40893. */
  40894. this._samples = samples || ( antialias === true ) ? 4 : 0;
  40895. /**
  40896. * OnCanvasTargetResize callback function.
  40897. *
  40898. * @private
  40899. * @type {Function}
  40900. */
  40901. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  40902. /**
  40903. * The canvas target for rendering.
  40904. *
  40905. * @private
  40906. * @type {CanvasTarget}
  40907. */
  40908. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  40909. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  40910. this._canvasTarget.isDefaultCanvasTarget = true;
  40911. /**
  40912. * The inspector provides information about the internal renderer state.
  40913. *
  40914. * @private
  40915. * @type {InspectorBase}
  40916. */
  40917. this._inspector = new InspectorBase();
  40918. this._inspector.setRenderer( this );
  40919. /**
  40920. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  40921. *
  40922. * @private
  40923. * @type {?Function}
  40924. */
  40925. this._getFallback = getFallback;
  40926. /**
  40927. * A reference to a renderer module for managing shader attributes.
  40928. *
  40929. * @private
  40930. * @type {?Attributes}
  40931. * @default null
  40932. */
  40933. this._attributes = null;
  40934. /**
  40935. * A reference to a renderer module for managing geometries.
  40936. *
  40937. * @private
  40938. * @type {?Geometries}
  40939. * @default null
  40940. */
  40941. this._geometries = null;
  40942. /**
  40943. * A reference to a renderer module for managing node related logic.
  40944. *
  40945. * @private
  40946. * @type {?NodeManager}
  40947. * @default null
  40948. */
  40949. this._nodes = null;
  40950. /**
  40951. * A reference to a renderer module for managing the internal animation loop.
  40952. *
  40953. * @private
  40954. * @type {?Animation}
  40955. * @default null
  40956. */
  40957. this._animation = null;
  40958. /**
  40959. * A reference to a renderer module for managing shader program bindings.
  40960. *
  40961. * @private
  40962. * @type {?Bindings}
  40963. * @default null
  40964. */
  40965. this._bindings = null;
  40966. /**
  40967. * A reference to a renderer module for managing render objects.
  40968. *
  40969. * @private
  40970. * @type {?RenderObjects}
  40971. * @default null
  40972. */
  40973. this._objects = null;
  40974. /**
  40975. * A reference to a renderer module for managing render and compute pipelines.
  40976. *
  40977. * @private
  40978. * @type {?Pipelines}
  40979. * @default null
  40980. */
  40981. this._pipelines = null;
  40982. /**
  40983. * A reference to a renderer module for managing render bundles.
  40984. *
  40985. * @private
  40986. * @type {?RenderBundles}
  40987. * @default null
  40988. */
  40989. this._bundles = null;
  40990. /**
  40991. * A reference to a renderer module for managing render lists.
  40992. *
  40993. * @private
  40994. * @type {?RenderLists}
  40995. * @default null
  40996. */
  40997. this._renderLists = null;
  40998. /**
  40999. * A reference to a renderer module for managing render contexts.
  41000. *
  41001. * @private
  41002. * @type {?RenderContexts}
  41003. * @default null
  41004. */
  41005. this._renderContexts = null;
  41006. /**
  41007. * A reference to a renderer module for managing textures.
  41008. *
  41009. * @private
  41010. * @type {?Textures}
  41011. * @default null
  41012. */
  41013. this._textures = null;
  41014. /**
  41015. * A reference to a renderer module for backgrounds.
  41016. *
  41017. * @private
  41018. * @type {?Background}
  41019. * @default null
  41020. */
  41021. this._background = null;
  41022. /**
  41023. * This fullscreen quad is used for internal render passes
  41024. * like the tone mapping and color space output pass.
  41025. *
  41026. * @private
  41027. * @type {QuadMesh}
  41028. */
  41029. this._quad = new QuadMesh( new NodeMaterial() );
  41030. this._quad.name = 'Output Color Transform';
  41031. this._quad.material.name = 'outputColorTransform';
  41032. /**
  41033. * A reference to the current render context.
  41034. *
  41035. * @private
  41036. * @type {?RenderContext}
  41037. * @default null
  41038. */
  41039. this._currentRenderContext = null;
  41040. /**
  41041. * A custom sort function for the opaque render list.
  41042. *
  41043. * @private
  41044. * @type {?Function}
  41045. * @default null
  41046. */
  41047. this._opaqueSort = null;
  41048. /**
  41049. * A custom sort function for the transparent render list.
  41050. *
  41051. * @private
  41052. * @type {?Function}
  41053. * @default null
  41054. */
  41055. this._transparentSort = null;
  41056. /**
  41057. * The framebuffer target.
  41058. *
  41059. * @private
  41060. * @type {?RenderTarget}
  41061. * @default null
  41062. */
  41063. this._frameBufferTarget = null;
  41064. const alphaClear = this.alpha === true ? 0 : 1;
  41065. /**
  41066. * The clear color value.
  41067. *
  41068. * @private
  41069. * @type {Color4}
  41070. */
  41071. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  41072. /**
  41073. * The clear depth value.
  41074. *
  41075. * @private
  41076. * @type {number}
  41077. * @default 1
  41078. */
  41079. this._clearDepth = 1;
  41080. /**
  41081. * The clear stencil value.
  41082. *
  41083. * @private
  41084. * @type {number}
  41085. * @default 0
  41086. */
  41087. this._clearStencil = 0;
  41088. /**
  41089. * The current render target.
  41090. *
  41091. * @private
  41092. * @type {?RenderTarget}
  41093. * @default null
  41094. */
  41095. this._renderTarget = null;
  41096. /**
  41097. * The active cube face.
  41098. *
  41099. * @private
  41100. * @type {number}
  41101. * @default 0
  41102. */
  41103. this._activeCubeFace = 0;
  41104. /**
  41105. * The active mipmap level.
  41106. *
  41107. * @private
  41108. * @type {number}
  41109. * @default 0
  41110. */
  41111. this._activeMipmapLevel = 0;
  41112. /**
  41113. * The current output render target.
  41114. *
  41115. * @private
  41116. * @type {?RenderTarget}
  41117. * @default null
  41118. */
  41119. this._outputRenderTarget = null;
  41120. /**
  41121. * The MRT setting.
  41122. *
  41123. * @private
  41124. * @type {?MRTNode}
  41125. * @default null
  41126. */
  41127. this._mrt = null;
  41128. /**
  41129. * This function defines how a render object is going
  41130. * to be rendered.
  41131. *
  41132. * @private
  41133. * @type {?Function}
  41134. * @default null
  41135. */
  41136. this._renderObjectFunction = null;
  41137. /**
  41138. * Used to keep track of the current render object function.
  41139. *
  41140. * @private
  41141. * @type {?Function}
  41142. * @default null
  41143. */
  41144. this._currentRenderObjectFunction = null;
  41145. /**
  41146. * Used to keep track of the current render bundle.
  41147. *
  41148. * @private
  41149. * @type {?RenderBundle}
  41150. * @default null
  41151. */
  41152. this._currentRenderBundle = null;
  41153. /**
  41154. * Next to `_renderObjectFunction()`, this function provides another hook
  41155. * for influencing the render process of a render object. It is meant for internal
  41156. * use and only relevant for `compileAsync()` right now. Instead of using
  41157. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  41158. * a different function might be used which performs no draw but just the node
  41159. * and pipeline updates.
  41160. *
  41161. * @private
  41162. * @type {Function}
  41163. */
  41164. this._handleObjectFunction = this._renderObjectDirect;
  41165. /**
  41166. * Indicates whether the device has been lost or not. In WebGL terms, the device
  41167. * lost is considered as a context lost. When this is set to `true`, rendering
  41168. * isn't possible anymore.
  41169. *
  41170. * @private
  41171. * @type {boolean}
  41172. * @default false
  41173. */
  41174. this._isDeviceLost = false;
  41175. /**
  41176. * A callback function that defines what should happen when a device/context lost occurs.
  41177. *
  41178. * @type {Function}
  41179. */
  41180. this.onDeviceLost = this._onDeviceLost;
  41181. /**
  41182. * Defines the type of output buffers. The default `HalfFloatType` is recommend for
  41183. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  41184. * This will reduce rendering quality though.
  41185. *
  41186. * @private
  41187. * @type {number}
  41188. * @default HalfFloatType
  41189. */
  41190. this._outputBufferType = outputBufferType;
  41191. /**
  41192. * A cache for shadow nodes per material
  41193. *
  41194. * @private
  41195. * @type {WeakMap<Material, Object>}
  41196. */
  41197. this._cacheShadowNodes = new WeakMap();
  41198. /**
  41199. * Whether the renderer has been initialized or not.
  41200. *
  41201. * @private
  41202. * @type {boolean}
  41203. * @default false
  41204. */
  41205. this._initialized = false;
  41206. /**
  41207. * The call depth of the renderer. Counts the number of
  41208. * nested render calls.
  41209. *
  41210. * @private
  41211. * @type {number}
  41212. * @default - 1
  41213. */
  41214. this._callDepth = -1;
  41215. /**
  41216. * A reference to the promise which initializes the renderer.
  41217. *
  41218. * @private
  41219. * @type {?Promise<this>}
  41220. * @default null
  41221. */
  41222. this._initPromise = null;
  41223. /**
  41224. * An array of compilation promises which are used in `compileAsync()`.
  41225. *
  41226. * @private
  41227. * @type {?Array<Promise>}
  41228. * @default null
  41229. */
  41230. this._compilationPromises = null;
  41231. /**
  41232. * Whether the renderer should render transparent render objects or not.
  41233. *
  41234. * @type {boolean}
  41235. * @default true
  41236. */
  41237. this.transparent = true;
  41238. /**
  41239. * Whether the renderer should render opaque render objects or not.
  41240. *
  41241. * @type {boolean}
  41242. * @default true
  41243. */
  41244. this.opaque = true;
  41245. /**
  41246. * Shadow map configuration
  41247. * @typedef {Object} ShadowMapConfig
  41248. * @property {boolean} enabled - Whether to globally enable shadows or not.
  41249. * @property {boolean} transmitted - Whether to enable light transmission through non-opaque materials.
  41250. * @property {number} type - The shadow map type.
  41251. */
  41252. /**
  41253. * The renderer's shadow configuration.
  41254. *
  41255. * @type {ShadowMapConfig}
  41256. */
  41257. this.shadowMap = {
  41258. enabled: false,
  41259. transmitted: false,
  41260. type: PCFShadowMap
  41261. };
  41262. /**
  41263. * XR configuration.
  41264. * @typedef {Object} XRConfig
  41265. * @property {boolean} enabled - Whether to globally enable XR or not.
  41266. */
  41267. /**
  41268. * The renderer's XR manager.
  41269. *
  41270. * @type {XRManager}
  41271. */
  41272. this.xr = new XRManager( this, multiview );
  41273. /**
  41274. * Debug configuration.
  41275. * @typedef {Object} DebugConfig
  41276. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  41277. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  41278. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  41279. */
  41280. /**
  41281. * The renderer's debug configuration.
  41282. *
  41283. * @type {DebugConfig}
  41284. */
  41285. this.debug = {
  41286. checkShaderErrors: true,
  41287. onShaderError: null,
  41288. getShaderAsync: async ( scene, camera, object ) => {
  41289. await this.compileAsync( scene, camera );
  41290. const renderList = this._renderLists.get( scene, camera );
  41291. const renderContext = this._renderContexts.get( this._renderTarget, this._mrt );
  41292. const material = scene.overrideMaterial || object.material;
  41293. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  41294. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  41295. return { fragmentShader, vertexShader };
  41296. }
  41297. };
  41298. }
  41299. /**
  41300. * Initializes the renderer so it is ready for usage.
  41301. *
  41302. * @async
  41303. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  41304. */
  41305. async init() {
  41306. if ( this._initPromise !== null ) {
  41307. return this._initPromise;
  41308. }
  41309. this._initPromise = new Promise( async ( resolve, reject ) => {
  41310. let backend = this.backend;
  41311. try {
  41312. await backend.init( this );
  41313. } catch ( error ) {
  41314. if ( this._getFallback !== null ) {
  41315. // try the fallback
  41316. try {
  41317. this.backend = backend = this._getFallback( error );
  41318. await backend.init( this );
  41319. } catch ( error ) {
  41320. reject( error );
  41321. return;
  41322. }
  41323. } else {
  41324. reject( error );
  41325. return;
  41326. }
  41327. }
  41328. this._nodes = new NodeManager( this, backend );
  41329. this._animation = new Animation( this, this._nodes, this.info );
  41330. this._attributes = new Attributes( backend );
  41331. this._background = new Background( this, this._nodes );
  41332. this._geometries = new Geometries( this._attributes, this.info );
  41333. this._textures = new Textures( this, backend, this.info );
  41334. this._pipelines = new Pipelines( backend, this._nodes );
  41335. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  41336. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  41337. this._renderLists = new RenderLists( this.lighting );
  41338. this._bundles = new RenderBundles();
  41339. this._renderContexts = new RenderContexts( this );
  41340. //
  41341. this._animation.start();
  41342. this._initialized = true;
  41343. //
  41344. this._inspector.init();
  41345. //
  41346. resolve( this );
  41347. } );
  41348. return this._initPromise;
  41349. }
  41350. /**
  41351. * A reference to the canvas element the renderer is drawing to.
  41352. * This value of this property will automatically be created by
  41353. * the renderer.
  41354. *
  41355. * @type {HTMLCanvasElement|OffscreenCanvas}
  41356. */
  41357. get domElement() {
  41358. return this._canvasTarget.domElement;
  41359. }
  41360. /**
  41361. * The coordinate system of the renderer. The value of this property
  41362. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  41363. * `THREE.WebGPUCoordinateSystem`.
  41364. *
  41365. * @readonly
  41366. * @type {number}
  41367. */
  41368. get coordinateSystem() {
  41369. return this.backend.coordinateSystem;
  41370. }
  41371. /**
  41372. * Compiles all materials in the given scene. This can be useful to avoid a
  41373. * phenomenon which is called "shader compilation stutter", which occurs when
  41374. * rendering an object with a new shader for the first time.
  41375. *
  41376. * If you want to add a 3D object to an existing scene, use the third optional
  41377. * parameter for applying the target scene. Note that the (target) scene's lighting
  41378. * and environment must be configured before calling this method.
  41379. *
  41380. * @async
  41381. * @param {Object3D} scene - The scene or 3D object to precompile.
  41382. * @param {Camera} camera - The camera that is used to render the scene.
  41383. * @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.
  41384. * @return {Promise} A Promise that resolves when the compile has been finished.
  41385. */
  41386. async compileAsync( scene, camera, targetScene = null ) {
  41387. if ( this._isDeviceLost === true ) return;
  41388. if ( this._initialized === false ) await this.init();
  41389. // preserve render tree
  41390. const nodeFrame = this._nodes.nodeFrame;
  41391. const previousRenderId = nodeFrame.renderId;
  41392. const previousRenderContext = this._currentRenderContext;
  41393. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  41394. const previousHandleObjectFunction = this._handleObjectFunction;
  41395. const previousCompilationPromises = this._compilationPromises;
  41396. //
  41397. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  41398. if ( targetScene === null ) targetScene = scene;
  41399. const renderTarget = this._renderTarget;
  41400. const renderContext = this._renderContexts.get( renderTarget, this._mrt );
  41401. const activeMipmapLevel = this._activeMipmapLevel;
  41402. const compilationPromises = [];
  41403. this._currentRenderContext = renderContext;
  41404. this._currentRenderObjectFunction = this.renderObject;
  41405. this._handleObjectFunction = this._createObjectPipeline;
  41406. this._compilationPromises = compilationPromises;
  41407. nodeFrame.renderId ++;
  41408. //
  41409. nodeFrame.update();
  41410. //
  41411. renderContext.depth = this.depth;
  41412. renderContext.stencil = this.stencil;
  41413. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  41414. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  41415. //
  41416. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  41417. //
  41418. const renderList = this._renderLists.get( scene, camera );
  41419. renderList.begin();
  41420. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  41421. // include lights from target scene
  41422. if ( targetScene !== scene ) {
  41423. targetScene.traverseVisible( function ( object ) {
  41424. if ( object.isLight && object.layers.test( camera.layers ) ) {
  41425. renderList.pushLight( object );
  41426. }
  41427. } );
  41428. }
  41429. renderList.finish();
  41430. //
  41431. if ( renderTarget !== null ) {
  41432. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  41433. const renderTargetData = this._textures.get( renderTarget );
  41434. renderContext.textures = renderTargetData.textures;
  41435. renderContext.depthTexture = renderTargetData.depthTexture;
  41436. } else {
  41437. renderContext.textures = null;
  41438. renderContext.depthTexture = null;
  41439. }
  41440. //
  41441. if ( targetScene !== scene ) {
  41442. this._background.update( targetScene, renderList, renderContext );
  41443. } else {
  41444. this._background.update( sceneRef, renderList, renderContext );
  41445. }
  41446. // process render lists
  41447. const opaqueObjects = renderList.opaque;
  41448. const transparentObjects = renderList.transparent;
  41449. const transparentDoublePassObjects = renderList.transparentDoublePass;
  41450. const lightsNode = renderList.lightsNode;
  41451. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41452. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41453. // restore render tree
  41454. nodeFrame.renderId = previousRenderId;
  41455. this._currentRenderContext = previousRenderContext;
  41456. this._currentRenderObjectFunction = previousRenderObjectFunction;
  41457. this._handleObjectFunction = previousHandleObjectFunction;
  41458. this._compilationPromises = previousCompilationPromises;
  41459. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  41460. await Promise.all( compilationPromises );
  41461. }
  41462. /**
  41463. * Renders the scene in an async fashion.
  41464. *
  41465. * @async
  41466. * @deprecated
  41467. * @param {Object3D} scene - The scene or 3D object to render.
  41468. * @param {Camera} camera - The camera.
  41469. * @return {Promise} A Promise that resolves when the render has been finished.
  41470. */
  41471. async renderAsync( scene, camera ) {
  41472. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41473. await this.init();
  41474. this.render( scene, camera );
  41475. }
  41476. /**
  41477. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  41478. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  41479. *
  41480. * @async
  41481. * @deprecated
  41482. * @return {Promise} A Promise that resolves when synchronization has been finished.
  41483. */
  41484. async waitForGPU() {
  41485. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  41486. }
  41487. //
  41488. set inspector( value ) {
  41489. if ( this._inspector !== null ) {
  41490. this._inspector.setRenderer( null );
  41491. }
  41492. this._inspector = value;
  41493. this._inspector.setRenderer( this );
  41494. }
  41495. /**
  41496. * The inspector instance. The inspector can be any class that extends from `InspectorBase`.
  41497. *
  41498. * @type {InspectorBase}
  41499. */
  41500. get inspector() {
  41501. return this._inspector;
  41502. }
  41503. /**
  41504. * Enables or disables high precision for model-view and normal-view matrices.
  41505. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  41506. *
  41507. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  41508. *
  41509. * @param {boolean} value - Whether to enable or disable high precision.
  41510. * @type {boolean}
  41511. */
  41512. set highPrecision( value ) {
  41513. const contextNodeData = this.contextNode.value;
  41514. if ( value === true ) {
  41515. contextNodeData.modelViewMatrix = highpModelViewMatrix;
  41516. contextNodeData.modelNormalViewMatrix = highpModelNormalViewMatrix;
  41517. } else if ( this.highPrecision ) {
  41518. delete contextNodeData.modelViewMatrix;
  41519. delete contextNodeData.modelNormalViewMatrix;
  41520. }
  41521. }
  41522. /**
  41523. * Returns whether high precision is enabled or not.
  41524. *
  41525. * @return {boolean} Whether high precision is enabled or not.
  41526. * @type {boolean}
  41527. */
  41528. get highPrecision() {
  41529. const contextNodeData = this.contextNode.value;
  41530. return contextNodeData.modelViewMatrix === highpModelViewMatrix && contextNodeData.modelNormalViewMatrix === highpModelNormalViewMatrix;
  41531. }
  41532. /**
  41533. * Sets the given MRT configuration.
  41534. *
  41535. * @param {MRTNode} mrt - The MRT node to set.
  41536. * @return {Renderer} A reference to this renderer.
  41537. */
  41538. setMRT( mrt ) {
  41539. this._mrt = mrt;
  41540. return this;
  41541. }
  41542. /**
  41543. * Returns the MRT configuration.
  41544. *
  41545. * @return {MRTNode} The MRT configuration.
  41546. */
  41547. getMRT() {
  41548. return this._mrt;
  41549. }
  41550. /**
  41551. * Returns the output buffer type.
  41552. *
  41553. * @return {number} The output buffer type.
  41554. */
  41555. getOutputBufferType() {
  41556. return this._outputBufferType;
  41557. }
  41558. /**
  41559. * Returns the output buffer type.
  41560. *
  41561. * @deprecated since r182. Use `.getOutputBufferType()` instead.
  41562. * @return {number} The output buffer type.
  41563. */
  41564. getColorBufferType() { // @deprecated, r182
  41565. warnOnce( 'Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".' );
  41566. return this.getOutputBufferType();
  41567. }
  41568. /**
  41569. * Default implementation of the device lost callback.
  41570. *
  41571. * @private
  41572. * @param {Object} info - Information about the context lost.
  41573. */
  41574. _onDeviceLost( info ) {
  41575. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  41576. if ( info.reason ) {
  41577. errorMessage += `\nReason: ${info.reason}`;
  41578. }
  41579. error( errorMessage );
  41580. this._isDeviceLost = true;
  41581. }
  41582. /**
  41583. * Renders the given render bundle.
  41584. *
  41585. * @private
  41586. * @param {Object} bundle - Render bundle data.
  41587. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  41588. * @param {LightsNode} lightsNode - The lights node.
  41589. */
  41590. _renderBundle( bundle, sceneRef, lightsNode ) {
  41591. const { bundleGroup, camera, renderList } = bundle;
  41592. const renderContext = this._currentRenderContext;
  41593. //
  41594. const renderBundle = this._bundles.get( bundleGroup, camera );
  41595. const renderBundleData = this.backend.get( renderBundle );
  41596. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  41597. //
  41598. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  41599. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  41600. renderBundleData.renderContexts.add( renderContext );
  41601. if ( renderBundleNeedsUpdate ) {
  41602. this.backend.beginBundle( renderContext );
  41603. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  41604. renderBundleData.renderObjects = [];
  41605. }
  41606. this._currentRenderBundle = renderBundle;
  41607. const {
  41608. transparentDoublePass: transparentDoublePassObjects,
  41609. transparent: transparentObjects,
  41610. opaque: opaqueObjects
  41611. } = renderList;
  41612. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41613. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41614. this._currentRenderBundle = null;
  41615. //
  41616. this.backend.finishBundle( renderContext, renderBundle );
  41617. renderBundleData.version = bundleGroup.version;
  41618. } else {
  41619. const { renderObjects } = renderBundleData;
  41620. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  41621. const renderObject = renderObjects[ i ];
  41622. if ( this._nodes.needsRefresh( renderObject ) ) {
  41623. this._nodes.updateBefore( renderObject );
  41624. this._nodes.updateForRender( renderObject );
  41625. this._bindings.updateForRender( renderObject );
  41626. this._nodes.updateAfter( renderObject );
  41627. }
  41628. }
  41629. }
  41630. this.backend.addBundle( renderContext, renderBundle );
  41631. }
  41632. /**
  41633. * Renders the scene or 3D object with the given camera. This method can only be called
  41634. * if the renderer has been initialized. When using `render()` inside an animation loop,
  41635. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  41636. * with {@link Renderer#setAnimationLoop} though.
  41637. *
  41638. * For all other use cases (like when using on-demand rendering), you must call
  41639. * {@link Renderer#init} before rendering.
  41640. *
  41641. * The target of the method is the default framebuffer (meaning the canvas)
  41642. * or alternatively a render target when specified via `setRenderTarget()`.
  41643. *
  41644. * @param {Object3D} scene - The scene or 3D object to render.
  41645. * @param {Camera} camera - The camera to render the scene with.
  41646. */
  41647. render( scene, camera ) {
  41648. if ( this._initialized === false ) {
  41649. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  41650. }
  41651. this._renderScene( scene, camera );
  41652. }
  41653. /**
  41654. * Returns whether the renderer has been initialized or not.
  41655. *
  41656. * @readonly
  41657. * @return {boolean} Whether the renderer has been initialized or not.
  41658. */
  41659. get initialized() {
  41660. return this._initialized;
  41661. }
  41662. /**
  41663. * Returns an internal render target which is used when computing the output tone mapping
  41664. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  41665. * pass and not inline to achieve more correct results.
  41666. *
  41667. * @private
  41668. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  41669. */
  41670. _getFrameBufferTarget() {
  41671. const { currentToneMapping, currentColorSpace } = this;
  41672. const useToneMapping = currentToneMapping !== NoToneMapping;
  41673. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  41674. if ( useToneMapping === false && useColorSpace === false ) return null;
  41675. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  41676. const { depth, stencil } = this;
  41677. let frameBufferTarget = this._frameBufferTarget;
  41678. if ( frameBufferTarget === null ) {
  41679. frameBufferTarget = new RenderTarget( width, height, {
  41680. depthBuffer: depth,
  41681. stencilBuffer: stencil,
  41682. type: this._outputBufferType,
  41683. format: RGBAFormat,
  41684. colorSpace: ColorManagement.workingColorSpace,
  41685. generateMipmaps: false,
  41686. minFilter: LinearFilter,
  41687. magFilter: LinearFilter,
  41688. samples: this.samples
  41689. } );
  41690. frameBufferTarget.isPostProcessingRenderTarget = true;
  41691. this._frameBufferTarget = frameBufferTarget;
  41692. }
  41693. const outputRenderTarget = this.getOutputRenderTarget();
  41694. frameBufferTarget.depthBuffer = depth;
  41695. frameBufferTarget.stencilBuffer = stencil;
  41696. if ( outputRenderTarget !== null ) {
  41697. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  41698. } else {
  41699. frameBufferTarget.setSize( width, height, 1 );
  41700. }
  41701. const canvasTarget = this._canvasTarget;
  41702. frameBufferTarget.viewport.copy( canvasTarget._viewport );
  41703. frameBufferTarget.scissor.copy( canvasTarget._scissor );
  41704. frameBufferTarget.viewport.multiplyScalar( canvasTarget._pixelRatio );
  41705. frameBufferTarget.scissor.multiplyScalar( canvasTarget._pixelRatio );
  41706. frameBufferTarget.scissorTest = canvasTarget._scissorTest;
  41707. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  41708. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  41709. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  41710. return frameBufferTarget;
  41711. }
  41712. /**
  41713. * Renders the scene or 3D object with the given camera.
  41714. *
  41715. * @private
  41716. * @param {Object3D} scene - The scene or 3D object to render.
  41717. * @param {Camera} camera - The camera to render the scene with.
  41718. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  41719. * @return {RenderContext} The current render context.
  41720. */
  41721. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  41722. if ( this._isDeviceLost === true ) return;
  41723. //
  41724. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  41725. // preserve render tree
  41726. const nodeFrame = this._nodes.nodeFrame;
  41727. const previousRenderId = nodeFrame.renderId;
  41728. const previousRenderContext = this._currentRenderContext;
  41729. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  41730. const previousHandleObjectFunction = this._handleObjectFunction;
  41731. //
  41732. this._callDepth ++;
  41733. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  41734. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  41735. const activeCubeFace = this._activeCubeFace;
  41736. const activeMipmapLevel = this._activeMipmapLevel;
  41737. //
  41738. let renderTarget;
  41739. if ( frameBufferTarget !== null ) {
  41740. renderTarget = frameBufferTarget;
  41741. this.setRenderTarget( renderTarget );
  41742. } else {
  41743. renderTarget = outputRenderTarget;
  41744. }
  41745. //
  41746. const renderContext = this._renderContexts.get( renderTarget, this._mrt, this._callDepth );
  41747. this._currentRenderContext = renderContext;
  41748. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  41749. this._handleObjectFunction = this._renderObjectDirect;
  41750. //
  41751. this.info.calls ++;
  41752. this.info.render.calls ++;
  41753. this.info.render.frameCalls ++;
  41754. nodeFrame.renderId = this.info.calls;
  41755. //
  41756. this.backend.updateTimeStampUID( renderContext );
  41757. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  41758. //
  41759. const xr = this.xr;
  41760. if ( xr.isPresenting === false ) {
  41761. let projectionMatrixNeedsUpdate = false;
  41762. // reversed depth
  41763. if ( this.reversedDepthBuffer === true && camera.reversedDepth !== true ) {
  41764. camera._reversedDepth = true;
  41765. if ( camera.isArrayCamera ) {
  41766. for ( const subCamera of camera.cameras ) {
  41767. subCamera._reversedDepth = true;
  41768. }
  41769. }
  41770. projectionMatrixNeedsUpdate = true;
  41771. }
  41772. // WebGPU/WebGL coordinate system
  41773. const coordinateSystem = this.coordinateSystem;
  41774. if ( camera.coordinateSystem !== coordinateSystem ) {
  41775. camera.coordinateSystem = coordinateSystem;
  41776. if ( camera.isArrayCamera ) {
  41777. for ( const subCamera of camera.cameras ) {
  41778. subCamera.coordinateSystem = coordinateSystem;
  41779. }
  41780. }
  41781. projectionMatrixNeedsUpdate = true;
  41782. }
  41783. // camera update
  41784. if ( projectionMatrixNeedsUpdate === true ) {
  41785. camera.updateProjectionMatrix();
  41786. if ( camera.isArrayCamera ) {
  41787. for ( const subCamera of camera.cameras ) {
  41788. subCamera.updateProjectionMatrix();
  41789. }
  41790. }
  41791. }
  41792. }
  41793. //
  41794. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  41795. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  41796. if ( xr.enabled === true && xr.isPresenting === true ) {
  41797. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  41798. camera = xr.getCamera(); // use XR camera for rendering
  41799. }
  41800. //
  41801. const canvasTarget = this._canvasTarget;
  41802. let viewport = canvasTarget._viewport;
  41803. let scissor = canvasTarget._scissor;
  41804. let pixelRatio = canvasTarget._pixelRatio;
  41805. if ( renderTarget !== null ) {
  41806. viewport = renderTarget.viewport;
  41807. scissor = renderTarget.scissor;
  41808. pixelRatio = 1;
  41809. }
  41810. this.getDrawingBufferSize( _drawingBufferSize );
  41811. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  41812. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  41813. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  41814. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  41815. renderContext.viewportValue.width >>= activeMipmapLevel;
  41816. renderContext.viewportValue.height >>= activeMipmapLevel;
  41817. renderContext.viewportValue.minDepth = minDepth;
  41818. renderContext.viewportValue.maxDepth = maxDepth;
  41819. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  41820. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  41821. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  41822. renderContext.scissorValue.width >>= activeMipmapLevel;
  41823. renderContext.scissorValue.height >>= activeMipmapLevel;
  41824. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  41825. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  41826. //
  41827. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  41828. //
  41829. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41830. if ( ! camera.isArrayCamera ) {
  41831. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  41832. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  41833. }
  41834. const renderList = this._renderLists.get( scene, camera );
  41835. renderList.begin();
  41836. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  41837. renderList.finish();
  41838. if ( this.sortObjects === true ) {
  41839. renderList.sort( this._opaqueSort, this._transparentSort );
  41840. }
  41841. //
  41842. if ( renderTarget !== null ) {
  41843. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  41844. const renderTargetData = this._textures.get( renderTarget );
  41845. renderContext.textures = renderTargetData.textures;
  41846. renderContext.depthTexture = renderTargetData.depthTexture;
  41847. renderContext.width = renderTargetData.width;
  41848. renderContext.height = renderTargetData.height;
  41849. renderContext.renderTarget = renderTarget;
  41850. renderContext.depth = renderTarget.depthBuffer;
  41851. renderContext.stencil = renderTarget.stencilBuffer;
  41852. } else {
  41853. renderContext.textures = null;
  41854. renderContext.depthTexture = null;
  41855. renderContext.width = _drawingBufferSize.width;
  41856. renderContext.height = _drawingBufferSize.height;
  41857. renderContext.depth = this.depth;
  41858. renderContext.stencil = this.stencil;
  41859. }
  41860. renderContext.width >>= activeMipmapLevel;
  41861. renderContext.height >>= activeMipmapLevel;
  41862. renderContext.activeCubeFace = activeCubeFace;
  41863. renderContext.activeMipmapLevel = activeMipmapLevel;
  41864. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  41865. //
  41866. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  41867. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  41868. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  41869. }
  41870. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  41871. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  41872. }
  41873. //
  41874. this._background.update( sceneRef, renderList, renderContext );
  41875. //
  41876. renderContext.camera = camera;
  41877. this.backend.beginRender( renderContext );
  41878. // process render lists
  41879. const {
  41880. bundles,
  41881. lightsNode,
  41882. transparentDoublePass: transparentDoublePassObjects,
  41883. transparent: transparentObjects,
  41884. opaque: opaqueObjects
  41885. } = renderList;
  41886. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  41887. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41888. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41889. // finish render pass
  41890. this.backend.finishRender( renderContext );
  41891. // restore render tree
  41892. nodeFrame.renderId = previousRenderId;
  41893. this._currentRenderContext = previousRenderContext;
  41894. this._currentRenderObjectFunction = previousRenderObjectFunction;
  41895. this._handleObjectFunction = previousHandleObjectFunction;
  41896. //
  41897. this._callDepth --;
  41898. if ( frameBufferTarget !== null ) {
  41899. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  41900. this._renderOutput( renderTarget );
  41901. }
  41902. //
  41903. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  41904. //
  41905. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  41906. //
  41907. return renderContext;
  41908. }
  41909. _setXRLayerSize( width, height ) {
  41910. // TODO: Find a better solution to resize the canvas when in XR.
  41911. this._canvasTarget._width = width;
  41912. this._canvasTarget._height = height;
  41913. this.setViewport( 0, 0, width, height );
  41914. }
  41915. /**
  41916. * The output pass performs tone mapping and color space conversion.
  41917. *
  41918. * @private
  41919. * @param {RenderTarget} renderTarget - The current render target.
  41920. */
  41921. _renderOutput( renderTarget ) {
  41922. const quad = this._quad;
  41923. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  41924. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  41925. quad.material.needsUpdate = true;
  41926. }
  41927. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  41928. const currentAutoClear = this.autoClear;
  41929. const currentXR = this.xr.enabled;
  41930. this.autoClear = false;
  41931. this.xr.enabled = false;
  41932. this._renderScene( quad, quad.camera, false );
  41933. this.autoClear = currentAutoClear;
  41934. this.xr.enabled = currentXR;
  41935. }
  41936. /**
  41937. * Returns the maximum available anisotropy for texture filtering.
  41938. *
  41939. * @return {number} The maximum available anisotropy.
  41940. */
  41941. getMaxAnisotropy() {
  41942. return this.backend.getMaxAnisotropy();
  41943. }
  41944. /**
  41945. * Returns the active cube face.
  41946. *
  41947. * @return {number} The active cube face.
  41948. */
  41949. getActiveCubeFace() {
  41950. return this._activeCubeFace;
  41951. }
  41952. /**
  41953. * Returns the active mipmap level.
  41954. *
  41955. * @return {number} The active mipmap level.
  41956. */
  41957. getActiveMipmapLevel() {
  41958. return this._activeMipmapLevel;
  41959. }
  41960. /**
  41961. * Applications are advised to always define the animation loop
  41962. * with this method and not manually with `requestAnimationFrame()`
  41963. * for best compatibility.
  41964. *
  41965. * @async
  41966. * @param {?onAnimationCallback} callback - The application's animation loop.
  41967. * @return {Promise} A Promise that resolves when the set has been executed.
  41968. */
  41969. async setAnimationLoop( callback ) {
  41970. if ( this._initialized === false ) await this.init();
  41971. this._animation.setAnimationLoop( callback );
  41972. }
  41973. /**
  41974. * Returns the current animation loop callback.
  41975. *
  41976. * @return {?Function} The current animation loop callback.
  41977. */
  41978. getAnimationLoop() {
  41979. return this._animation.getAnimationLoop();
  41980. }
  41981. /**
  41982. * Can be used to transfer buffer data from a storage buffer attribute
  41983. * from the GPU to the CPU in context of compute shaders.
  41984. *
  41985. * @async
  41986. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  41987. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  41988. */
  41989. async getArrayBufferAsync( attribute ) {
  41990. return await this.backend.getArrayBufferAsync( attribute );
  41991. }
  41992. /**
  41993. * Returns the rendering context.
  41994. *
  41995. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  41996. */
  41997. getContext() {
  41998. return this.backend.getContext();
  41999. }
  42000. /**
  42001. * Returns the pixel ratio.
  42002. *
  42003. * @return {number} The pixel ratio.
  42004. */
  42005. getPixelRatio() {
  42006. return this._canvasTarget.getPixelRatio();
  42007. }
  42008. /**
  42009. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  42010. *
  42011. * @param {Vector2} target - The method writes the result in this target object.
  42012. * @return {Vector2} The drawing buffer size.
  42013. */
  42014. getDrawingBufferSize( target ) {
  42015. return this._canvasTarget.getDrawingBufferSize( target );
  42016. }
  42017. /**
  42018. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  42019. *
  42020. * @param {Vector2} target - The method writes the result in this target object.
  42021. * @return {Vector2} The renderer's size in logical pixels.
  42022. */
  42023. getSize( target ) {
  42024. return this._canvasTarget.getSize( target );
  42025. }
  42026. /**
  42027. * Sets the given pixel ratio and resizes the canvas if necessary.
  42028. *
  42029. * @param {number} [value=1] - The pixel ratio.
  42030. */
  42031. setPixelRatio( value = 1 ) {
  42032. this._canvasTarget.setPixelRatio( value );
  42033. }
  42034. /**
  42035. * This method allows to define the drawing buffer size by specifying
  42036. * width, height and pixel ratio all at once. The size of the drawing
  42037. * buffer is computed with this formula:
  42038. * ```js
  42039. * size.x = width * pixelRatio;
  42040. * size.y = height * pixelRatio;
  42041. * ```
  42042. *
  42043. * @param {number} width - The width in logical pixels.
  42044. * @param {number} height - The height in logical pixels.
  42045. * @param {number} pixelRatio - The pixel ratio.
  42046. */
  42047. setDrawingBufferSize( width, height, pixelRatio ) {
  42048. // Renderer can't be resized while presenting in XR.
  42049. if ( this.xr && this.xr.isPresenting ) return;
  42050. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  42051. }
  42052. /**
  42053. * Sets the size of the renderer.
  42054. *
  42055. * @param {number} width - The width in logical pixels.
  42056. * @param {number} height - The height in logical pixels.
  42057. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  42058. */
  42059. setSize( width, height, updateStyle = true ) {
  42060. // Renderer can't be resized while presenting in XR.
  42061. if ( this.xr && this.xr.isPresenting ) return;
  42062. this._canvasTarget.setSize( width, height, updateStyle );
  42063. }
  42064. /**
  42065. * Defines a manual sort function for the opaque render list.
  42066. * Pass `null` to use the default sort.
  42067. *
  42068. * @param {Function} method - The sort function.
  42069. */
  42070. setOpaqueSort( method ) {
  42071. this._opaqueSort = method;
  42072. }
  42073. /**
  42074. * Defines a manual sort function for the transparent render list.
  42075. * Pass `null` to use the default sort.
  42076. *
  42077. * @param {Function} method - The sort function.
  42078. */
  42079. setTransparentSort( method ) {
  42080. this._transparentSort = method;
  42081. }
  42082. /**
  42083. * Returns the scissor rectangle.
  42084. *
  42085. * @param {Vector4} target - The method writes the result in this target object.
  42086. * @return {Vector4} The scissor rectangle.
  42087. */
  42088. getScissor( target ) {
  42089. return this._canvasTarget.getScissor( target );
  42090. }
  42091. /**
  42092. * Defines the scissor rectangle.
  42093. *
  42094. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the box in logical pixel unit.
  42095. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  42096. * @param {number} y - The vertical coordinate for the upper left corner of the box in logical pixel unit.
  42097. * @param {number} width - The width of the scissor box in logical pixel unit.
  42098. * @param {number} height - The height of the scissor box in logical pixel unit.
  42099. */
  42100. setScissor( x, y, width, height ) {
  42101. this._canvasTarget.setScissor( x, y, width, height );
  42102. }
  42103. /**
  42104. * Returns the scissor test value.
  42105. *
  42106. * @return {boolean} Whether the scissor test should be enabled or not.
  42107. */
  42108. getScissorTest() {
  42109. return this._canvasTarget.getScissorTest();
  42110. }
  42111. /**
  42112. * Defines the scissor test.
  42113. *
  42114. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42115. */
  42116. setScissorTest( boolean ) {
  42117. this._canvasTarget.setScissorTest( boolean );
  42118. // TODO: Move it to CanvasTarget event listener.
  42119. this.backend.setScissorTest( boolean );
  42120. }
  42121. /**
  42122. * Returns the viewport definition.
  42123. *
  42124. * @param {Vector4} target - The method writes the result in this target object.
  42125. * @return {Vector4} The viewport definition.
  42126. */
  42127. getViewport( target ) {
  42128. return this._canvasTarget.getViewport( target );
  42129. }
  42130. /**
  42131. * Defines the viewport.
  42132. *
  42133. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the viewport origin in logical pixel unit.
  42134. * @param {number} y - The vertical coordinate for the upper left corner of the viewport origin in logical pixel unit.
  42135. * @param {number} width - The width of the viewport in logical pixel unit.
  42136. * @param {number} height - The height of the viewport in logical pixel unit.
  42137. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  42138. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  42139. */
  42140. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  42141. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  42142. }
  42143. /**
  42144. * Returns the clear color.
  42145. *
  42146. * @param {Color} target - The method writes the result in this target object.
  42147. * @return {Color} The clear color.
  42148. */
  42149. getClearColor( target ) {
  42150. return target.copy( this._clearColor );
  42151. }
  42152. /**
  42153. * Defines the clear color and optionally the clear alpha.
  42154. *
  42155. * @param {Color} color - The clear color.
  42156. * @param {number} [alpha=1] - The clear alpha.
  42157. */
  42158. setClearColor( color, alpha = 1 ) {
  42159. this._clearColor.set( color );
  42160. this._clearColor.a = alpha;
  42161. }
  42162. /**
  42163. * Returns the clear alpha.
  42164. *
  42165. * @return {number} The clear alpha.
  42166. */
  42167. getClearAlpha() {
  42168. return this._clearColor.a;
  42169. }
  42170. /**
  42171. * Defines the clear alpha.
  42172. *
  42173. * @param {number} alpha - The clear alpha.
  42174. */
  42175. setClearAlpha( alpha ) {
  42176. this._clearColor.a = alpha;
  42177. }
  42178. /**
  42179. * Returns the clear depth.
  42180. *
  42181. * @return {number} The clear depth.
  42182. */
  42183. getClearDepth() {
  42184. return ( this.reversedDepthBuffer === true ) ? 1 - this._clearDepth : this._clearDepth;
  42185. }
  42186. /**
  42187. * Defines the clear depth.
  42188. *
  42189. * @param {number} depth - The clear depth.
  42190. */
  42191. setClearDepth( depth ) {
  42192. this._clearDepth = depth;
  42193. }
  42194. /**
  42195. * Returns the clear stencil.
  42196. *
  42197. * @return {number} The clear stencil.
  42198. */
  42199. getClearStencil() {
  42200. return this._clearStencil;
  42201. }
  42202. /**
  42203. * Defines the clear stencil.
  42204. *
  42205. * @param {number} stencil - The clear stencil.
  42206. */
  42207. setClearStencil( stencil ) {
  42208. this._clearStencil = stencil;
  42209. }
  42210. /**
  42211. * This method performs an occlusion query for the given 3D object.
  42212. * It returns `true` if the given 3D object is fully occluded by other
  42213. * 3D objects in the scene.
  42214. *
  42215. * @param {Object3D} object - The 3D object to test.
  42216. * @return {boolean} Whether the 3D object is fully occluded or not.
  42217. */
  42218. isOccluded( object ) {
  42219. const renderContext = this._currentRenderContext;
  42220. return renderContext && this.backend.isOccluded( renderContext, object );
  42221. }
  42222. /**
  42223. * Performs a manual clear operation. This method ignores `autoClear` properties.
  42224. *
  42225. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42226. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42227. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42228. */
  42229. clear( color = true, depth = true, stencil = true ) {
  42230. if ( this._initialized === false ) {
  42231. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42232. }
  42233. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42234. let renderContext = null;
  42235. if ( renderTarget !== null ) {
  42236. this._textures.updateRenderTarget( renderTarget );
  42237. const renderTargetData = this._textures.get( renderTarget );
  42238. renderContext = this._renderContexts.get( renderTarget );
  42239. renderContext.textures = renderTargetData.textures;
  42240. renderContext.depthTexture = renderTargetData.depthTexture;
  42241. renderContext.width = renderTargetData.width;
  42242. renderContext.height = renderTargetData.height;
  42243. renderContext.renderTarget = renderTarget;
  42244. renderContext.depth = renderTarget.depthBuffer;
  42245. renderContext.stencil = renderTarget.stencilBuffer;
  42246. // #30329
  42247. const color = this.backend.getClearColor();
  42248. renderContext.clearColorValue.r = color.r;
  42249. renderContext.clearColorValue.g = color.g;
  42250. renderContext.clearColorValue.b = color.b;
  42251. renderContext.clearColorValue.a = color.a;
  42252. renderContext.clearDepthValue = this.getClearDepth();
  42253. renderContext.clearStencilValue = this.getClearStencil();
  42254. renderContext.activeCubeFace = this.getActiveCubeFace();
  42255. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  42256. }
  42257. this.backend.clear( color, depth, stencil, renderContext );
  42258. if ( renderTarget !== null && this._renderTarget === null ) {
  42259. this._renderOutput( renderTarget );
  42260. }
  42261. }
  42262. /**
  42263. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  42264. */
  42265. clearColor() {
  42266. this.clear( true, false, false );
  42267. }
  42268. /**
  42269. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  42270. */
  42271. clearDepth() {
  42272. this.clear( false, true, false );
  42273. }
  42274. /**
  42275. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  42276. */
  42277. clearStencil() {
  42278. this.clear( false, false, true );
  42279. }
  42280. /**
  42281. * Async version of {@link Renderer#clear}.
  42282. *
  42283. * @async
  42284. * @deprecated
  42285. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42286. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42287. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42288. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42289. */
  42290. async clearAsync( color = true, depth = true, stencil = true ) {
  42291. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42292. await this.init();
  42293. this.clear( color, depth, stencil );
  42294. }
  42295. /**
  42296. * Async version of {@link Renderer#clearColor}.
  42297. *
  42298. * @async
  42299. * @deprecated
  42300. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42301. */
  42302. async clearColorAsync() {
  42303. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42304. this.clear( true, false, false );
  42305. }
  42306. /**
  42307. * Async version of {@link Renderer#clearDepth}.
  42308. *
  42309. * @async
  42310. * @deprecated
  42311. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42312. */
  42313. async clearDepthAsync() {
  42314. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42315. this.clear( false, true, false );
  42316. }
  42317. /**
  42318. * Async version of {@link Renderer#clearStencil}.
  42319. *
  42320. * @async
  42321. * @deprecated
  42322. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42323. */
  42324. async clearStencilAsync() {
  42325. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42326. this.clear( false, false, true );
  42327. }
  42328. /**
  42329. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  42330. * If this is the case, the renderer allocates an internal render target for that purpose.
  42331. *
  42332. */
  42333. get needsFrameBufferTarget() {
  42334. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  42335. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  42336. return useToneMapping || useColorSpace;
  42337. }
  42338. /**
  42339. * The number of samples used for multi-sample anti-aliasing (MSAA).
  42340. *
  42341. * @type {number}
  42342. * @default 0
  42343. */
  42344. get samples() {
  42345. return this._samples;
  42346. }
  42347. /**
  42348. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  42349. *
  42350. * When rendering to a custom render target, the number of samples of that render target is used.
  42351. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  42352. * the number of samples is set to 0.
  42353. *
  42354. * @type {number}
  42355. */
  42356. get currentSamples() {
  42357. let samples = this._samples;
  42358. if ( this._renderTarget !== null ) {
  42359. samples = this._renderTarget.samples;
  42360. } else if ( this.needsFrameBufferTarget ) {
  42361. samples = 0;
  42362. }
  42363. return samples;
  42364. }
  42365. /**
  42366. * The current tone mapping of the renderer. When not producing screen output,
  42367. * the tone mapping is always `NoToneMapping`.
  42368. *
  42369. * @type {number}
  42370. */
  42371. get currentToneMapping() {
  42372. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  42373. }
  42374. /**
  42375. * The current color space of the renderer. When not producing screen output,
  42376. * the color space is always the working color space.
  42377. *
  42378. * @type {string}
  42379. */
  42380. get currentColorSpace() {
  42381. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  42382. }
  42383. /**
  42384. * Returns `true` if the rendering settings are set to screen output.
  42385. *
  42386. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  42387. */
  42388. get isOutputTarget() {
  42389. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  42390. }
  42391. /**
  42392. * Frees all internal resources of the renderer. Call this method if the renderer
  42393. * is no longer in use by your app.
  42394. */
  42395. dispose() {
  42396. if ( this._initialized === true ) {
  42397. this.info.dispose();
  42398. this.backend.dispose();
  42399. this._animation.dispose();
  42400. this._objects.dispose();
  42401. this._geometries.dispose();
  42402. this._pipelines.dispose();
  42403. this._nodes.dispose();
  42404. this._bindings.dispose();
  42405. this._renderLists.dispose();
  42406. this._renderContexts.dispose();
  42407. this._textures.dispose();
  42408. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  42409. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  42410. if ( queryPool !== null ) queryPool.dispose();
  42411. } );
  42412. }
  42413. this.setRenderTarget( null );
  42414. this.setAnimationLoop( null );
  42415. }
  42416. /**
  42417. * Sets the given render target. Calling this method means the renderer does not
  42418. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  42419. * Use `null` as the first argument to reset the state.
  42420. *
  42421. * @param {?RenderTarget} renderTarget - The render target to set.
  42422. * @param {number} [activeCubeFace=0] - The active cube face.
  42423. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  42424. */
  42425. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  42426. this._renderTarget = renderTarget;
  42427. this._activeCubeFace = activeCubeFace;
  42428. this._activeMipmapLevel = activeMipmapLevel;
  42429. }
  42430. /**
  42431. * Returns the current render target.
  42432. *
  42433. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  42434. */
  42435. getRenderTarget() {
  42436. return this._renderTarget;
  42437. }
  42438. /**
  42439. * Sets the output render target for the renderer.
  42440. *
  42441. * @param {Object} renderTarget - The render target to set as the output target.
  42442. */
  42443. setOutputRenderTarget( renderTarget ) {
  42444. this._outputRenderTarget = renderTarget;
  42445. }
  42446. /**
  42447. * Returns the current output target.
  42448. *
  42449. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  42450. */
  42451. getOutputRenderTarget() {
  42452. return this._outputRenderTarget;
  42453. }
  42454. /**
  42455. * Sets the canvas target. The canvas target manages the HTML canvas
  42456. * or the offscreen canvas the renderer draws into.
  42457. *
  42458. * @param {CanvasTarget} canvasTarget - The canvas target.
  42459. */
  42460. setCanvasTarget( canvasTarget ) {
  42461. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  42462. this._canvasTarget = canvasTarget;
  42463. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  42464. }
  42465. /**
  42466. * Returns the current canvas target.
  42467. *
  42468. * @return {CanvasTarget} The current canvas target.
  42469. */
  42470. getCanvasTarget() {
  42471. return this._canvasTarget;
  42472. }
  42473. /**
  42474. * Resets the renderer to the initial state before WebXR started.
  42475. *
  42476. * @private
  42477. */
  42478. _resetXRState() {
  42479. this.backend.setXRTarget( null );
  42480. this.setOutputRenderTarget( null );
  42481. this.setRenderTarget( null );
  42482. this._frameBufferTarget.dispose();
  42483. this._frameBufferTarget = null;
  42484. }
  42485. /**
  42486. * Callback for {@link Renderer#setRenderObjectFunction}.
  42487. *
  42488. * @callback renderObjectFunction
  42489. * @param {Object3D} object - The 3D object.
  42490. * @param {Scene} scene - The scene the 3D object belongs to.
  42491. * @param {Camera} camera - The camera the object should be rendered with.
  42492. * @param {BufferGeometry} geometry - The object's geometry.
  42493. * @param {Material} material - The object's material.
  42494. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42495. * @param {LightsNode} lightsNode - The current lights node.
  42496. * @param {ClippingContext} clippingContext - The clipping context.
  42497. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42498. */
  42499. /**
  42500. * Sets the given render object function. Calling this method overwrites the default implementation
  42501. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  42502. * if you want to modify the way objects are rendered. For example you can define things like "every
  42503. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  42504. * The custom function must always call `renderObject()` in its implementation.
  42505. *
  42506. * Use `null` as the first argument to reset the state.
  42507. *
  42508. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  42509. */
  42510. setRenderObjectFunction( renderObjectFunction ) {
  42511. this._renderObjectFunction = renderObjectFunction;
  42512. }
  42513. /**
  42514. * Returns the current render object function.
  42515. *
  42516. * @return {?Function} The current render object function. Returns `null` if no function is set.
  42517. */
  42518. getRenderObjectFunction() {
  42519. return this._renderObjectFunction;
  42520. }
  42521. /**
  42522. * Execute a single or an array of compute nodes. This method can only be called
  42523. * if the renderer has been initialized.
  42524. *
  42525. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42526. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42527. * - A single number representing count, or
  42528. * - An array [x, y, z] representing dispatch size, or
  42529. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42530. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  42531. */
  42532. compute( computeNodes, dispatchSize = null ) {
  42533. if ( this._isDeviceLost === true ) return;
  42534. if ( this._initialized === false ) {
  42535. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  42536. return this.computeAsync( computeNodes, dispatchSize );
  42537. }
  42538. //
  42539. const nodeFrame = this._nodes.nodeFrame;
  42540. const previousRenderId = nodeFrame.renderId;
  42541. //
  42542. this.info.calls ++;
  42543. this.info.compute.calls ++;
  42544. this.info.compute.frameCalls ++;
  42545. nodeFrame.renderId = this.info.calls;
  42546. //
  42547. this.backend.updateTimeStampUID( computeNodes );
  42548. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  42549. //
  42550. const backend = this.backend;
  42551. const pipelines = this._pipelines;
  42552. const bindings = this._bindings;
  42553. const nodes = this._nodes;
  42554. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  42555. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  42556. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  42557. }
  42558. backend.beginCompute( computeNodes );
  42559. for ( const computeNode of computeList ) {
  42560. // onInit
  42561. if ( pipelines.has( computeNode ) === false ) {
  42562. const dispose = () => {
  42563. computeNode.removeEventListener( 'dispose', dispose );
  42564. pipelines.delete( computeNode );
  42565. bindings.deleteForCompute( computeNode );
  42566. nodes.delete( computeNode );
  42567. };
  42568. computeNode.addEventListener( 'dispose', dispose );
  42569. //
  42570. const onInitFn = computeNode.onInitFunction;
  42571. if ( onInitFn !== null ) {
  42572. onInitFn.call( computeNode, { renderer: this } );
  42573. }
  42574. }
  42575. nodes.updateForCompute( computeNode );
  42576. bindings.updateForCompute( computeNode );
  42577. const computeBindings = bindings.getForCompute( computeNode );
  42578. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  42579. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSize );
  42580. }
  42581. backend.finishCompute( computeNodes );
  42582. //
  42583. nodeFrame.renderId = previousRenderId;
  42584. //
  42585. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  42586. }
  42587. /**
  42588. * Execute a single or an array of compute nodes.
  42589. *
  42590. * @async
  42591. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42592. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42593. * - A single number representing count, or
  42594. * - An array [x, y, z] representing dispatch size, or
  42595. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42596. * @return {Promise} A Promise that resolve when the compute has finished.
  42597. */
  42598. async computeAsync( computeNodes, dispatchSize = null ) {
  42599. if ( this._initialized === false ) await this.init();
  42600. this.compute( computeNodes, dispatchSize );
  42601. }
  42602. /**
  42603. * Checks if the given feature is supported by the selected backend.
  42604. *
  42605. * @async
  42606. * @deprecated
  42607. * @param {string} name - The feature's name.
  42608. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  42609. */
  42610. async hasFeatureAsync( name ) {
  42611. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42612. await this.init();
  42613. return this.hasFeature( name );
  42614. }
  42615. async resolveTimestampsAsync( type = 'render' ) {
  42616. if ( this._initialized === false ) await this.init();
  42617. return this.backend.resolveTimestampsAsync( type );
  42618. }
  42619. /**
  42620. * Checks if the given feature is supported by the selected backend. If the
  42621. * renderer has not been initialized, this method always returns `false`.
  42622. *
  42623. * @param {string} name - The feature's name.
  42624. * @return {boolean} Whether the feature is supported or not.
  42625. */
  42626. hasFeature( name ) {
  42627. if ( this._initialized === false ) {
  42628. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42629. }
  42630. return this.backend.hasFeature( name );
  42631. }
  42632. /**
  42633. * Returns `true` when the renderer has been initialized.
  42634. *
  42635. * @return {boolean} Whether the renderer has been initialized or not.
  42636. */
  42637. hasInitialized() {
  42638. return this._initialized;
  42639. }
  42640. /**
  42641. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  42642. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42643. *
  42644. * @async
  42645. * @deprecated
  42646. * @param {Texture} texture - The texture.
  42647. * @return {Promise} A Promise that resolves when the texture has been initialized.
  42648. */
  42649. async initTextureAsync( texture ) {
  42650. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42651. await this.init();
  42652. this.initTexture( texture );
  42653. }
  42654. /**
  42655. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  42656. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42657. *
  42658. * This method can only be used if the renderer has been initialized.
  42659. *
  42660. * @param {Texture} texture - The texture.
  42661. */
  42662. initTexture( texture ) {
  42663. if ( this._initialized === false ) {
  42664. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42665. }
  42666. this._textures.updateTexture( texture );
  42667. }
  42668. /**
  42669. * Initializes the given render target.
  42670. *
  42671. * @param {RenderTarget} renderTarget - The render target to intialize.
  42672. */
  42673. initRenderTarget( renderTarget ) {
  42674. if ( this._initialized === false ) {
  42675. throw new Error( 'Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42676. }
  42677. this._textures.updateRenderTarget( renderTarget );
  42678. const renderTargetData = this._textures.get( renderTarget );
  42679. const renderContext = this._renderContexts.get( renderTarget );
  42680. renderContext.textures = renderTargetData.textures;
  42681. renderContext.depthTexture = renderTargetData.depthTexture;
  42682. renderContext.width = renderTargetData.width;
  42683. renderContext.height = renderTargetData.height;
  42684. renderContext.renderTarget = renderTarget;
  42685. renderContext.depth = renderTarget.depthBuffer;
  42686. renderContext.stencil = renderTarget.stencilBuffer;
  42687. this.backend.initRenderTarget( renderContext );
  42688. }
  42689. /**
  42690. * Copies the current bound framebuffer into the given texture.
  42691. *
  42692. * @param {FramebufferTexture} framebufferTexture - The texture.
  42693. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  42694. */
  42695. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  42696. if ( rectangle !== null ) {
  42697. if ( rectangle.isVector2 ) {
  42698. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  42699. } else if ( rectangle.isVector4 ) {
  42700. rectangle = _vector4.copy( rectangle ).floor();
  42701. } else {
  42702. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  42703. return;
  42704. }
  42705. } else {
  42706. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  42707. }
  42708. //
  42709. let renderContext = this._currentRenderContext;
  42710. let renderTarget;
  42711. if ( renderContext !== null ) {
  42712. renderTarget = renderContext.renderTarget;
  42713. } else {
  42714. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42715. if ( renderTarget !== null ) {
  42716. this._textures.updateRenderTarget( renderTarget );
  42717. renderContext = this._textures.get( renderTarget );
  42718. }
  42719. }
  42720. //
  42721. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  42722. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  42723. this._inspector.copyFramebufferToTexture( framebufferTexture );
  42724. }
  42725. /**
  42726. * Copies data of the given source texture into a destination texture.
  42727. *
  42728. * @param {Texture} srcTexture - The source texture.
  42729. * @param {Texture} dstTexture - The destination texture.
  42730. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  42731. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  42732. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42733. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42734. */
  42735. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  42736. this._textures.updateTexture( srcTexture );
  42737. this._textures.updateTexture( dstTexture );
  42738. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  42739. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  42740. }
  42741. /**
  42742. * Reads pixel data from the given render target.
  42743. *
  42744. * @async
  42745. * @param {RenderTarget} renderTarget - The render target to read from.
  42746. * @param {number} x - The `x` coordinate of the copy region's origin.
  42747. * @param {number} y - The `y` coordinate of the copy region's origin.
  42748. * @param {number} width - The width of the copy region.
  42749. * @param {number} height - The height of the copy region.
  42750. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  42751. * @param {number} [faceIndex=0] - The active cube face index.
  42752. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  42753. */
  42754. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  42755. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  42756. }
  42757. /**
  42758. * Analyzes the given 3D object's hierarchy and builds render lists from the
  42759. * processed hierarchy.
  42760. *
  42761. * @private
  42762. * @param {Object3D} object - The 3D object to process (usually a scene).
  42763. * @param {Camera} camera - The camera the object is rendered with.
  42764. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  42765. * @param {RenderList} renderList - The current render list.
  42766. * @param {ClippingContext} clippingContext - The current clipping context.
  42767. */
  42768. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  42769. if ( object.visible === false ) return;
  42770. const visible = object.layers.test( camera.layers );
  42771. if ( visible ) {
  42772. if ( object.isGroup ) {
  42773. groupOrder = object.renderOrder;
  42774. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  42775. } else if ( object.isLOD ) {
  42776. if ( object.autoUpdate === true ) object.update( camera );
  42777. } else if ( object.isLight ) {
  42778. renderList.pushLight( object );
  42779. } else if ( object.isSprite ) {
  42780. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42781. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  42782. if ( this.sortObjects === true ) {
  42783. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  42784. }
  42785. const { geometry, material } = object;
  42786. if ( material.visible ) {
  42787. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  42788. }
  42789. }
  42790. } else if ( object.isLineLoop ) {
  42791. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  42792. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  42793. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42794. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  42795. const { geometry, material } = object;
  42796. if ( this.sortObjects === true ) {
  42797. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  42798. _vector4
  42799. .copy( geometry.boundingSphere.center )
  42800. .applyMatrix4( object.matrixWorld )
  42801. .applyMatrix4( _projScreenMatrix );
  42802. }
  42803. if ( Array.isArray( material ) ) {
  42804. const groups = geometry.groups;
  42805. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  42806. const group = groups[ i ];
  42807. const groupMaterial = material[ group.materialIndex ];
  42808. if ( groupMaterial && groupMaterial.visible ) {
  42809. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  42810. }
  42811. }
  42812. } else if ( material.visible ) {
  42813. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  42814. }
  42815. }
  42816. }
  42817. }
  42818. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  42819. const baseRenderList = renderList;
  42820. // replace render list
  42821. renderList = this._renderLists.get( object, camera );
  42822. renderList.begin();
  42823. baseRenderList.pushBundle( {
  42824. bundleGroup: object,
  42825. camera,
  42826. renderList,
  42827. } );
  42828. renderList.finish();
  42829. }
  42830. const children = object.children;
  42831. for ( let i = 0, l = children.length; i < l; i ++ ) {
  42832. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  42833. }
  42834. }
  42835. /**
  42836. * Renders the given render bundles.
  42837. *
  42838. * @private
  42839. * @param {Array<Object>} bundles - Array with render bundle data.
  42840. * @param {Scene} sceneRef - The scene the render bundles belong to.
  42841. * @param {LightsNode} lightsNode - The current lights node.
  42842. */
  42843. _renderBundles( bundles, sceneRef, lightsNode ) {
  42844. for ( const bundle of bundles ) {
  42845. this._renderBundle( bundle, sceneRef, lightsNode );
  42846. }
  42847. }
  42848. /**
  42849. * Renders the transparent objects from the given render lists.
  42850. *
  42851. * @private
  42852. * @param {Array<Object>} renderList - The transparent render list.
  42853. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  42854. * @param {Camera} camera - The camera the render list should be rendered with.
  42855. * @param {Scene} scene - The scene the render list belongs to.
  42856. * @param {LightsNode} lightsNode - The current lights node.
  42857. */
  42858. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  42859. if ( doublePassList.length > 0 ) {
  42860. // render back side
  42861. for ( const { material } of doublePassList ) {
  42862. material.side = BackSide;
  42863. }
  42864. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  42865. // render front side
  42866. for ( const { material } of doublePassList ) {
  42867. material.side = FrontSide;
  42868. }
  42869. this._renderObjects( renderList, camera, scene, lightsNode );
  42870. // restore
  42871. for ( const { material } of doublePassList ) {
  42872. material.side = DoubleSide;
  42873. }
  42874. } else {
  42875. this._renderObjects( renderList, camera, scene, lightsNode );
  42876. }
  42877. }
  42878. /**
  42879. * Renders the objects from the given render list.
  42880. *
  42881. * @private
  42882. * @param {Array<Object>} renderList - The render list.
  42883. * @param {Camera} camera - The camera the render list should be rendered with.
  42884. * @param {Scene} scene - The scene the render list belongs to.
  42885. * @param {LightsNode} lightsNode - The current lights node.
  42886. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42887. */
  42888. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  42889. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  42890. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  42891. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  42892. }
  42893. }
  42894. /**
  42895. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  42896. * The result is cached per material and updated when the material's version changes.
  42897. *
  42898. * @private
  42899. * @param {Material} material
  42900. * @returns {Object} - The shadow nodes for the material.
  42901. */
  42902. _getShadowNodes( material ) {
  42903. const version = material.version;
  42904. let cache = this._cacheShadowNodes.get( material );
  42905. if ( cache === undefined || cache.version !== version ) {
  42906. const hasMap = material.map !== null;
  42907. const hasColorNode = material.colorNode && material.colorNode.isNode;
  42908. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  42909. const hasMaskNode = ( material.maskShadowNode && material.maskShadowNode.isNode ) || ( material.maskNode && material.maskNode.isNode );
  42910. let positionNode = null;
  42911. let colorNode = null;
  42912. let depthNode = null;
  42913. if ( hasMap || hasColorNode || hasCastShadowNode || hasMaskNode ) {
  42914. let shadowRGB;
  42915. let shadowAlpha;
  42916. if ( hasCastShadowNode ) {
  42917. shadowRGB = material.castShadowNode.rgb;
  42918. shadowAlpha = material.castShadowNode.a;
  42919. if ( this.shadowMap.transmitted !== true ) {
  42920. warnOnce( 'Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.' );
  42921. }
  42922. } else {
  42923. shadowRGB = vec3( 0 );
  42924. shadowAlpha = float( 1 );
  42925. }
  42926. if ( hasMap ) {
  42927. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  42928. }
  42929. if ( hasColorNode ) {
  42930. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  42931. }
  42932. colorNode = vec4( shadowRGB, shadowAlpha );
  42933. if ( hasMaskNode ) {
  42934. const maskNode = material.maskShadowNode || material.maskNode;
  42935. colorNode = Fn( ( [ color ] ) => {
  42936. maskNode.not().discard();
  42937. return color;
  42938. } )( colorNode );
  42939. }
  42940. }
  42941. if ( material.depthNode && material.depthNode.isNode ) {
  42942. depthNode = material.depthNode;
  42943. }
  42944. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  42945. positionNode = material.castShadowPositionNode;
  42946. } else if ( material.positionNode && material.positionNode.isNode ) {
  42947. positionNode = material.positionNode;
  42948. }
  42949. cache = {
  42950. version,
  42951. colorNode,
  42952. depthNode,
  42953. positionNode
  42954. };
  42955. this._cacheShadowNodes.set( material, cache );
  42956. }
  42957. return cache;
  42958. }
  42959. /**
  42960. * This method represents the default render object function that manages the render lifecycle
  42961. * of the object.
  42962. *
  42963. * @param {Object3D} object - The 3D object.
  42964. * @param {Scene} scene - The scene the 3D object belongs to.
  42965. * @param {Camera} camera - The camera the object should be rendered with.
  42966. * @param {BufferGeometry} geometry - The object's geometry.
  42967. * @param {Material} material - The object's material.
  42968. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42969. * @param {LightsNode} lightsNode - The current lights node.
  42970. * @param {?ClippingContext} clippingContext - The clipping context.
  42971. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42972. */
  42973. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  42974. let materialOverride = false;
  42975. let materialColorNode;
  42976. let materialDepthNode;
  42977. let materialPositionNode;
  42978. let materialSide;
  42979. //
  42980. object.onBeforeRender( this, scene, camera, geometry, material, group );
  42981. //
  42982. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  42983. const overrideMaterial = scene.overrideMaterial;
  42984. materialOverride = true;
  42985. // store original nodes
  42986. materialColorNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.colorNode : null;
  42987. materialDepthNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.depthNode : null;
  42988. materialPositionNode = ( overrideMaterial.isNodeMaterial ) ? overrideMaterial.positionNode : null;
  42989. materialSide = scene.overrideMaterial.side;
  42990. if ( material.positionNode && material.positionNode.isNode ) {
  42991. overrideMaterial.positionNode = material.positionNode;
  42992. }
  42993. overrideMaterial.alphaTest = material.alphaTest;
  42994. overrideMaterial.alphaMap = material.alphaMap;
  42995. overrideMaterial.transparent = material.transparent || material.transmission > 0 ||
  42996. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  42997. ( material.backdropNode && material.backdropNode.isNode );
  42998. if ( overrideMaterial.isShadowPassMaterial ) {
  42999. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  43000. if ( this.shadowMap.type === VSMShadowMap ) {
  43001. overrideMaterial.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  43002. } else {
  43003. overrideMaterial.side = ( material.shadowSide !== null ) ? material.shadowSide : _shadowSide[ material.side ];
  43004. }
  43005. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  43006. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  43007. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  43008. }
  43009. material = overrideMaterial;
  43010. }
  43011. //
  43012. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  43013. material.side = BackSide;
  43014. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  43015. material.side = FrontSide;
  43016. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  43017. material.side = DoubleSide;
  43018. } else {
  43019. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  43020. }
  43021. //
  43022. if ( materialOverride ) {
  43023. scene.overrideMaterial.colorNode = materialColorNode;
  43024. scene.overrideMaterial.depthNode = materialDepthNode;
  43025. scene.overrideMaterial.positionNode = materialPositionNode;
  43026. scene.overrideMaterial.side = materialSide;
  43027. }
  43028. //
  43029. object.onAfterRender( this, scene, camera, geometry, material, group );
  43030. }
  43031. /**
  43032. * Checks if the given compatibility is supported by the selected backend. If the
  43033. * renderer has not been initialized, this method always returns `false`.
  43034. *
  43035. * @param {string} name - The compatibility's name.
  43036. * @return {boolean} Whether the compatibility is supported or not.
  43037. */
  43038. hasCompatibility( name ) {
  43039. return this.backend.hasCompatibility( name );
  43040. }
  43041. /**
  43042. * This method represents the default `_handleObjectFunction` implementation which creates
  43043. * a render object from the given data and performs the draw command with the selected backend.
  43044. *
  43045. * @private
  43046. * @param {Object3D} object - The 3D object.
  43047. * @param {Material} material - The object's material.
  43048. * @param {Scene} scene - The scene the 3D object belongs to.
  43049. * @param {Camera} camera - The camera the object should be rendered with.
  43050. * @param {LightsNode} lightsNode - The current lights node.
  43051. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43052. * @param {ClippingContext} clippingContext - The clipping context.
  43053. * @param {string} [passId] - An optional ID for identifying the pass.
  43054. */
  43055. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43056. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43057. renderObject.drawRange = object.geometry.drawRange;
  43058. renderObject.group = group;
  43059. if ( this._currentRenderBundle !== null ) {
  43060. const renderBundleData = this.backend.get( this._currentRenderBundle );
  43061. renderBundleData.renderObjects.push( renderObject );
  43062. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  43063. }
  43064. //
  43065. const needsRefresh = this._nodes.needsRefresh( renderObject );
  43066. if ( needsRefresh ) {
  43067. this._nodes.updateBefore( renderObject );
  43068. this._geometries.updateForRender( renderObject );
  43069. this._nodes.updateForRender( renderObject );
  43070. this._bindings.updateForRender( renderObject );
  43071. }
  43072. this._pipelines.updateForRender( renderObject );
  43073. //
  43074. this.backend.draw( renderObject, this.info );
  43075. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  43076. }
  43077. /**
  43078. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  43079. * Used in `compileAsync()`.
  43080. *
  43081. * @private
  43082. * @param {Object3D} object - The 3D object.
  43083. * @param {Material} material - The object's material.
  43084. * @param {Scene} scene - The scene the 3D object belongs to.
  43085. * @param {Camera} camera - The camera the object should be rendered with.
  43086. * @param {LightsNode} lightsNode - The current lights node.
  43087. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43088. * @param {ClippingContext} clippingContext - The clipping context.
  43089. * @param {string} [passId] - An optional ID for identifying the pass.
  43090. */
  43091. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43092. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43093. renderObject.drawRange = object.geometry.drawRange;
  43094. renderObject.group = group;
  43095. //
  43096. this._nodes.updateBefore( renderObject );
  43097. this._geometries.updateForRender( renderObject );
  43098. this._nodes.updateForRender( renderObject );
  43099. this._bindings.updateForRender( renderObject );
  43100. this._pipelines.getForRender( renderObject, this._compilationPromises );
  43101. this._nodes.updateAfter( renderObject );
  43102. }
  43103. /**
  43104. * Callback when the canvas has been resized.
  43105. *
  43106. * @private
  43107. */
  43108. _onCanvasTargetResize() {
  43109. if ( this._initialized ) this.backend.updateSize();
  43110. }
  43111. /**
  43112. * Alias for `compileAsync()`.
  43113. *
  43114. * @method
  43115. * @param {Object3D} scene - The scene or 3D object to precompile.
  43116. * @param {Camera} camera - The camera that is used to render the scene.
  43117. * @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.
  43118. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  43119. */
  43120. get compile() {
  43121. return this.compileAsync;
  43122. }
  43123. }
  43124. /**
  43125. * A binding represents the connection between a resource (like a texture, sampler
  43126. * or uniform buffer) and the resource definition in a shader stage.
  43127. *
  43128. * This module is an abstract base class for all concrete bindings types.
  43129. *
  43130. * @abstract
  43131. * @private
  43132. */
  43133. class Binding {
  43134. /**
  43135. * Constructs a new binding.
  43136. *
  43137. * @param {string} [name=''] - The binding's name.
  43138. */
  43139. constructor( name = '' ) {
  43140. /**
  43141. * The binding's name.
  43142. *
  43143. * @type {string}
  43144. */
  43145. this.name = name;
  43146. /**
  43147. * A bitmask that defines in what shader stages the
  43148. * binding's resource is accessible.
  43149. *
  43150. * @type {number}
  43151. */
  43152. this.visibility = 0;
  43153. }
  43154. /**
  43155. * Makes sure binding's resource is visible for the given shader stage.
  43156. *
  43157. * @param {number} visibility - The shader stage.
  43158. */
  43159. setVisibility( visibility ) {
  43160. this.visibility |= visibility;
  43161. }
  43162. /**
  43163. * The shader stages in which the binding's resource is visible.
  43164. *
  43165. * @return {number} The visibility bitmask.
  43166. */
  43167. getVisibility() {
  43168. return this.visibility;
  43169. }
  43170. /**
  43171. * Clones the binding.
  43172. *
  43173. * @return {Binding} The cloned binding.
  43174. */
  43175. clone() {
  43176. return Object.assign( new this.constructor(), this );
  43177. }
  43178. }
  43179. /**
  43180. * This function is usually called with the length in bytes of an array buffer.
  43181. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  43182. *
  43183. * @function
  43184. * @param {number} floatLength - The buffer length.
  43185. * @return {number} The padded length.
  43186. */
  43187. function getFloatLength( floatLength ) {
  43188. // ensure chunk size alignment (STD140 layout)
  43189. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  43190. }
  43191. /**
  43192. * Represents a buffer binding type.
  43193. *
  43194. * @private
  43195. * @abstract
  43196. * @augments Binding
  43197. */
  43198. class Buffer extends Binding {
  43199. /**
  43200. * Constructs a new buffer.
  43201. *
  43202. * @param {string} name - The buffer's name.
  43203. * @param {TypedArray} [buffer=null] - The buffer.
  43204. */
  43205. constructor( name, buffer = null ) {
  43206. super( name );
  43207. /**
  43208. * This flag can be used for type testing.
  43209. *
  43210. * @type {boolean}
  43211. * @readonly
  43212. * @default true
  43213. */
  43214. this.isBuffer = true;
  43215. /**
  43216. * The bytes per element.
  43217. *
  43218. * @type {number}
  43219. */
  43220. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  43221. /**
  43222. * A reference to the internal buffer.
  43223. *
  43224. * @private
  43225. * @type {TypedArray}
  43226. */
  43227. this._buffer = buffer;
  43228. /**
  43229. * An array of update ranges.
  43230. *
  43231. * @private
  43232. * @type {Array<{start: number, count: number}>}
  43233. */
  43234. this._updateRanges = [];
  43235. }
  43236. /**
  43237. * The array of update ranges.
  43238. *
  43239. * @type {Array<{start: number, count: number}>}
  43240. */
  43241. get updateRanges() {
  43242. return this._updateRanges;
  43243. }
  43244. /**
  43245. * Adds an update range.
  43246. *
  43247. * @param {number} start - The start index.
  43248. * @param {number} count - The number of elements.
  43249. */
  43250. addUpdateRange( start, count ) {
  43251. this.updateRanges.push( { start, count } );
  43252. }
  43253. /**
  43254. * Clears all update ranges.
  43255. */
  43256. clearUpdateRanges() {
  43257. this.updateRanges.length = 0;
  43258. }
  43259. /**
  43260. * The buffer's byte length.
  43261. *
  43262. * @type {number}
  43263. * @readonly
  43264. */
  43265. get byteLength() {
  43266. return getFloatLength( this._buffer.byteLength );
  43267. }
  43268. /**
  43269. * A reference to the internal buffer.
  43270. *
  43271. * @type {Float32Array}
  43272. * @readonly
  43273. */
  43274. get buffer() {
  43275. return this._buffer;
  43276. }
  43277. /**
  43278. * Updates the binding.
  43279. *
  43280. * @return {boolean} Whether the buffer has been updated and must be
  43281. * uploaded to the GPU.
  43282. */
  43283. update() {
  43284. return true;
  43285. }
  43286. }
  43287. /**
  43288. * Represents a uniform buffer binding type.
  43289. *
  43290. * @private
  43291. * @augments Buffer
  43292. */
  43293. class UniformBuffer extends Buffer {
  43294. /**
  43295. * Constructs a new uniform buffer.
  43296. *
  43297. * @param {string} name - The buffer's name.
  43298. * @param {TypedArray} [buffer=null] - The buffer.
  43299. */
  43300. constructor( name, buffer = null ) {
  43301. super( name, buffer );
  43302. /**
  43303. * This flag can be used for type testing.
  43304. *
  43305. * @type {boolean}
  43306. * @readonly
  43307. * @default true
  43308. */
  43309. this.isUniformBuffer = true;
  43310. }
  43311. }
  43312. let _id$4 = 0;
  43313. /**
  43314. * A special form of uniform buffer binding type.
  43315. * It's buffer value is managed by a node object.
  43316. *
  43317. * @private
  43318. * @augments UniformBuffer
  43319. */
  43320. class NodeUniformBuffer extends UniformBuffer {
  43321. /**
  43322. * Constructs a new node-based uniform buffer.
  43323. *
  43324. * @param {BufferNode} nodeUniform - The uniform buffer node.
  43325. * @param {UniformGroupNode} groupNode - The uniform group node.
  43326. */
  43327. constructor( nodeUniform, groupNode ) {
  43328. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  43329. /**
  43330. * The uniform buffer node.
  43331. *
  43332. * @type {BufferNode}
  43333. */
  43334. this.nodeUniform = nodeUniform;
  43335. /**
  43336. * The uniform group node.
  43337. *
  43338. * @type {UniformGroupNode}
  43339. */
  43340. this.groupNode = groupNode;
  43341. /**
  43342. * This flag can be used for type testing.
  43343. *
  43344. * @type {boolean}
  43345. * @readonly
  43346. * @default true
  43347. */
  43348. this.isNodeUniformBuffer = true;
  43349. }
  43350. /**
  43351. * The array of update ranges.
  43352. *
  43353. * @param {Array<{start: number, count: number}>} value - The update ranges.
  43354. */
  43355. set updateRanges( value ) {
  43356. this.nodeUniform.updateRanges = value;
  43357. }
  43358. /**
  43359. * The array of update ranges.
  43360. *
  43361. * @type {Array<{start: number, count: number}>}
  43362. */
  43363. get updateRanges() {
  43364. return this.nodeUniform.updateRanges;
  43365. }
  43366. /**
  43367. * Adds a range of data in the data array to be updated on the GPU.
  43368. *
  43369. * @param {number} start - Position at which to start update.
  43370. * @param {number} count - The number of components to update.
  43371. */
  43372. addUpdateRange( start, count ) {
  43373. this.nodeUniform.addUpdateRange( start, count );
  43374. }
  43375. /**
  43376. * Clears all update ranges.
  43377. */
  43378. clearUpdateRanges() {
  43379. this.nodeUniform.clearUpdateRanges();
  43380. }
  43381. /**
  43382. * The uniform buffer.
  43383. *
  43384. * @type {Float32Array}
  43385. */
  43386. get buffer() {
  43387. return this.nodeUniform.value;
  43388. }
  43389. }
  43390. /**
  43391. * This class represents a uniform buffer binding but with
  43392. * an API that allows to maintain individual uniform objects.
  43393. *
  43394. * @private
  43395. * @augments UniformBuffer
  43396. */
  43397. class UniformsGroup extends UniformBuffer {
  43398. /**
  43399. * Constructs a new uniforms group.
  43400. *
  43401. * @param {string} name - The group's name.
  43402. */
  43403. constructor( name ) {
  43404. super( name );
  43405. /**
  43406. * This flag can be used for type testing.
  43407. *
  43408. * @type {boolean}
  43409. * @readonly
  43410. * @default true
  43411. */
  43412. this.isUniformsGroup = true;
  43413. /**
  43414. * An array with the raw uniform values.
  43415. *
  43416. * @private
  43417. * @type {?Array<number>}
  43418. * @default null
  43419. */
  43420. this._values = null;
  43421. /**
  43422. * An array of uniform objects.
  43423. *
  43424. * The order of uniforms in this array must match the order of uniforms in the shader.
  43425. *
  43426. * @type {Array<Uniform>}
  43427. */
  43428. this.uniforms = [];
  43429. /**
  43430. * A cache for the uniform update ranges.
  43431. *
  43432. * @private
  43433. * @type {Map<number, {start: number, count: number}>}
  43434. */
  43435. this._updateRangeCache = new Map();
  43436. }
  43437. /**
  43438. * Adds a uniform's update range to this buffer.
  43439. *
  43440. * @param {Uniform} uniform - The uniform.
  43441. */
  43442. addUniformUpdateRange( uniform ) {
  43443. const index = uniform.index;
  43444. if ( this._updateRangeCache.has( index ) !== true ) {
  43445. const updateRanges = this.updateRanges;
  43446. const start = uniform.offset;
  43447. const count = uniform.itemSize;
  43448. const range = { start, count };
  43449. updateRanges.push( range );
  43450. this._updateRangeCache.set( index, range );
  43451. }
  43452. }
  43453. /**
  43454. * Clears all update ranges of this buffer.
  43455. */
  43456. clearUpdateRanges() {
  43457. this._updateRangeCache.clear();
  43458. super.clearUpdateRanges();
  43459. }
  43460. /**
  43461. * Adds a uniform to this group.
  43462. *
  43463. * @param {Uniform} uniform - The uniform to add.
  43464. * @return {UniformsGroup} A reference to this group.
  43465. */
  43466. addUniform( uniform ) {
  43467. this.uniforms.push( uniform );
  43468. return this;
  43469. }
  43470. /**
  43471. * Removes a uniform from this group.
  43472. *
  43473. * @param {Uniform} uniform - The uniform to remove.
  43474. * @return {UniformsGroup} A reference to this group.
  43475. */
  43476. removeUniform( uniform ) {
  43477. const index = this.uniforms.indexOf( uniform );
  43478. if ( index !== -1 ) {
  43479. this.uniforms.splice( index, 1 );
  43480. }
  43481. return this;
  43482. }
  43483. /**
  43484. * An array with the raw uniform values.
  43485. *
  43486. * @type {Array<number>}
  43487. */
  43488. get values() {
  43489. if ( this._values === null ) {
  43490. this._values = Array.from( this.buffer );
  43491. }
  43492. return this._values;
  43493. }
  43494. /**
  43495. * A Float32 array buffer with the uniform values.
  43496. *
  43497. * @type {Float32Array}
  43498. */
  43499. get buffer() {
  43500. let buffer = this._buffer;
  43501. if ( buffer === null ) {
  43502. const byteLength = this.byteLength;
  43503. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  43504. this._buffer = buffer;
  43505. }
  43506. return buffer;
  43507. }
  43508. /**
  43509. * The byte length of the buffer with correct buffer alignment.
  43510. *
  43511. * @type {number}
  43512. */
  43513. get byteLength() {
  43514. const bytesPerElement = this.bytesPerElement;
  43515. let offset = 0; // global buffer offset in bytes
  43516. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  43517. const uniform = this.uniforms[ i ];
  43518. const boundary = uniform.boundary;
  43519. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  43520. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  43521. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  43522. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  43523. offset += chunkPadding;
  43524. // Check for chunk overflow
  43525. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  43526. // Add padding to the end of the chunk
  43527. offset += ( GPU_CHUNK_BYTES - chunkStart );
  43528. }
  43529. uniform.offset = offset / bytesPerElement;
  43530. uniform.index = i;
  43531. offset += itemSize;
  43532. }
  43533. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  43534. }
  43535. /**
  43536. * Updates this group by updating each uniform object of
  43537. * the internal uniform list. The uniform objects check if their
  43538. * values has actually changed so this method only returns
  43539. * `true` if there is a real value change.
  43540. *
  43541. * @return {boolean} Whether the uniforms have been updated and
  43542. * must be uploaded to the GPU.
  43543. */
  43544. update() {
  43545. let updated = false;
  43546. for ( const uniform of this.uniforms ) {
  43547. if ( this.updateByType( uniform ) === true ) {
  43548. updated = true;
  43549. }
  43550. }
  43551. return updated;
  43552. }
  43553. /**
  43554. * Updates a given uniform by calling an update method matching
  43555. * the uniforms type.
  43556. *
  43557. * @param {Uniform} uniform - The uniform to update.
  43558. * @return {boolean} Whether the uniform has been updated or not.
  43559. */
  43560. updateByType( uniform ) {
  43561. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  43562. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  43563. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  43564. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  43565. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  43566. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  43567. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  43568. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  43569. }
  43570. /**
  43571. * Updates a given Number uniform.
  43572. *
  43573. * @param {NumberUniform} uniform - The Number uniform.
  43574. * @return {boolean} Whether the uniform has been updated or not.
  43575. */
  43576. updateNumber( uniform ) {
  43577. let updated = false;
  43578. const a = this.values;
  43579. const v = uniform.getValue();
  43580. const offset = uniform.offset;
  43581. const type = uniform.getType();
  43582. if ( a[ offset ] !== v ) {
  43583. const b = this._getBufferForType( type );
  43584. b[ offset ] = a[ offset ] = v;
  43585. updated = true;
  43586. this.addUniformUpdateRange( uniform );
  43587. }
  43588. return updated;
  43589. }
  43590. /**
  43591. * Updates a given Vector2 uniform.
  43592. *
  43593. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  43594. * @return {boolean} Whether the uniform has been updated or not.
  43595. */
  43596. updateVector2( uniform ) {
  43597. let updated = false;
  43598. const a = this.values;
  43599. const v = uniform.getValue();
  43600. const offset = uniform.offset;
  43601. const type = uniform.getType();
  43602. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  43603. const b = this._getBufferForType( type );
  43604. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43605. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43606. updated = true;
  43607. this.addUniformUpdateRange( uniform );
  43608. }
  43609. return updated;
  43610. }
  43611. /**
  43612. * Updates a given Vector3 uniform.
  43613. *
  43614. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  43615. * @return {boolean} Whether the uniform has been updated or not.
  43616. */
  43617. updateVector3( uniform ) {
  43618. let updated = false;
  43619. const a = this.values;
  43620. const v = uniform.getValue();
  43621. const offset = uniform.offset;
  43622. const type = uniform.getType();
  43623. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  43624. const b = this._getBufferForType( type );
  43625. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43626. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43627. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43628. updated = true;
  43629. this.addUniformUpdateRange( uniform );
  43630. }
  43631. return updated;
  43632. }
  43633. /**
  43634. * Updates a given Vector4 uniform.
  43635. *
  43636. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  43637. * @return {boolean} Whether the uniform has been updated or not.
  43638. */
  43639. updateVector4( uniform ) {
  43640. let updated = false;
  43641. const a = this.values;
  43642. const v = uniform.getValue();
  43643. const offset = uniform.offset;
  43644. const type = uniform.getType();
  43645. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  43646. const b = this._getBufferForType( type );
  43647. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43648. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43649. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43650. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  43651. updated = true;
  43652. this.addUniformUpdateRange( uniform );
  43653. }
  43654. return updated;
  43655. }
  43656. /**
  43657. * Updates a given Color uniform.
  43658. *
  43659. * @param {ColorUniform} uniform - The Color uniform.
  43660. * @return {boolean} Whether the uniform has been updated or not.
  43661. */
  43662. updateColor( uniform ) {
  43663. let updated = false;
  43664. const a = this.values;
  43665. const c = uniform.getValue();
  43666. const offset = uniform.offset;
  43667. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  43668. const b = this.buffer;
  43669. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  43670. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  43671. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  43672. updated = true;
  43673. this.addUniformUpdateRange( uniform );
  43674. }
  43675. return updated;
  43676. }
  43677. /**
  43678. * Updates a given Matrix3 uniform.
  43679. *
  43680. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  43681. * @return {boolean} Whether the uniform has been updated or not.
  43682. */
  43683. updateMatrix3( uniform ) {
  43684. let updated = false;
  43685. const a = this.values;
  43686. const e = uniform.getValue().elements;
  43687. const offset = uniform.offset;
  43688. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  43689. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  43690. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  43691. const b = this.buffer;
  43692. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  43693. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  43694. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  43695. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  43696. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  43697. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  43698. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  43699. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  43700. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  43701. updated = true;
  43702. this.addUniformUpdateRange( uniform );
  43703. }
  43704. return updated;
  43705. }
  43706. /**
  43707. * Updates a given Matrix4 uniform.
  43708. *
  43709. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  43710. * @return {boolean} Whether the uniform has been updated or not.
  43711. */
  43712. updateMatrix4( uniform ) {
  43713. let updated = false;
  43714. const a = this.values;
  43715. const e = uniform.getValue().elements;
  43716. const offset = uniform.offset;
  43717. if ( arraysEqual( a, e, offset ) === false ) {
  43718. const b = this.buffer;
  43719. b.set( e, offset );
  43720. setArray( a, e, offset );
  43721. updated = true;
  43722. this.addUniformUpdateRange( uniform );
  43723. }
  43724. return updated;
  43725. }
  43726. /**
  43727. * Returns a typed array that matches the given data type.
  43728. *
  43729. * @private
  43730. * @param {string} type - The data type.
  43731. * @return {TypedArray} The typed array.
  43732. */
  43733. _getBufferForType( type ) {
  43734. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  43735. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  43736. return this.buffer;
  43737. }
  43738. }
  43739. /**
  43740. * Sets the values of the second array to the first array.
  43741. *
  43742. * @private
  43743. * @param {TypedArray} a - The first array.
  43744. * @param {TypedArray} b - The second array.
  43745. * @param {number} offset - An index offset for the first array.
  43746. */
  43747. function setArray( a, b, offset ) {
  43748. for ( let i = 0, l = b.length; i < l; i ++ ) {
  43749. a[ offset + i ] = b[ i ];
  43750. }
  43751. }
  43752. /**
  43753. * Returns `true` if the given arrays are equal.
  43754. *
  43755. * @private
  43756. * @param {TypedArray} a - The first array.
  43757. * @param {TypedArray} b - The second array.
  43758. * @param {number} offset - An index offset for the first array.
  43759. * @return {boolean} Whether the given arrays are equal or not.
  43760. */
  43761. function arraysEqual( a, b, offset ) {
  43762. for ( let i = 0, l = b.length; i < l; i ++ ) {
  43763. if ( a[ offset + i ] !== b[ i ] ) return false;
  43764. }
  43765. return true;
  43766. }
  43767. let _id$3 = 0;
  43768. /**
  43769. * A special form of uniforms group that represents
  43770. * the individual uniforms as node-based uniforms.
  43771. *
  43772. * @private
  43773. * @augments UniformsGroup
  43774. */
  43775. class NodeUniformsGroup extends UniformsGroup {
  43776. /**
  43777. * Constructs a new node-based uniforms group.
  43778. *
  43779. * @param {string} name - The group's name.
  43780. * @param {UniformGroupNode} groupNode - The uniform group node.
  43781. */
  43782. constructor( name, groupNode ) {
  43783. super( name );
  43784. /**
  43785. * The group's ID.
  43786. *
  43787. * @type {number}
  43788. */
  43789. this.id = _id$3 ++;
  43790. /**
  43791. * The uniform group node.
  43792. *
  43793. * @type {UniformGroupNode}
  43794. */
  43795. this.groupNode = groupNode;
  43796. /**
  43797. * This flag can be used for type testing.
  43798. *
  43799. * @type {boolean}
  43800. * @readonly
  43801. * @default true
  43802. */
  43803. this.isNodeUniformsGroup = true;
  43804. }
  43805. }
  43806. /**
  43807. * Represents a sampler binding type.
  43808. *
  43809. * @private
  43810. * @augments Binding
  43811. */
  43812. class Sampler extends Binding {
  43813. /**
  43814. * Constructs a new sampler.
  43815. *
  43816. * @param {string} name - The samplers's name.
  43817. * @param {?Texture} texture - The texture this binding is referring to.
  43818. */
  43819. constructor( name, texture ) {
  43820. super( name );
  43821. /**
  43822. * The texture the sampler is referring to.
  43823. *
  43824. * @private
  43825. * @type {?Texture}
  43826. */
  43827. this._texture = null;
  43828. /**
  43829. * An event listener which is added to {@link texture}'s dispose event.
  43830. *
  43831. * @private
  43832. * @type {Function}
  43833. */
  43834. this._onTextureDispose = () => {
  43835. this.generation = null;
  43836. this.version = 0;
  43837. };
  43838. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  43839. this.texture = texture;
  43840. /**
  43841. * The binding's version.
  43842. *
  43843. * @type {number}
  43844. */
  43845. this.version = texture ? texture.version : 0;
  43846. /**
  43847. * The binding's generation which is an additional version
  43848. * qualifier.
  43849. *
  43850. * @type {?number}
  43851. * @default null
  43852. */
  43853. this.generation = null;
  43854. /**
  43855. * The binding's sampler key.
  43856. *
  43857. * @type {string}
  43858. * @default ''
  43859. */
  43860. this.samplerKey = '';
  43861. /**
  43862. * This flag can be used for type testing.
  43863. *
  43864. * @type {boolean}
  43865. * @readonly
  43866. * @default true
  43867. */
  43868. this.isSampler = true;
  43869. }
  43870. /**
  43871. * Sets the texture of this sampler.
  43872. *
  43873. * @param {Texture} value - The texture to set.
  43874. */
  43875. set texture( value ) {
  43876. if ( this._texture === value ) return;
  43877. if ( this._texture ) {
  43878. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  43879. }
  43880. this._texture = value;
  43881. this.generation = null;
  43882. this.version = 0;
  43883. if ( this._texture ) {
  43884. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  43885. }
  43886. }
  43887. /**
  43888. * Gets the texture of this sampler.
  43889. * @return {?Texture} The texture.
  43890. */
  43891. get texture() {
  43892. return this._texture;
  43893. }
  43894. /**
  43895. * Updates the binding.
  43896. *
  43897. * @return {boolean} Whether the texture has been updated and must be
  43898. * uploaded to the GPU.
  43899. */
  43900. update() {
  43901. const { texture, version } = this;
  43902. if ( version !== texture.version ) {
  43903. this.version = texture.version;
  43904. return true;
  43905. }
  43906. return false;
  43907. }
  43908. clone() {
  43909. const clonedSampler = super.clone();
  43910. // fix dispose handler for cloned instances
  43911. // TODO: Find better solution, see #31747
  43912. clonedSampler._texture = null;
  43913. clonedSampler._onTextureDispose = () => {
  43914. clonedSampler.generation = null;
  43915. clonedSampler.version = 0;
  43916. };
  43917. clonedSampler.texture = this.texture;
  43918. return clonedSampler;
  43919. }
  43920. }
  43921. let _id$2 = 0;
  43922. /**
  43923. * Represents a sampled texture binding type.
  43924. *
  43925. * @private
  43926. * @augments Sampler
  43927. */
  43928. class SampledTexture extends Sampler {
  43929. /**
  43930. * Constructs a new sampled texture.
  43931. *
  43932. * @param {string} name - The sampled texture's name.
  43933. * @param {?Texture} texture - The texture this binding is referring to.
  43934. */
  43935. constructor( name, texture ) {
  43936. super( name, texture );
  43937. /**
  43938. * This identifier.
  43939. *
  43940. * @type {number}
  43941. */
  43942. this.id = _id$2 ++;
  43943. /**
  43944. * Whether the texture is a storage texture or not.
  43945. *
  43946. * @type {boolean}
  43947. * @default false
  43948. */
  43949. this.store = false;
  43950. /**
  43951. * The mip level to bind for storage textures.
  43952. *
  43953. * @type {number}
  43954. * @default 0
  43955. */
  43956. this.mipLevel = 0;
  43957. /**
  43958. * This flag can be used for type testing.
  43959. *
  43960. * @type {boolean}
  43961. * @readonly
  43962. * @default true
  43963. */
  43964. this.isSampledTexture = true;
  43965. }
  43966. }
  43967. /**
  43968. * A special form of sampled texture binding type.
  43969. * It's texture value is managed by a node object.
  43970. *
  43971. * @private
  43972. * @augments SampledTexture
  43973. */
  43974. class NodeSampledTexture extends SampledTexture {
  43975. /**
  43976. * Constructs a new node-based sampled texture.
  43977. *
  43978. * @param {string} name - The textures's name.
  43979. * @param {TextureNode} textureNode - The texture node.
  43980. * @param {UniformGroupNode} groupNode - The uniform group node.
  43981. * @param {?string} [access=null] - The access type.
  43982. */
  43983. constructor( name, textureNode, groupNode, access = null ) {
  43984. super( name, textureNode ? textureNode.value : null );
  43985. /**
  43986. * The texture node.
  43987. *
  43988. * @type {TextureNode}
  43989. */
  43990. this.textureNode = textureNode;
  43991. /**
  43992. * The uniform group node.
  43993. *
  43994. * @type {UniformGroupNode}
  43995. */
  43996. this.groupNode = groupNode;
  43997. /**
  43998. * The access type.
  43999. *
  44000. * @type {?string}
  44001. * @default null
  44002. */
  44003. this.access = access;
  44004. }
  44005. /**
  44006. * Updates the binding.
  44007. *
  44008. * @return {boolean} Whether the texture has been updated and must be
  44009. * uploaded to the GPU.
  44010. */
  44011. update() {
  44012. const { textureNode } = this;
  44013. if ( this.texture !== textureNode.value ) {
  44014. this.texture = textureNode.value;
  44015. return true;
  44016. }
  44017. return super.update();
  44018. }
  44019. }
  44020. /**
  44021. * A special form of sampled cube texture binding type.
  44022. * It's texture value is managed by a node object.
  44023. *
  44024. * @private
  44025. * @augments NodeSampledTexture
  44026. */
  44027. class NodeSampledCubeTexture extends NodeSampledTexture {
  44028. /**
  44029. * Constructs a new node-based sampled cube texture.
  44030. *
  44031. * @param {string} name - The textures's name.
  44032. * @param {TextureNode} textureNode - The texture node.
  44033. * @param {UniformGroupNode} groupNode - The uniform group node.
  44034. * @param {?string} [access=null] - The access type.
  44035. */
  44036. constructor( name, textureNode, groupNode, access = null ) {
  44037. super( name, textureNode, groupNode, access );
  44038. /**
  44039. * This flag can be used for type testing.
  44040. *
  44041. * @type {boolean}
  44042. * @readonly
  44043. * @default true
  44044. */
  44045. this.isSampledCubeTexture = true;
  44046. }
  44047. }
  44048. /**
  44049. * A special form of sampled 3D texture binding type.
  44050. * It's texture value is managed by a node object.
  44051. *
  44052. * @private
  44053. * @augments NodeSampledTexture
  44054. */
  44055. class NodeSampledTexture3D extends NodeSampledTexture {
  44056. /**
  44057. * Constructs a new node-based sampled 3D texture.
  44058. *
  44059. * @param {string} name - The textures's name.
  44060. * @param {TextureNode} textureNode - The texture node.
  44061. * @param {UniformGroupNode} groupNode - The uniform group node.
  44062. * @param {?string} [access=null] - The access type.
  44063. */
  44064. constructor( name, textureNode, groupNode, access = null ) {
  44065. super( name, textureNode, groupNode, access );
  44066. /**
  44067. * This flag can be used for type testing.
  44068. *
  44069. * @type {boolean}
  44070. * @readonly
  44071. * @default true
  44072. */
  44073. this.isSampledTexture3D = true;
  44074. }
  44075. }
  44076. const glslPolyfills = {
  44077. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' ),
  44078. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }' )
  44079. };
  44080. const glslMethods = {
  44081. textureDimensions: 'textureSize',
  44082. equals: 'equal',
  44083. bitcast_float_int: 'floatBitsToInt',
  44084. bitcast_int_float: 'intBitsToFloat',
  44085. bitcast_uint_float: 'uintBitsToFloat',
  44086. bitcast_float_uint: 'floatBitsToUint',
  44087. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  44088. bitcast_int_uint: 'tsl_bitcast_int_to_uint',
  44089. floatpack_snorm_2x16: 'packSnorm2x16',
  44090. floatpack_unorm_2x16: 'packUnorm2x16',
  44091. floatpack_float16_2x16: 'packHalf2x16',
  44092. floatunpack_snorm_2x16: 'unpackSnorm2x16',
  44093. floatunpack_unorm_2x16: 'unpackUnorm2x16',
  44094. floatunpack_float16_2x16: 'unpackHalf2x16'
  44095. };
  44096. const precisionLib = {
  44097. low: 'lowp',
  44098. medium: 'mediump',
  44099. high: 'highp'
  44100. };
  44101. const supports$1 = {
  44102. swizzleAssign: true,
  44103. storageBuffer: false
  44104. };
  44105. const interpolationTypeMap = {
  44106. perspective: 'smooth',
  44107. linear: 'noperspective'
  44108. };
  44109. const interpolationModeMap = {
  44110. 'centroid': 'centroid'
  44111. };
  44112. const defaultPrecisions = `
  44113. precision highp float;
  44114. precision highp int;
  44115. precision highp sampler2D;
  44116. precision highp sampler3D;
  44117. precision highp samplerCube;
  44118. precision highp sampler2DArray;
  44119. precision highp usampler2D;
  44120. precision highp usampler3D;
  44121. precision highp usamplerCube;
  44122. precision highp usampler2DArray;
  44123. precision highp isampler2D;
  44124. precision highp isampler3D;
  44125. precision highp isamplerCube;
  44126. precision highp isampler2DArray;
  44127. precision highp sampler2DShadow;
  44128. precision highp sampler2DArrayShadow;
  44129. precision highp samplerCubeShadow;
  44130. `;
  44131. /**
  44132. * A node builder targeting GLSL.
  44133. *
  44134. * This module generates GLSL shader code from node materials and also
  44135. * generates the respective bindings and vertex buffer definitions. These
  44136. * data are later used by the renderer to create render and compute pipelines
  44137. * for render objects.
  44138. *
  44139. * @augments NodeBuilder
  44140. */
  44141. class GLSLNodeBuilder extends NodeBuilder {
  44142. /**
  44143. * Constructs a new GLSL node builder renderer.
  44144. *
  44145. * @param {Object3D} object - The 3D object.
  44146. * @param {Renderer} renderer - The renderer.
  44147. */
  44148. constructor( object, renderer ) {
  44149. super( object, renderer, new GLSLNodeParser() );
  44150. /**
  44151. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  44152. * another dictionary which manages UBOs per group ('render','frame','object').
  44153. *
  44154. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  44155. */
  44156. this.uniformGroups = {};
  44157. /**
  44158. * An array that holds objects defining the varying and attribute data in
  44159. * context of Transform Feedback.
  44160. *
  44161. * @type {Array<Object<string,AttributeNode|string>>}
  44162. */
  44163. this.transforms = [];
  44164. /**
  44165. * A dictionary that holds for each shader stage a Map of used extensions.
  44166. *
  44167. * @type {Object<string,Map<string,Object>>}
  44168. */
  44169. this.extensions = {};
  44170. /**
  44171. * A dictionary that holds for each shader stage an Array of used builtins.
  44172. *
  44173. * @type {Object<string,Array<string>>}
  44174. */
  44175. this.builtins = { vertex: [], fragment: [], compute: [] };
  44176. }
  44177. /**
  44178. * Checks if the given texture requires a manual conversion to the working color space.
  44179. *
  44180. * @param {Texture} texture - The texture to check.
  44181. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  44182. */
  44183. needsToWorkingColorSpace( texture ) {
  44184. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  44185. }
  44186. /**
  44187. * Includes the given method name into the current
  44188. * function node.
  44189. *
  44190. * @private
  44191. * @param {string} name - The method name to include.
  44192. * @return {CodeNode} The respective code node.
  44193. */
  44194. _include( name ) {
  44195. const codeNode = glslPolyfills[ name ];
  44196. codeNode.build( this );
  44197. this.addInclude( codeNode );
  44198. return codeNode;
  44199. }
  44200. /**
  44201. * Returns the native shader method name for a given generic name.
  44202. *
  44203. * @param {string} method - The method name to resolve.
  44204. * @return {string} The resolved GLSL method name.
  44205. */
  44206. getMethod( method ) {
  44207. if ( glslPolyfills[ method ] !== undefined ) {
  44208. this._include( method );
  44209. }
  44210. return glslMethods[ method ] || method;
  44211. }
  44212. /**
  44213. * Returns the bitcast method name for a given input and outputType.
  44214. *
  44215. * @param {string} type - The output type to bitcast to.
  44216. * @param {string} inputType - The input type of the.
  44217. * @return {string} The resolved WGSL bitcast invocation.
  44218. */
  44219. getBitcastMethod( type, inputType ) {
  44220. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  44221. }
  44222. /**
  44223. * Returns the float packing method name for a given numeric encoding.
  44224. *
  44225. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  44226. * @returns {string} The resolved GLSL float packing method name.
  44227. */
  44228. getFloatPackingMethod( encoding ) {
  44229. return this.getMethod( `floatpack_${ encoding }_2x16` );
  44230. }
  44231. /**
  44232. * Returns the float unpacking method name for a given numeric encoding.
  44233. *
  44234. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  44235. * @returns {string} The resolved GLSL float unpacking method name.
  44236. */
  44237. getFloatUnpackingMethod( encoding ) {
  44238. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  44239. }
  44240. /**
  44241. * Returns the native snippet for a ternary operation.
  44242. *
  44243. * @param {string} condSnippet - The condition determining which expression gets resolved.
  44244. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  44245. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  44246. * @return {string} The resolved method name.
  44247. */
  44248. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  44249. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  44250. }
  44251. /**
  44252. * Returns the output struct name. Not relevant for GLSL.
  44253. *
  44254. * @return {string}
  44255. */
  44256. getOutputStructName() {
  44257. return '';
  44258. }
  44259. /**
  44260. * Builds the given shader node.
  44261. *
  44262. * @param {ShaderNodeInternal} shaderNode - The shader node.
  44263. * @return {string} The GLSL function code.
  44264. */
  44265. buildFunctionCode( shaderNode ) {
  44266. const layout = shaderNode.layout;
  44267. const flowData = this.flowShaderNode( shaderNode );
  44268. const parameters = [];
  44269. for ( const input of layout.inputs ) {
  44270. parameters.push( this.getType( input.type ) + ' ' + input.name );
  44271. }
  44272. //
  44273. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  44274. ${ flowData.vars }
  44275. ${ flowData.code }
  44276. return ${ flowData.result };
  44277. }`;
  44278. //
  44279. return code;
  44280. }
  44281. /**
  44282. * Setups the Pixel Buffer Object (PBO) for the given storage
  44283. * buffer node.
  44284. *
  44285. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  44286. */
  44287. setupPBO( storageBufferNode ) {
  44288. const attribute = storageBufferNode.value;
  44289. if ( attribute.pbo === undefined ) {
  44290. const originalArray = attribute.array;
  44291. const numElements = attribute.count * attribute.itemSize;
  44292. const { itemSize } = attribute;
  44293. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  44294. let format = isInteger ? RedIntegerFormat : RedFormat;
  44295. if ( itemSize === 2 ) {
  44296. format = isInteger ? RGIntegerFormat : RGFormat;
  44297. } else if ( itemSize === 3 ) {
  44298. format = isInteger ? RGBIntegerFormat : RGBFormat;
  44299. } else if ( itemSize === 4 ) {
  44300. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  44301. }
  44302. const typeMap = {
  44303. Float32Array: FloatType,
  44304. Uint8Array: UnsignedByteType,
  44305. Uint16Array: UnsignedShortType,
  44306. Uint32Array: UnsignedIntType,
  44307. Int8Array: ByteType,
  44308. Int16Array: ShortType,
  44309. Int32Array: IntType,
  44310. Uint8ClampedArray: UnsignedByteType,
  44311. };
  44312. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  44313. let height = Math.ceil( ( numElements / itemSize ) / width );
  44314. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  44315. const newSize = width * height * itemSize;
  44316. const newArray = new originalArray.constructor( newSize );
  44317. newArray.set( originalArray, 0 );
  44318. attribute.array = newArray;
  44319. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  44320. pboTexture.needsUpdate = true;
  44321. pboTexture.isPBOTexture = true;
  44322. const pbo = new TextureNode( pboTexture, null, null );
  44323. pbo.setPrecision( 'high' );
  44324. attribute.pboNode = pbo;
  44325. attribute.pbo = pbo.value;
  44326. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44327. }
  44328. }
  44329. /**
  44330. * Returns a GLSL snippet that represents the property name of the given node.
  44331. *
  44332. * @param {Node} node - The node.
  44333. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44334. * @return {string} The property name.
  44335. */
  44336. getPropertyName( node, shaderStage = this.shaderStage ) {
  44337. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  44338. return node.name;
  44339. }
  44340. return super.getPropertyName( node, shaderStage );
  44341. }
  44342. /**
  44343. * Setups the Pixel Buffer Object (PBO) for the given storage
  44344. * buffer node.
  44345. *
  44346. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  44347. * @return {string} The property name.
  44348. */
  44349. generatePBO( storageArrayElementNode ) {
  44350. const { node, indexNode } = storageArrayElementNode;
  44351. const attribute = node.value;
  44352. if ( this.renderer.backend.has( attribute ) ) {
  44353. const attributeData = this.renderer.backend.get( attribute );
  44354. attributeData.pbo = attribute.pbo;
  44355. }
  44356. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44357. const textureName = this.getPropertyName( nodeUniform );
  44358. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  44359. const indexSnippet = indexNode.build( this, 'uint' );
  44360. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  44361. let propertyName = elementNodeData.propertyName;
  44362. if ( propertyName === undefined ) {
  44363. // property element
  44364. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  44365. propertyName = this.getPropertyName( nodeVar );
  44366. // property size
  44367. const bufferNodeData = this.getDataFromNode( node );
  44368. let propertySizeName = bufferNodeData.propertySizeName;
  44369. if ( propertySizeName === undefined ) {
  44370. propertySizeName = propertyName + 'Size';
  44371. this.getVarFromNode( node, propertySizeName, 'uint' );
  44372. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  44373. bufferNodeData.propertySizeName = propertySizeName;
  44374. }
  44375. //
  44376. const { itemSize } = attribute;
  44377. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  44378. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  44379. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  44380. //
  44381. let prefix = 'vec4';
  44382. if ( attribute.pbo.type === UnsignedIntType ) {
  44383. prefix = 'uvec4';
  44384. } else if ( attribute.pbo.type === IntType ) {
  44385. prefix = 'ivec4';
  44386. }
  44387. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  44388. elementNodeData.propertyName = propertyName;
  44389. }
  44390. return propertyName;
  44391. }
  44392. /**
  44393. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  44394. *
  44395. * @param {?Texture} texture - The texture.
  44396. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44397. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44398. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44399. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44400. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44401. * @return {string} The GLSL snippet.
  44402. */
  44403. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  44404. if ( levelSnippet === null ) levelSnippet = '0';
  44405. let snippet;
  44406. if ( depthSnippet ) {
  44407. if ( offsetSnippet ) {
  44408. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  44409. } else {
  44410. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  44411. }
  44412. } else {
  44413. if ( offsetSnippet ) {
  44414. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44415. } else {
  44416. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  44417. }
  44418. }
  44419. if ( texture !== null && texture.isDepthTexture ) {
  44420. snippet += '.x';
  44421. }
  44422. return snippet;
  44423. }
  44424. /**
  44425. * Generates the GLSL snippet for sampling/loading the given texture.
  44426. *
  44427. * @param {Texture} texture - The texture.
  44428. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44429. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44430. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44431. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44432. * @return {string} The GLSL snippet.
  44433. */
  44434. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  44435. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  44436. if ( texture.isDepthTexture ) {
  44437. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  44438. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  44439. }
  44440. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  44441. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  44442. }
  44443. /**
  44444. * Generates the GLSL snippet when sampling textures with explicit mip level.
  44445. *
  44446. * @param {Texture} texture - The texture.
  44447. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44448. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44449. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44450. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44451. * @return {string} The GLSL snippet.
  44452. */
  44453. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  44454. if ( offsetSnippet ) {
  44455. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44456. }
  44457. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  44458. }
  44459. /**
  44460. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  44461. *
  44462. * @param {Texture} texture - The texture.
  44463. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44464. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44465. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  44466. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44467. * @return {string} The GLSL snippet.
  44468. */
  44469. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  44470. if ( offsetSnippet ) {
  44471. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  44472. }
  44473. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  44474. }
  44475. /**
  44476. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  44477. *
  44478. * @param {Texture} texture - The texture.
  44479. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44480. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44481. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  44482. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44483. * @return {string} The GLSL snippet.
  44484. */
  44485. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  44486. if ( offsetSnippet ) {
  44487. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  44488. }
  44489. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  44490. }
  44491. /**
  44492. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  44493. * against a reference value.
  44494. *
  44495. * @param {Texture} texture - The texture.
  44496. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44497. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44498. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  44499. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  44500. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44501. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44502. * @return {string} The GLSL snippet.
  44503. */
  44504. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  44505. if ( shaderStage === 'fragment' ) {
  44506. // Cube shadow maps use vec4(direction, compareValue)
  44507. if ( texture.isCubeTexture ) {
  44508. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ compareSnippet } ) )`;
  44509. }
  44510. if ( depthSnippet ) {
  44511. if ( offsetSnippet ) {
  44512. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44513. }
  44514. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  44515. }
  44516. if ( offsetSnippet ) {
  44517. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44518. }
  44519. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  44520. } else {
  44521. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  44522. }
  44523. }
  44524. /**
  44525. * Returns the variables of the given shader stage as a GLSL string.
  44526. *
  44527. * @param {string} shaderStage - The shader stage.
  44528. * @return {string} The GLSL snippet that defines the variables.
  44529. */
  44530. getVars( shaderStage ) {
  44531. const snippets = [];
  44532. const vars = this.vars[ shaderStage ];
  44533. if ( vars !== undefined ) {
  44534. for ( const variable of vars ) {
  44535. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  44536. }
  44537. }
  44538. return snippets.join( '\n\t' );
  44539. }
  44540. /**
  44541. * Returns the uniforms of the given shader stage as a GLSL string.
  44542. *
  44543. * @param {string} shaderStage - The shader stage.
  44544. * @return {string} The GLSL snippet that defines the uniforms.
  44545. */
  44546. getUniforms( shaderStage ) {
  44547. const uniforms = this.uniforms[ shaderStage ];
  44548. const bindingSnippets = [];
  44549. const uniformGroups = {};
  44550. for ( const uniform of uniforms ) {
  44551. let snippet = null;
  44552. let group = false;
  44553. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  44554. const texture = uniform.node.value;
  44555. let typePrefix = '';
  44556. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  44557. if ( texture.type === UnsignedIntType ) {
  44558. typePrefix = 'u';
  44559. } else if ( texture.type === IntType ) {
  44560. typePrefix = 'i';
  44561. }
  44562. }
  44563. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  44564. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  44565. } else if ( texture.compareFunction ) {
  44566. if ( texture.isArrayTexture === true ) {
  44567. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  44568. } else {
  44569. snippet = `sampler2DShadow ${ uniform.name };`;
  44570. }
  44571. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44572. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  44573. } else {
  44574. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  44575. }
  44576. } else if ( uniform.type === 'cubeTexture' ) {
  44577. snippet = `samplerCube ${ uniform.name };`;
  44578. } else if ( uniform.type === 'cubeDepthTexture' ) {
  44579. const texture = uniform.node.value;
  44580. if ( texture.compareFunction ) {
  44581. snippet = `samplerCubeShadow ${ uniform.name };`;
  44582. } else {
  44583. snippet = `samplerCube ${ uniform.name };`;
  44584. }
  44585. } else if ( uniform.type === 'buffer' ) {
  44586. const bufferNode = uniform.node;
  44587. const bufferType = this.getType( bufferNode.bufferType );
  44588. const bufferCount = bufferNode.bufferCount;
  44589. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  44590. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  44591. } else {
  44592. const groupName = uniform.groupNode.name;
  44593. // Check if this group has already been processed
  44594. if ( uniformGroups[ groupName ] === undefined ) {
  44595. // Get the shared uniform group that contains uniforms from all stages
  44596. const sharedUniformGroup = this.uniformGroups[ groupName ];
  44597. if ( sharedUniformGroup !== undefined ) {
  44598. // Generate snippets for ALL uniforms in this shared group
  44599. const snippets = [];
  44600. for ( const sharedUniform of sharedUniformGroup.uniforms ) {
  44601. const type = sharedUniform.getType();
  44602. const vectorType = this.getVectorType( type );
  44603. const precision = sharedUniform.nodeUniform.node.precision;
  44604. let uniformSnippet = `${ vectorType } ${ sharedUniform.name };`;
  44605. if ( precision !== null ) {
  44606. uniformSnippet = precisionLib[ precision ] + ' ' + uniformSnippet;
  44607. }
  44608. snippets.push( '\t' + uniformSnippet );
  44609. }
  44610. uniformGroups[ groupName ] = snippets;
  44611. }
  44612. }
  44613. group = true;
  44614. }
  44615. if ( ! group ) {
  44616. const precision = uniform.node.precision;
  44617. if ( precision !== null ) {
  44618. snippet = precisionLib[ precision ] + ' ' + snippet;
  44619. }
  44620. snippet = 'uniform ' + snippet;
  44621. bindingSnippets.push( snippet );
  44622. }
  44623. }
  44624. let output = '';
  44625. for ( const name in uniformGroups ) {
  44626. const groupSnippets = uniformGroups[ name ];
  44627. output += this._getGLSLUniformStruct( name, groupSnippets.join( '\n' ) ) + '\n';
  44628. }
  44629. output += bindingSnippets.join( '\n' );
  44630. return output;
  44631. }
  44632. /**
  44633. * Returns the type for a given buffer attribute.
  44634. *
  44635. * @param {BufferAttribute} attribute - The buffer attribute.
  44636. * @return {string} The type.
  44637. */
  44638. getTypeFromAttribute( attribute ) {
  44639. let nodeType = super.getTypeFromAttribute( attribute );
  44640. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  44641. let dataAttribute = attribute;
  44642. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  44643. const array = dataAttribute.array;
  44644. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  44645. nodeType = nodeType.slice( 1 );
  44646. }
  44647. }
  44648. return nodeType;
  44649. }
  44650. /**
  44651. * Returns the shader attributes of the given shader stage as a GLSL string.
  44652. *
  44653. * @param {string} shaderStage - The shader stage.
  44654. * @return {string} The GLSL snippet that defines the shader attributes.
  44655. */
  44656. getAttributes( shaderStage ) {
  44657. let snippet = '';
  44658. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44659. const attributes = this.getAttributesArray();
  44660. let location = 0;
  44661. for ( const attribute of attributes ) {
  44662. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  44663. }
  44664. }
  44665. return snippet;
  44666. }
  44667. /**
  44668. * Returns the members of the given struct type node as a GLSL string.
  44669. *
  44670. * @param {StructTypeNode} struct - The struct type node.
  44671. * @return {string} The GLSL snippet that defines the struct members.
  44672. */
  44673. getStructMembers( struct ) {
  44674. const snippets = [];
  44675. for ( const member of struct.members ) {
  44676. snippets.push( `\t${ member.type } ${ member.name };` );
  44677. }
  44678. return snippets.join( '\n' );
  44679. }
  44680. /**
  44681. * Returns the structs of the given shader stage as a GLSL string.
  44682. *
  44683. * @param {string} shaderStage - The shader stage.
  44684. * @return {string} The GLSL snippet that defines the structs.
  44685. */
  44686. getStructs( shaderStage ) {
  44687. const snippets = [];
  44688. const structs = this.structs[ shaderStage ];
  44689. const outputSnippet = [];
  44690. for ( const struct of structs ) {
  44691. if ( struct.output ) {
  44692. for ( const member of struct.members ) {
  44693. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  44694. }
  44695. } else {
  44696. let snippet = 'struct ' + struct.name + ' {\n';
  44697. snippet += this.getStructMembers( struct );
  44698. snippet += '\n};\n';
  44699. snippets.push( snippet );
  44700. }
  44701. }
  44702. if ( outputSnippet.length === 0 ) {
  44703. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  44704. }
  44705. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  44706. }
  44707. /**
  44708. * Returns the varyings of the given shader stage as a GLSL string.
  44709. *
  44710. * @param {string} shaderStage - The shader stage.
  44711. * @return {string} The GLSL snippet that defines the varyings.
  44712. */
  44713. getVaryings( shaderStage ) {
  44714. let snippet = '';
  44715. const varyings = this.varyings;
  44716. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44717. for ( const varying of varyings ) {
  44718. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  44719. const type = this.getType( varying.type );
  44720. if ( varying.needsInterpolation ) {
  44721. if ( varying.interpolationType ) {
  44722. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  44723. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  44724. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  44725. } else {
  44726. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  44727. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  44728. }
  44729. } else {
  44730. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  44731. }
  44732. }
  44733. } else if ( shaderStage === 'fragment' ) {
  44734. for ( const varying of varyings ) {
  44735. if ( varying.needsInterpolation ) {
  44736. const type = this.getType( varying.type );
  44737. if ( varying.interpolationType ) {
  44738. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  44739. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  44740. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  44741. } else {
  44742. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  44743. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  44744. }
  44745. }
  44746. }
  44747. }
  44748. for ( const builtin of this.builtins[ shaderStage ] ) {
  44749. snippet += `${builtin};\n`;
  44750. }
  44751. return snippet;
  44752. }
  44753. /**
  44754. * Returns the vertex index builtin.
  44755. *
  44756. * @return {string} The vertex index.
  44757. */
  44758. getVertexIndex() {
  44759. return 'uint( gl_VertexID )';
  44760. }
  44761. /**
  44762. * Contextually returns either the vertex stage instance index builtin
  44763. * or the linearized index of an compute invocation within a grid of workgroups.
  44764. *
  44765. * @return {string} The instance index.
  44766. */
  44767. getInstanceIndex() {
  44768. return 'uint( gl_InstanceID )';
  44769. }
  44770. /**
  44771. * Returns a builtin representing the index of an invocation within its workgroup.
  44772. *
  44773. * @return {string} The invocation local index.
  44774. */
  44775. getInvocationLocalIndex() {
  44776. const workgroupSize = this.object.workgroupSize;
  44777. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  44778. return `uint( gl_InstanceID ) % ${size}u`;
  44779. }
  44780. /**
  44781. * Returns a builtin representing the size of a subgroup within the current shader.
  44782. */
  44783. getSubgroupSize() {
  44784. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  44785. }
  44786. /**
  44787. * Returns a builtin representing the index of an invocation within its subgroup.
  44788. */
  44789. getInvocationSubgroupIndex() {
  44790. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  44791. }
  44792. /**
  44793. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  44794. */
  44795. getSubgroupIndex() {
  44796. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  44797. }
  44798. /**
  44799. * Returns the draw index builtin.
  44800. *
  44801. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  44802. */
  44803. getDrawIndex() {
  44804. const extensions = this.renderer.backend.extensions;
  44805. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  44806. return 'uint( gl_DrawID )';
  44807. }
  44808. return null;
  44809. }
  44810. /**
  44811. * Returns the front facing builtin.
  44812. *
  44813. * @return {string} The front facing builtin.
  44814. */
  44815. getFrontFacing() {
  44816. return 'gl_FrontFacing';
  44817. }
  44818. /**
  44819. * Returns the frag coord builtin.
  44820. *
  44821. * @return {string} The frag coord builtin.
  44822. */
  44823. getFragCoord() {
  44824. return 'gl_FragCoord.xy';
  44825. }
  44826. /**
  44827. * Returns the frag depth builtin.
  44828. *
  44829. * @return {string} The frag depth builtin.
  44830. */
  44831. getFragDepth() {
  44832. return 'gl_FragDepth';
  44833. }
  44834. /**
  44835. * Enables the given extension.
  44836. *
  44837. * @param {string} name - The extension name.
  44838. * @param {string} behavior - The extension behavior.
  44839. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  44840. */
  44841. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  44842. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  44843. if ( map.has( name ) === false ) {
  44844. map.set( name, {
  44845. name,
  44846. behavior
  44847. } );
  44848. }
  44849. }
  44850. /**
  44851. * Returns the enabled extensions of the given shader stage as a GLSL string.
  44852. *
  44853. * @param {string} shaderStage - The shader stage.
  44854. * @return {string} The GLSL snippet that defines the enabled extensions.
  44855. */
  44856. getExtensions( shaderStage ) {
  44857. const snippets = [];
  44858. if ( shaderStage === 'vertex' ) {
  44859. const ext = this.renderer.backend.extensions;
  44860. const isBatchedMesh = this.object.isBatchedMesh;
  44861. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  44862. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  44863. }
  44864. }
  44865. const extensions = this.extensions[ shaderStage ];
  44866. if ( extensions !== undefined ) {
  44867. for ( const { name, behavior } of extensions.values() ) {
  44868. snippets.push( `#extension ${name} : ${behavior}` );
  44869. }
  44870. }
  44871. return snippets.join( '\n' );
  44872. }
  44873. /**
  44874. * Returns the clip distances builtin.
  44875. *
  44876. * @return {string} The clip distances builtin.
  44877. */
  44878. getClipDistance() {
  44879. return 'gl_ClipDistance';
  44880. }
  44881. /**
  44882. * Whether the requested feature is available or not.
  44883. *
  44884. * @param {string} name - The requested feature.
  44885. * @return {boolean} Whether the requested feature is supported or not.
  44886. */
  44887. isAvailable( name ) {
  44888. let result = supports$1[ name ];
  44889. if ( result === undefined ) {
  44890. let extensionName;
  44891. result = false;
  44892. switch ( name ) {
  44893. case 'float32Filterable':
  44894. extensionName = 'OES_texture_float_linear';
  44895. break;
  44896. case 'clipDistance':
  44897. extensionName = 'WEBGL_clip_cull_distance';
  44898. break;
  44899. }
  44900. if ( extensionName !== undefined ) {
  44901. const extensions = this.renderer.backend.extensions;
  44902. if ( extensions.has( extensionName ) ) {
  44903. extensions.get( extensionName );
  44904. result = true;
  44905. }
  44906. }
  44907. supports$1[ name ] = result;
  44908. }
  44909. return result;
  44910. }
  44911. /**
  44912. * Whether to flip texture data along its vertical axis or not.
  44913. *
  44914. * @return {boolean} Returns always `true` in context of GLSL.
  44915. */
  44916. isFlipY() {
  44917. return true;
  44918. }
  44919. /**
  44920. * Returns the maximum number of bytes available for uniform buffers.
  44921. *
  44922. * @return {number} The maximum number of bytes available for uniform buffers.
  44923. */
  44924. getUniformBufferLimit() {
  44925. const gl = this.renderer.backend.gl;
  44926. return gl.getParameter( gl.MAX_UNIFORM_BLOCK_SIZE );
  44927. }
  44928. /**
  44929. * Enables hardware clipping.
  44930. *
  44931. * @param {string} planeCount - The clipping plane count.
  44932. */
  44933. enableHardwareClipping( planeCount ) {
  44934. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  44935. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  44936. }
  44937. /**
  44938. * Enables multiview.
  44939. */
  44940. enableMultiview() {
  44941. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  44942. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  44943. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  44944. }
  44945. /**
  44946. * Registers a transform in context of Transform Feedback.
  44947. *
  44948. * @param {string} varyingName - The varying name.
  44949. * @param {AttributeNode} attributeNode - The attribute node.
  44950. */
  44951. registerTransform( varyingName, attributeNode ) {
  44952. this.transforms.push( { varyingName, attributeNode } );
  44953. }
  44954. /**
  44955. * Returns the transforms of the given shader stage as a GLSL string.
  44956. *
  44957. * @param {string} shaderStage - The shader stage.
  44958. * @return {string} The GLSL snippet that defines the transforms.
  44959. */
  44960. getTransforms( /* shaderStage */ ) {
  44961. const transforms = this.transforms;
  44962. let snippet = '';
  44963. for ( let i = 0; i < transforms.length; i ++ ) {
  44964. const transform = transforms[ i ];
  44965. const attributeName = this.getPropertyName( transform.attributeNode );
  44966. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  44967. }
  44968. return snippet;
  44969. }
  44970. /**
  44971. * Returns a GLSL struct based on the given name and variables.
  44972. *
  44973. * @private
  44974. * @param {string} name - The struct name.
  44975. * @param {string} vars - The struct variables.
  44976. * @return {string} The GLSL snippet representing a struct.
  44977. */
  44978. _getGLSLUniformStruct( name, vars ) {
  44979. return `
  44980. layout( std140 ) uniform ${name} {
  44981. ${vars}
  44982. };`;
  44983. }
  44984. /**
  44985. * Returns a GLSL vertex shader based on the given shader data.
  44986. *
  44987. * @private
  44988. * @param {Object} shaderData - The shader data.
  44989. * @return {string} The vertex shader.
  44990. */
  44991. _getGLSLVertexCode( shaderData ) {
  44992. return `#version 300 es
  44993. ${ this.getSignature() }
  44994. // extensions
  44995. ${shaderData.extensions}
  44996. // precision
  44997. ${ defaultPrecisions }
  44998. // uniforms
  44999. ${shaderData.uniforms}
  45000. // varyings
  45001. ${shaderData.varyings}
  45002. // attributes
  45003. ${shaderData.attributes}
  45004. // codes
  45005. ${shaderData.codes}
  45006. void main() {
  45007. // vars
  45008. ${shaderData.vars}
  45009. // transforms
  45010. ${shaderData.transforms}
  45011. // flow
  45012. ${shaderData.flow}
  45013. gl_PointSize = 1.0;
  45014. }
  45015. `;
  45016. }
  45017. /**
  45018. * Returns a GLSL fragment shader based on the given shader data.
  45019. *
  45020. * @private
  45021. * @param {Object} shaderData - The shader data.
  45022. * @return {string} The vertex shader.
  45023. */
  45024. _getGLSLFragmentCode( shaderData ) {
  45025. return `#version 300 es
  45026. ${ this.getSignature() }
  45027. // extensions
  45028. ${shaderData.extensions}
  45029. // precision
  45030. ${ defaultPrecisions }
  45031. // structs
  45032. ${shaderData.structs}
  45033. // uniforms
  45034. ${shaderData.uniforms}
  45035. // varyings
  45036. ${shaderData.varyings}
  45037. // codes
  45038. ${shaderData.codes}
  45039. void main() {
  45040. // vars
  45041. ${shaderData.vars}
  45042. // flow
  45043. ${shaderData.flow}
  45044. }
  45045. `;
  45046. }
  45047. /**
  45048. * Controls the code build of the shader stages.
  45049. */
  45050. buildCode() {
  45051. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  45052. this.sortBindingGroups();
  45053. for ( const shaderStage in shadersData ) {
  45054. let flow = '// code\n\n';
  45055. flow += this.flowCode[ shaderStage ];
  45056. const flowNodes = this.flowNodes[ shaderStage ];
  45057. const mainNode = flowNodes[ flowNodes.length - 1 ];
  45058. for ( const node of flowNodes ) {
  45059. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  45060. const slotName = node.name;
  45061. if ( slotName ) {
  45062. if ( flow.length > 0 ) flow += '\n';
  45063. flow += `\t// flow -> ${ slotName }\n\t`;
  45064. }
  45065. flow += `${ flowSlotData.code }\n\t`;
  45066. if ( node === mainNode && shaderStage !== 'compute' ) {
  45067. flow += '// result\n\t';
  45068. if ( shaderStage === 'vertex' ) {
  45069. flow += 'gl_Position = ';
  45070. flow += `${ flowSlotData.result };`;
  45071. } else if ( shaderStage === 'fragment' ) {
  45072. if ( ! node.outputNode.isOutputStructNode ) {
  45073. flow += 'fragColor = ';
  45074. flow += `${ flowSlotData.result };`;
  45075. }
  45076. }
  45077. }
  45078. }
  45079. const stageData = shadersData[ shaderStage ];
  45080. stageData.extensions = this.getExtensions( shaderStage );
  45081. stageData.uniforms = this.getUniforms( shaderStage );
  45082. stageData.attributes = this.getAttributes( shaderStage );
  45083. stageData.varyings = this.getVaryings( shaderStage );
  45084. stageData.vars = this.getVars( shaderStage );
  45085. stageData.structs = this.getStructs( shaderStage );
  45086. stageData.codes = this.getCodes( shaderStage );
  45087. stageData.transforms = this.getTransforms( shaderStage );
  45088. stageData.flow = flow;
  45089. }
  45090. if ( this.material !== null ) {
  45091. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  45092. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  45093. } else {
  45094. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  45095. }
  45096. }
  45097. /**
  45098. * This method is one of the more important ones since it's responsible
  45099. * for generating a matching binding instance for the given uniform node.
  45100. *
  45101. * These bindings are later used in the renderer to create bind groups
  45102. * and layouts.
  45103. *
  45104. * @param {UniformNode} node - The uniform node.
  45105. * @param {string} type - The node data type.
  45106. * @param {string} shaderStage - The shader stage.
  45107. * @param {?string} [name=null] - An optional uniform name.
  45108. * @return {NodeUniform} The node uniform object.
  45109. */
  45110. getUniformFromNode( node, type, shaderStage, name = null ) {
  45111. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  45112. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  45113. let uniformGPU = nodeData.uniformGPU;
  45114. if ( uniformGPU === undefined ) {
  45115. const group = node.groupNode;
  45116. const groupName = group.name;
  45117. const bindings = this.getBindGroupArray( groupName, shaderStage );
  45118. if ( type === 'texture' ) {
  45119. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  45120. bindings.push( uniformGPU );
  45121. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  45122. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  45123. bindings.push( uniformGPU );
  45124. } else if ( type === 'texture3D' ) {
  45125. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  45126. bindings.push( uniformGPU );
  45127. } else if ( type === 'buffer' ) {
  45128. uniformNode.name = `buffer${ node.id }`;
  45129. const sharedData = this.getSharedDataFromNode( node );
  45130. let buffer = sharedData.buffer;
  45131. if ( buffer === undefined ) {
  45132. node.name = `NodeBuffer_${ node.id }`;
  45133. buffer = new NodeUniformBuffer( node, group );
  45134. buffer.name = node.name;
  45135. sharedData.buffer = buffer;
  45136. }
  45137. bindings.push( buffer );
  45138. uniformGPU = buffer;
  45139. } else {
  45140. let uniformsGroup = this.uniformGroups[ groupName ];
  45141. if ( uniformsGroup === undefined ) {
  45142. uniformsGroup = new NodeUniformsGroup( groupName, group );
  45143. this.uniformGroups[ groupName ] = uniformsGroup;
  45144. bindings.push( uniformsGroup );
  45145. } else {
  45146. // Add to bindings for this stage if not already present
  45147. if ( bindings.indexOf( uniformsGroup ) === -1 ) {
  45148. bindings.push( uniformsGroup );
  45149. }
  45150. }
  45151. uniformGPU = this.getNodeUniform( uniformNode, type );
  45152. // Only add uniform if not already present in the group (check by name to avoid duplicates across stages)
  45153. const uniformName = uniformGPU.name;
  45154. const alreadyExists = uniformsGroup.uniforms.some( u => u.name === uniformName );
  45155. if ( ! alreadyExists ) {
  45156. uniformsGroup.addUniform( uniformGPU );
  45157. }
  45158. }
  45159. nodeData.uniformGPU = uniformGPU;
  45160. }
  45161. return uniformNode;
  45162. }
  45163. }
  45164. let _vector2 = null;
  45165. let _color4 = null;
  45166. /**
  45167. * Most of the rendering related logic is implemented in the
  45168. * {@link Renderer} module and related management components.
  45169. * Sometimes it is required though to execute commands which are
  45170. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  45171. * This abstract base class defines an interface that encapsulates
  45172. * all backend-related logic. Derived classes for each backend must
  45173. * implement the interface.
  45174. *
  45175. * @abstract
  45176. * @private
  45177. */
  45178. class Backend {
  45179. /**
  45180. * Constructs a new backend.
  45181. *
  45182. * @param {Object} parameters - An object holding parameters for the backend.
  45183. */
  45184. constructor( parameters = {} ) {
  45185. /**
  45186. * The parameters of the backend.
  45187. *
  45188. * @type {Object}
  45189. */
  45190. this.parameters = Object.assign( {}, parameters );
  45191. /**
  45192. * This weak map holds backend-specific data of objects
  45193. * like textures, attributes or render targets.
  45194. *
  45195. * @type {WeakMap<Object, Object>}
  45196. */
  45197. this.data = new WeakMap();
  45198. /**
  45199. * A reference to the renderer.
  45200. *
  45201. * @type {?Renderer}
  45202. * @default null
  45203. */
  45204. this.renderer = null;
  45205. /**
  45206. * A reference to the canvas element the renderer is drawing to.
  45207. *
  45208. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  45209. * @default null
  45210. */
  45211. this.domElement = null;
  45212. /**
  45213. * A reference to the timestamp query pool.
  45214. *
  45215. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  45216. */
  45217. this.timestampQueryPool = {
  45218. [ TimestampQuery.RENDER ]: null,
  45219. [ TimestampQuery.COMPUTE ]: null
  45220. };
  45221. /**
  45222. * Whether to track timestamps with a Timestamp Query API or not.
  45223. *
  45224. * @type {boolean}
  45225. * @default false
  45226. */
  45227. this.trackTimestamp = ( parameters.trackTimestamp === true );
  45228. }
  45229. /**
  45230. * Initializes the backend so it is ready for usage. Concrete backends
  45231. * are supposed to implement their rendering context creation and related
  45232. * operations in this method.
  45233. *
  45234. * @async
  45235. * @param {Renderer} renderer - The renderer.
  45236. * @return {Promise} A Promise that resolves when the backend has been initialized.
  45237. */
  45238. async init( renderer ) {
  45239. this.renderer = renderer;
  45240. }
  45241. /**
  45242. * The coordinate system of the backend.
  45243. *
  45244. * @abstract
  45245. * @type {number}
  45246. * @readonly
  45247. */
  45248. get coordinateSystem() {}
  45249. // render context
  45250. /**
  45251. * This method is executed at the beginning of a render call and
  45252. * can be used by the backend to prepare the state for upcoming
  45253. * draw calls.
  45254. *
  45255. * @abstract
  45256. * @param {RenderContext} renderContext - The render context.
  45257. */
  45258. beginRender( /*renderContext*/ ) {}
  45259. /**
  45260. * This method is executed at the end of a render call and
  45261. * can be used by the backend to finalize work after draw
  45262. * calls.
  45263. *
  45264. * @abstract
  45265. * @param {RenderContext} renderContext - The render context.
  45266. */
  45267. finishRender( /*renderContext*/ ) {}
  45268. /**
  45269. * This method is executed at the beginning of a compute call and
  45270. * can be used by the backend to prepare the state for upcoming
  45271. * compute tasks.
  45272. *
  45273. * @abstract
  45274. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45275. */
  45276. beginCompute( /*computeGroup*/ ) {}
  45277. /**
  45278. * This method is executed at the end of a compute call and
  45279. * can be used by the backend to finalize work after compute
  45280. * tasks.
  45281. *
  45282. * @abstract
  45283. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45284. */
  45285. finishCompute( /*computeGroup*/ ) {}
  45286. // render object
  45287. /**
  45288. * Executes a draw command for the given render object.
  45289. *
  45290. * @abstract
  45291. * @param {RenderObject} renderObject - The render object to draw.
  45292. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  45293. */
  45294. draw( /*renderObject, info*/ ) { }
  45295. // compute node
  45296. /**
  45297. * Executes a compute command for the given compute node.
  45298. *
  45299. * @abstract
  45300. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  45301. * @param {Node} computeNode - The compute node.
  45302. * @param {Array<BindGroup>} bindings - The bindings.
  45303. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45304. */
  45305. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  45306. // program
  45307. /**
  45308. * Creates a shader program from the given programmable stage.
  45309. *
  45310. * @abstract
  45311. * @param {ProgrammableStage} program - The programmable stage.
  45312. */
  45313. createProgram( /*program*/ ) { }
  45314. /**
  45315. * Destroys the shader program of the given programmable stage.
  45316. *
  45317. * @abstract
  45318. * @param {ProgrammableStage} program - The programmable stage.
  45319. */
  45320. destroyProgram( /*program*/ ) { }
  45321. // bindings
  45322. /**
  45323. * Creates bindings from the given bind group definition.
  45324. *
  45325. * @abstract
  45326. * @param {BindGroup} bindGroup - The bind group.
  45327. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45328. * @param {number} cacheIndex - The cache index.
  45329. * @param {number} version - The version.
  45330. */
  45331. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45332. /**
  45333. * Updates the given bind group definition.
  45334. *
  45335. * @abstract
  45336. * @param {BindGroup} bindGroup - The bind group.
  45337. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45338. * @param {number} cacheIndex - The cache index.
  45339. * @param {number} version - The version.
  45340. */
  45341. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45342. /**
  45343. * Updates a buffer binding.
  45344. *
  45345. * @abstract
  45346. * @param {Buffer} binding - The buffer binding to update.
  45347. */
  45348. updateBinding( /*binding*/ ) { }
  45349. // pipeline
  45350. /**
  45351. * Creates a render pipeline for the given render object.
  45352. *
  45353. * @abstract
  45354. * @param {RenderObject} renderObject - The render object.
  45355. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  45356. */
  45357. createRenderPipeline( /*renderObject, promises*/ ) { }
  45358. /**
  45359. * Creates a compute pipeline for the given compute node.
  45360. *
  45361. * @abstract
  45362. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45363. * @param {Array<BindGroup>} bindings - The bindings.
  45364. */
  45365. createComputePipeline( /*computePipeline, bindings*/ ) { }
  45366. // cache key
  45367. /**
  45368. * Returns `true` if the render pipeline requires an update.
  45369. *
  45370. * @abstract
  45371. * @param {RenderObject} renderObject - The render object.
  45372. * @return {boolean} Whether the render pipeline requires an update or not.
  45373. */
  45374. needsRenderUpdate( /*renderObject*/ ) { }
  45375. /**
  45376. * Returns a cache key that is used to identify render pipelines.
  45377. *
  45378. * @abstract
  45379. * @param {RenderObject} renderObject - The render object.
  45380. * @return {string} The cache key.
  45381. */
  45382. getRenderCacheKey( /*renderObject*/ ) { }
  45383. // node builder
  45384. /**
  45385. * Returns a node builder for the given render object.
  45386. *
  45387. * @abstract
  45388. * @param {RenderObject} renderObject - The render object.
  45389. * @param {Renderer} renderer - The renderer.
  45390. * @return {NodeBuilder} The node builder.
  45391. */
  45392. createNodeBuilder( /*renderObject, renderer*/ ) { }
  45393. // textures
  45394. /**
  45395. * Updates a GPU sampler for the given texture.
  45396. *
  45397. * @abstract
  45398. * @param {Texture} texture - The texture to update the sampler for.
  45399. * @return {string} The current sampler key.
  45400. */
  45401. updateSampler( /*texture*/ ) { }
  45402. /**
  45403. * Creates a default texture for the given texture that can be used
  45404. * as a placeholder until the actual texture is ready for usage.
  45405. *
  45406. * @abstract
  45407. * @param {Texture} texture - The texture to create a default texture for.
  45408. */
  45409. createDefaultTexture( /*texture*/ ) { }
  45410. /**
  45411. * Defines a texture on the GPU for the given texture object.
  45412. *
  45413. * @abstract
  45414. * @param {Texture} texture - The texture.
  45415. * @param {Object} [options={}] - Optional configuration parameter.
  45416. */
  45417. createTexture( /*texture, options={}*/ ) { }
  45418. /**
  45419. * Uploads the updated texture data to the GPU.
  45420. *
  45421. * @abstract
  45422. * @param {Texture} texture - The texture.
  45423. * @param {Object} [options={}] - Optional configuration parameter.
  45424. */
  45425. updateTexture( /*texture, options = {}*/ ) { }
  45426. /**
  45427. * Generates mipmaps for the given texture.
  45428. *
  45429. * @abstract
  45430. * @param {Texture} texture - The texture.
  45431. */
  45432. generateMipmaps( /*texture*/ ) { }
  45433. /**
  45434. * Destroys the GPU data for the given texture object.
  45435. *
  45436. * @abstract
  45437. * @param {Texture} texture - The texture.
  45438. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  45439. */
  45440. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  45441. /**
  45442. * Returns texture data as a typed array.
  45443. *
  45444. * @abstract
  45445. * @async
  45446. * @param {Texture} texture - The texture to copy.
  45447. * @param {number} x - The x coordinate of the copy origin.
  45448. * @param {number} y - The y coordinate of the copy origin.
  45449. * @param {number} width - The width of the copy.
  45450. * @param {number} height - The height of the copy.
  45451. * @param {number} faceIndex - The face index.
  45452. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45453. */
  45454. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  45455. /**
  45456. * Copies data of the given source texture to the given destination texture.
  45457. *
  45458. * @abstract
  45459. * @param {Texture} srcTexture - The source texture.
  45460. * @param {Texture} dstTexture - The destination texture.
  45461. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45462. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45463. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45464. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45465. */
  45466. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  45467. /**
  45468. * Copies the current bound framebuffer to the given texture.
  45469. *
  45470. * @abstract
  45471. * @param {Texture} texture - The destination texture.
  45472. * @param {RenderContext} renderContext - The render context.
  45473. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  45474. */
  45475. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  45476. // attributes
  45477. /**
  45478. * Creates the GPU buffer of a shader attribute.
  45479. *
  45480. * @abstract
  45481. * @param {BufferAttribute} attribute - The buffer attribute.
  45482. */
  45483. createAttribute( /*attribute*/ ) { }
  45484. /**
  45485. * Creates the GPU buffer of an indexed shader attribute.
  45486. *
  45487. * @abstract
  45488. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  45489. */
  45490. createIndexAttribute( /*attribute*/ ) { }
  45491. /**
  45492. * Creates the GPU buffer of a storage attribute.
  45493. *
  45494. * @abstract
  45495. * @param {BufferAttribute} attribute - The buffer attribute.
  45496. */
  45497. createStorageAttribute( /*attribute*/ ) { }
  45498. /**
  45499. * Updates the GPU buffer of a shader attribute.
  45500. *
  45501. * @abstract
  45502. * @param {BufferAttribute} attribute - The buffer attribute to update.
  45503. */
  45504. updateAttribute( /*attribute*/ ) { }
  45505. /**
  45506. * Destroys the GPU buffer of a shader attribute.
  45507. *
  45508. * @abstract
  45509. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  45510. */
  45511. destroyAttribute( /*attribute*/ ) { }
  45512. // canvas
  45513. /**
  45514. * Returns the backend's rendering context.
  45515. *
  45516. * @abstract
  45517. * @return {Object} The rendering context.
  45518. */
  45519. getContext() { }
  45520. /**
  45521. * Backends can use this method if they have to run
  45522. * logic when the renderer gets resized.
  45523. *
  45524. * @abstract
  45525. */
  45526. updateSize() { }
  45527. /**
  45528. * Updates the viewport with the values from the given render context.
  45529. *
  45530. * @abstract
  45531. * @param {RenderContext} renderContext - The render context.
  45532. */
  45533. updateViewport( /*renderContext*/ ) {}
  45534. // utils
  45535. /**
  45536. * Updates a unique identifier for the given render context that can be used
  45537. * to allocate resources like occlusion queries or timestamp queries.
  45538. *
  45539. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45540. */
  45541. updateTimeStampUID( abstractRenderContext ) {
  45542. const contextData = this.get( abstractRenderContext );
  45543. const frame = this.renderer.info.frame;
  45544. let prefix;
  45545. if ( abstractRenderContext.isComputeNode === true ) {
  45546. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  45547. } else {
  45548. prefix = 'r:' + this.renderer.info.render.frameCalls;
  45549. }
  45550. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  45551. }
  45552. /**
  45553. * Returns a unique identifier for the given render context that can be used
  45554. * to allocate resources like occlusion queries or timestamp queries.
  45555. *
  45556. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45557. * @return {string} The unique identifier.
  45558. */
  45559. getTimestampUID( abstractRenderContext ) {
  45560. return this.get( abstractRenderContext ).timestampUID;
  45561. }
  45562. /**
  45563. * Returns all timestamp frames for the given type.
  45564. *
  45565. * @param {string} type - The type of the time stamp.
  45566. * @return {Array<number>} The timestamp frames.
  45567. */
  45568. getTimestampFrames( type ) {
  45569. const queryPool = this.timestampQueryPool[ type ];
  45570. return queryPool ? queryPool.getTimestampFrames() : [];
  45571. }
  45572. /**
  45573. * Returns the query pool for the given uid.
  45574. *
  45575. * @param {string} uid - The unique identifier.
  45576. * @return {TimestampQueryPool} The query pool.
  45577. */
  45578. _getQueryPool( uid ) {
  45579. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  45580. const queryPool = this.timestampQueryPool[ type ];
  45581. return queryPool;
  45582. }
  45583. /**
  45584. * Returns the timestamp for the given uid.
  45585. *
  45586. * @param {string} uid - The unique identifier.
  45587. * @return {number} The timestamp.
  45588. */
  45589. getTimestamp( uid ) {
  45590. const queryPool = this._getQueryPool( uid );
  45591. return queryPool.getTimestamp( uid );
  45592. }
  45593. /**
  45594. * Returns `true` if a timestamp for the given uid is available.
  45595. *
  45596. * @param {string} uid - The unique identifier.
  45597. * @return {boolean} Whether the timestamp is available or not.
  45598. */
  45599. hasTimestamp( uid ) {
  45600. const queryPool = this._getQueryPool( uid );
  45601. return queryPool.hasTimestamp( uid );
  45602. }
  45603. /**
  45604. * Returns `true` if the given 3D object is fully occluded by other
  45605. * 3D objects in the scene. Backends must implement this method by using
  45606. * a Occlusion Query API.
  45607. *
  45608. * @abstract
  45609. * @param {RenderContext} renderContext - The render context.
  45610. * @param {Object3D} object - The 3D object to test.
  45611. * @return {boolean} Whether the 3D object is fully occluded or not.
  45612. */
  45613. isOccluded( /*renderContext, object*/ ) {}
  45614. /**
  45615. * Resolves the time stamp for the given render context and type.
  45616. *
  45617. * @async
  45618. * @abstract
  45619. * @param {string} [type='render'] - The type of the time stamp.
  45620. * @return {Promise<number>} A Promise that resolves with the time stamp.
  45621. */
  45622. async resolveTimestampsAsync( type = 'render' ) {
  45623. if ( ! this.trackTimestamp ) {
  45624. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  45625. return;
  45626. }
  45627. const queryPool = this.timestampQueryPool[ type ];
  45628. if ( ! queryPool ) {
  45629. return;
  45630. }
  45631. const duration = await queryPool.resolveQueriesAsync();
  45632. this.renderer.info[ type ].timestamp = duration;
  45633. return duration;
  45634. }
  45635. /**
  45636. * This method performs a readback operation by moving buffer data from
  45637. * a storage buffer attribute from the GPU to the CPU.
  45638. *
  45639. * @async
  45640. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45641. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45642. */
  45643. async getArrayBufferAsync( /* attribute */ ) {}
  45644. /**
  45645. * Checks if the given feature is supported by the backend.
  45646. *
  45647. * @async
  45648. * @abstract
  45649. * @param {string} name - The feature's name.
  45650. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  45651. */
  45652. async hasFeatureAsync( /*name*/ ) { }
  45653. /**
  45654. * Checks if the given feature is supported by the backend.
  45655. *
  45656. * @abstract
  45657. * @param {string} name - The feature's name.
  45658. * @return {boolean} Whether the feature is supported or not.
  45659. */
  45660. hasFeature( /*name*/ ) {}
  45661. /**
  45662. * Returns the maximum anisotropy texture filtering value.
  45663. *
  45664. * @abstract
  45665. * @return {number} The maximum anisotropy texture filtering value.
  45666. */
  45667. getMaxAnisotropy() {}
  45668. /**
  45669. * Returns the drawing buffer size.
  45670. *
  45671. * @return {Vector2} The drawing buffer size.
  45672. */
  45673. getDrawingBufferSize() {
  45674. _vector2 = _vector2 || new Vector2();
  45675. return this.renderer.getDrawingBufferSize( _vector2 );
  45676. }
  45677. /**
  45678. * Defines the scissor test.
  45679. *
  45680. * @abstract
  45681. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  45682. */
  45683. setScissorTest( /*boolean*/ ) { }
  45684. /**
  45685. * Returns the clear color and alpha into a single
  45686. * color object.
  45687. *
  45688. * @return {Color4} The clear color.
  45689. */
  45690. getClearColor() {
  45691. const renderer = this.renderer;
  45692. _color4 = _color4 || new Color4();
  45693. renderer.getClearColor( _color4 );
  45694. _color4.getRGB( _color4 );
  45695. return _color4;
  45696. }
  45697. /**
  45698. * Returns the DOM element. If no DOM element exists, the backend
  45699. * creates a new one.
  45700. *
  45701. * @return {HTMLCanvasElement} The DOM element.
  45702. */
  45703. getDomElement() {
  45704. let domElement = this.domElement;
  45705. if ( domElement === null ) {
  45706. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  45707. // OffscreenCanvas does not have setAttribute, see #22811
  45708. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  45709. this.domElement = domElement;
  45710. }
  45711. return domElement;
  45712. }
  45713. /**
  45714. * Checks if the backend has the given compatibility.
  45715. *
  45716. * @abstract
  45717. * @param {string} name - The compatibility.
  45718. * @return {boolean} Whether the backend has the given compatibility or not.
  45719. */
  45720. hasCompatibility( /*name*/ ) {
  45721. return false;
  45722. }
  45723. /**
  45724. * Initializes the render target defined in the given render context.
  45725. *
  45726. * @abstract
  45727. * @param {RenderContext} renderContext - The render context.
  45728. */
  45729. initRenderTarget( /*renderContext*/ ) {}
  45730. /**
  45731. * Sets a dictionary for the given object into the
  45732. * internal data structure.
  45733. *
  45734. * @param {Object} object - The object.
  45735. * @param {Object} value - The dictionary to set.
  45736. */
  45737. set( object, value ) {
  45738. this.data.set( object, value );
  45739. }
  45740. /**
  45741. * Returns the dictionary for the given object.
  45742. *
  45743. * @param {Object} object - The object.
  45744. * @return {Object} The object's dictionary.
  45745. */
  45746. get( object ) {
  45747. let map = this.data.get( object );
  45748. if ( map === undefined ) {
  45749. map = {};
  45750. this.data.set( object, map );
  45751. }
  45752. return map;
  45753. }
  45754. /**
  45755. * Checks if the given object has a dictionary
  45756. * with data defined.
  45757. *
  45758. * @param {Object} object - The object.
  45759. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  45760. */
  45761. has( object ) {
  45762. return this.data.has( object );
  45763. }
  45764. /**
  45765. * Deletes an object from the internal data structure.
  45766. *
  45767. * @param {Object} object - The object to delete.
  45768. */
  45769. delete( object ) {
  45770. this.data.delete( object );
  45771. }
  45772. /**
  45773. * Delete GPU data associated with a bind group.
  45774. *
  45775. * @abstract
  45776. * @param {BindGroup} bindGroup - The bind group.
  45777. */
  45778. deleteBindGroupData( /*bindGroup*/ ) { }
  45779. /**
  45780. * Frees internal resources.
  45781. *
  45782. * @abstract
  45783. */
  45784. dispose() { }
  45785. }
  45786. let _id$1 = 0;
  45787. /**
  45788. * This module is internally used in context of compute shaders.
  45789. * This type of shader is not natively supported in WebGL 2 and
  45790. * thus implemented via Transform Feedback. `DualAttributeData`
  45791. * manages the related data.
  45792. *
  45793. * @private
  45794. */
  45795. class DualAttributeData {
  45796. constructor( attributeData, dualBuffer ) {
  45797. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  45798. this.type = attributeData.type;
  45799. this.bufferType = attributeData.bufferType;
  45800. this.pbo = attributeData.pbo;
  45801. this.byteLength = attributeData.byteLength;
  45802. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  45803. this.version = attributeData.version;
  45804. this.isInteger = attributeData.isInteger;
  45805. this.activeBufferIndex = 0;
  45806. this.baseId = attributeData.id;
  45807. }
  45808. get id() {
  45809. return `${ this.baseId }|${ this.activeBufferIndex }`;
  45810. }
  45811. get bufferGPU() {
  45812. return this.buffers[ this.activeBufferIndex ];
  45813. }
  45814. get transformBuffer() {
  45815. return this.buffers[ this.activeBufferIndex ^ 1 ];
  45816. }
  45817. switchBuffers() {
  45818. this.activeBufferIndex ^= 1;
  45819. }
  45820. }
  45821. /**
  45822. * A WebGL 2 backend utility module for managing shader attributes.
  45823. *
  45824. * @private
  45825. */
  45826. class WebGLAttributeUtils {
  45827. /**
  45828. * Constructs a new utility object.
  45829. *
  45830. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45831. */
  45832. constructor( backend ) {
  45833. /**
  45834. * A reference to the WebGL 2 backend.
  45835. *
  45836. * @type {WebGLBackend}
  45837. */
  45838. this.backend = backend;
  45839. }
  45840. /**
  45841. * Creates the GPU buffer for the given buffer attribute.
  45842. *
  45843. * @param {BufferAttribute} attribute - The buffer attribute.
  45844. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  45845. */
  45846. createAttribute( attribute, bufferType ) {
  45847. const backend = this.backend;
  45848. const { gl } = backend;
  45849. const array = attribute.array;
  45850. const usage = attribute.usage || gl.STATIC_DRAW;
  45851. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45852. const bufferData = backend.get( bufferAttribute );
  45853. let bufferGPU = bufferData.bufferGPU;
  45854. if ( bufferGPU === undefined ) {
  45855. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  45856. bufferData.bufferGPU = bufferGPU;
  45857. bufferData.bufferType = bufferType;
  45858. bufferData.version = bufferAttribute.version;
  45859. }
  45860. //attribute.onUploadCallback();
  45861. let type;
  45862. if ( array instanceof Float32Array ) {
  45863. type = gl.FLOAT;
  45864. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  45865. type = gl.HALF_FLOAT;
  45866. } else if ( array instanceof Uint16Array ) {
  45867. if ( attribute.isFloat16BufferAttribute ) {
  45868. type = gl.HALF_FLOAT;
  45869. } else {
  45870. type = gl.UNSIGNED_SHORT;
  45871. }
  45872. } else if ( array instanceof Int16Array ) {
  45873. type = gl.SHORT;
  45874. } else if ( array instanceof Uint32Array ) {
  45875. type = gl.UNSIGNED_INT;
  45876. } else if ( array instanceof Int32Array ) {
  45877. type = gl.INT;
  45878. } else if ( array instanceof Int8Array ) {
  45879. type = gl.BYTE;
  45880. } else if ( array instanceof Uint8Array ) {
  45881. type = gl.UNSIGNED_BYTE;
  45882. } else if ( array instanceof Uint8ClampedArray ) {
  45883. type = gl.UNSIGNED_BYTE;
  45884. } else {
  45885. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  45886. }
  45887. let attributeData = {
  45888. bufferGPU,
  45889. bufferType,
  45890. type,
  45891. byteLength: array.byteLength,
  45892. bytesPerElement: array.BYTES_PER_ELEMENT,
  45893. version: attribute.version,
  45894. pbo: attribute.pbo,
  45895. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  45896. id: _id$1 ++
  45897. };
  45898. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  45899. // create buffer for transform feedback use
  45900. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  45901. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  45902. }
  45903. backend.set( attribute, attributeData );
  45904. }
  45905. /**
  45906. * Updates the GPU buffer of the given buffer attribute.
  45907. *
  45908. * @param {BufferAttribute} attribute - The buffer attribute.
  45909. */
  45910. updateAttribute( attribute ) {
  45911. const backend = this.backend;
  45912. const { gl } = backend;
  45913. const array = attribute.array;
  45914. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45915. const bufferData = backend.get( bufferAttribute );
  45916. const bufferType = bufferData.bufferType;
  45917. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  45918. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  45919. if ( updateRanges.length === 0 ) {
  45920. // Not using update ranges
  45921. gl.bufferSubData( bufferType, 0, array );
  45922. } else {
  45923. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  45924. const range = updateRanges[ i ];
  45925. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  45926. array, range.start, range.count );
  45927. }
  45928. bufferAttribute.clearUpdateRanges();
  45929. }
  45930. gl.bindBuffer( bufferType, null );
  45931. bufferData.version = bufferAttribute.version;
  45932. }
  45933. /**
  45934. * Destroys the GPU buffer of the given buffer attribute.
  45935. *
  45936. * @param {BufferAttribute} attribute - The buffer attribute.
  45937. */
  45938. destroyAttribute( attribute ) {
  45939. const backend = this.backend;
  45940. const { gl } = backend;
  45941. if ( attribute.isInterleavedBufferAttribute ) {
  45942. backend.delete( attribute.data );
  45943. }
  45944. const attributeData = backend.get( attribute );
  45945. gl.deleteBuffer( attributeData.bufferGPU );
  45946. backend.delete( attribute );
  45947. }
  45948. /**
  45949. * This method performs a readback operation by moving buffer data from
  45950. * a storage buffer attribute from the GPU to the CPU.
  45951. *
  45952. * @async
  45953. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45954. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45955. */
  45956. async getArrayBufferAsync( attribute ) {
  45957. const backend = this.backend;
  45958. const { gl } = backend;
  45959. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45960. const { bufferGPU } = backend.get( bufferAttribute );
  45961. const array = attribute.array;
  45962. const byteLength = array.byteLength;
  45963. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  45964. const writeBuffer = gl.createBuffer();
  45965. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  45966. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  45967. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  45968. await backend.utils._clientWaitAsync();
  45969. const dstBuffer = new attribute.array.constructor( array.length );
  45970. // Ensure the buffer is bound before reading
  45971. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  45972. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  45973. gl.deleteBuffer( writeBuffer );
  45974. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  45975. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  45976. return dstBuffer.buffer;
  45977. }
  45978. /**
  45979. * Creates a WebGL buffer with the given data.
  45980. *
  45981. * @private
  45982. * @param {WebGL2RenderingContext} gl - The rendering context.
  45983. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  45984. * @param {TypedArray} array - The array of the buffer attribute.
  45985. * @param {GLenum} usage - The usage.
  45986. * @return {WebGLBuffer} The WebGL buffer.
  45987. */
  45988. _createBuffer( gl, bufferType, array, usage ) {
  45989. const bufferGPU = gl.createBuffer();
  45990. gl.bindBuffer( bufferType, bufferGPU );
  45991. gl.bufferData( bufferType, array, usage );
  45992. gl.bindBuffer( bufferType, null );
  45993. return bufferGPU;
  45994. }
  45995. }
  45996. let equationToGL, factorToGL;
  45997. /**
  45998. * A WebGL 2 backend utility module for managing the WebGL state.
  45999. *
  46000. * The major goal of this module is to reduce the number of state changes
  46001. * by caching the WEbGL state with a series of variables. In this way, the
  46002. * renderer only executes state change commands when necessary which
  46003. * improves the overall performance.
  46004. *
  46005. * @private
  46006. */
  46007. class WebGLState {
  46008. /**
  46009. * Constructs a new utility object.
  46010. *
  46011. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46012. */
  46013. constructor( backend ) {
  46014. /**
  46015. * A reference to the WebGL 2 backend.
  46016. *
  46017. * @type {WebGLBackend}
  46018. */
  46019. this.backend = backend;
  46020. /**
  46021. * A reference to the rendering context.
  46022. *
  46023. * @type {WebGL2RenderingContext}
  46024. */
  46025. this.gl = this.backend.gl;
  46026. // Below properties are intended to cache
  46027. // the WebGL state and are not explicitly
  46028. // documented for convenience reasons.
  46029. this.enabled = {};
  46030. this.currentFlipSided = null;
  46031. this.currentCullFace = null;
  46032. this.currentProgram = null;
  46033. this.currentBlendingEnabled = false;
  46034. this.currentBlending = null;
  46035. this.currentBlendSrc = null;
  46036. this.currentBlendDst = null;
  46037. this.currentBlendSrcAlpha = null;
  46038. this.currentBlendDstAlpha = null;
  46039. this.currentPremultipledAlpha = null;
  46040. this.currentPolygonOffsetFactor = null;
  46041. this.currentPolygonOffsetUnits = null;
  46042. this.currentColorMask = null;
  46043. this.currentDepthReversed = false;
  46044. this.currentDepthFunc = null;
  46045. this.currentDepthMask = null;
  46046. this.currentStencilFunc = null;
  46047. this.currentStencilRef = null;
  46048. this.currentStencilFuncMask = null;
  46049. this.currentStencilFail = null;
  46050. this.currentStencilZFail = null;
  46051. this.currentStencilZPass = null;
  46052. this.currentStencilMask = null;
  46053. this.currentLineWidth = null;
  46054. this.currentClippingPlanes = 0;
  46055. this.currentVAO = null;
  46056. this.currentIndex = null;
  46057. this.currentBoundFramebuffers = {};
  46058. this.currentDrawbuffers = new WeakMap();
  46059. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  46060. this.currentTextureSlot = null;
  46061. this.currentBoundTextures = {};
  46062. this.currentBoundBufferBases = {};
  46063. this._init();
  46064. }
  46065. /**
  46066. * Inits the state of the utility.
  46067. *
  46068. * @private
  46069. */
  46070. _init() {
  46071. const gl = this.gl;
  46072. // Store only WebGL constants here.
  46073. equationToGL = {
  46074. [ AddEquation ]: gl.FUNC_ADD,
  46075. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  46076. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  46077. };
  46078. factorToGL = {
  46079. [ ZeroFactor ]: gl.ZERO,
  46080. [ OneFactor ]: gl.ONE,
  46081. [ SrcColorFactor ]: gl.SRC_COLOR,
  46082. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  46083. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  46084. [ DstColorFactor ]: gl.DST_COLOR,
  46085. [ DstAlphaFactor ]: gl.DST_ALPHA,
  46086. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  46087. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  46088. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  46089. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  46090. };
  46091. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  46092. const viewportParam = gl.getParameter( gl.VIEWPORT );
  46093. this.currentScissor = new Vector4().fromArray( scissorParam );
  46094. this.currentViewport = new Vector4().fromArray( viewportParam );
  46095. this._tempVec4 = new Vector4();
  46096. }
  46097. /**
  46098. * Enables the given WebGL capability.
  46099. *
  46100. * This method caches the capability state so
  46101. * `gl.enable()` is only called when necessary.
  46102. *
  46103. * @param {GLenum} id - The capability to enable.
  46104. */
  46105. enable( id ) {
  46106. const { enabled } = this;
  46107. if ( enabled[ id ] !== true ) {
  46108. this.gl.enable( id );
  46109. enabled[ id ] = true;
  46110. }
  46111. }
  46112. /**
  46113. * Disables the given WebGL capability.
  46114. *
  46115. * This method caches the capability state so
  46116. * `gl.disable()` is only called when necessary.
  46117. *
  46118. * @param {GLenum} id - The capability to enable.
  46119. */
  46120. disable( id ) {
  46121. const { enabled } = this;
  46122. if ( enabled[ id ] !== false ) {
  46123. this.gl.disable( id );
  46124. enabled[ id ] = false;
  46125. }
  46126. }
  46127. /**
  46128. * Specifies whether polygons are front- or back-facing
  46129. * by setting the winding orientation.
  46130. *
  46131. * This method caches the state so `gl.frontFace()` is only
  46132. * called when necessary.
  46133. *
  46134. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  46135. */
  46136. setFlipSided( flipSided ) {
  46137. if ( this.currentFlipSided !== flipSided ) {
  46138. const { gl } = this;
  46139. if ( flipSided ) {
  46140. gl.frontFace( gl.CW );
  46141. } else {
  46142. gl.frontFace( gl.CCW );
  46143. }
  46144. this.currentFlipSided = flipSided;
  46145. }
  46146. }
  46147. /**
  46148. * Specifies whether or not front- and/or back-facing
  46149. * polygons can be culled.
  46150. *
  46151. * This method caches the state so `gl.cullFace()` is only
  46152. * called when necessary.
  46153. *
  46154. * @param {number} cullFace - Defines which polygons are candidates for culling.
  46155. */
  46156. setCullFace( cullFace ) {
  46157. const { gl } = this;
  46158. if ( cullFace !== CullFaceNone ) {
  46159. this.enable( gl.CULL_FACE );
  46160. if ( cullFace !== this.currentCullFace ) {
  46161. if ( cullFace === CullFaceBack ) {
  46162. gl.cullFace( gl.BACK );
  46163. } else if ( cullFace === CullFaceFront ) {
  46164. gl.cullFace( gl.FRONT );
  46165. } else {
  46166. gl.cullFace( gl.FRONT_AND_BACK );
  46167. }
  46168. }
  46169. } else {
  46170. this.disable( gl.CULL_FACE );
  46171. }
  46172. this.currentCullFace = cullFace;
  46173. }
  46174. /**
  46175. * Specifies the width of line primitives.
  46176. *
  46177. * This method caches the state so `gl.lineWidth()` is only
  46178. * called when necessary.
  46179. *
  46180. * @param {number} width - The line width.
  46181. */
  46182. setLineWidth( width ) {
  46183. const { currentLineWidth, gl } = this;
  46184. if ( width !== currentLineWidth ) {
  46185. gl.lineWidth( width );
  46186. this.currentLineWidth = width;
  46187. }
  46188. }
  46189. setMRTBlending( textures, mrt, material ) {
  46190. const gl = this.gl;
  46191. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  46192. if ( ! drawBuffersIndexedExt ) {
  46193. 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.' );
  46194. return;
  46195. }
  46196. for ( let i = 0; i < textures.length; i ++ ) {
  46197. const texture = textures[ i ];
  46198. let blending = null;
  46199. if ( mrt !== null ) {
  46200. const blendMode = mrt.getBlendMode( texture.name );
  46201. if ( blendMode.blending === MaterialBlending ) {
  46202. // use material blending
  46203. blending = material;
  46204. } else if ( blendMode.blending !== NoBlending ) {
  46205. blending = blendMode;
  46206. }
  46207. } else {
  46208. // use material blending
  46209. blending = material;
  46210. }
  46211. if ( blending !== null ) {
  46212. this._setMRTBlendingIndex( i, blending );
  46213. } else {
  46214. // use opaque blending (no blending)
  46215. drawBuffersIndexedExt.blendFuncSeparateiOES( i, gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  46216. }
  46217. }
  46218. }
  46219. /**
  46220. * Applies blending configuration for a specific draw buffer index.
  46221. *
  46222. * @private
  46223. * @param {number} index - The draw buffer index.
  46224. * @param {Object} blending - The blending configuration (material or BlendMode).
  46225. */
  46226. _setMRTBlendingIndex( index, blending ) {
  46227. const { gl } = this;
  46228. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  46229. const blendingType = blending.blending;
  46230. const blendSrc = blending.blendSrc;
  46231. const blendDst = blending.blendDst;
  46232. const blendEquation = blending.blendEquation;
  46233. const premultipliedAlpha = blending.premultipliedAlpha;
  46234. if ( blendingType === CustomBlending ) {
  46235. const blendSrcAlpha = blending.blendSrcAlpha !== null ? blending.blendSrcAlpha : blendSrc;
  46236. const blendDstAlpha = blending.blendDstAlpha !== null ? blending.blendDstAlpha : blendDst;
  46237. const blendEquationAlpha = blending.blendEquationAlpha !== null ? blending.blendEquationAlpha : blendEquation;
  46238. drawBuffersIndexedExt.blendEquationSeparateiOES( index, equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  46239. drawBuffersIndexedExt.blendFuncSeparateiOES( index, factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  46240. } else {
  46241. drawBuffersIndexedExt.blendEquationSeparateiOES( index, gl.FUNC_ADD, gl.FUNC_ADD );
  46242. if ( premultipliedAlpha ) {
  46243. switch ( blendingType ) {
  46244. case NormalBlending:
  46245. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46246. break;
  46247. case AdditiveBlending:
  46248. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  46249. break;
  46250. case SubtractiveBlending:
  46251. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  46252. break;
  46253. case MultiplyBlending:
  46254. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  46255. break;
  46256. default:
  46257. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46258. break;
  46259. }
  46260. } else {
  46261. switch ( blendingType ) {
  46262. case NormalBlending:
  46263. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46264. break;
  46265. case AdditiveBlending:
  46266. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  46267. break;
  46268. case SubtractiveBlending:
  46269. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  46270. break;
  46271. case MultiplyBlending:
  46272. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  46273. break;
  46274. default:
  46275. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46276. break;
  46277. }
  46278. }
  46279. }
  46280. }
  46281. /**
  46282. * Defines the blending.
  46283. *
  46284. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  46285. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  46286. *
  46287. * @param {number} blending - The blending type.
  46288. * @param {number} blendEquation - The blending equation.
  46289. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  46290. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  46291. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  46292. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  46293. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  46294. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  46295. */
  46296. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  46297. const { gl } = this;
  46298. if ( blending === NoBlending ) {
  46299. if ( this.currentBlendingEnabled === true ) {
  46300. this.disable( gl.BLEND );
  46301. this.currentBlendingEnabled = false;
  46302. }
  46303. return;
  46304. }
  46305. if ( this.currentBlendingEnabled === false ) {
  46306. this.enable( gl.BLEND );
  46307. this.currentBlendingEnabled = true;
  46308. }
  46309. if ( blending !== CustomBlending ) {
  46310. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  46311. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  46312. gl.blendEquation( gl.FUNC_ADD );
  46313. this.currentBlendEquation = AddEquation;
  46314. this.currentBlendEquationAlpha = AddEquation;
  46315. }
  46316. if ( premultipliedAlpha ) {
  46317. switch ( blending ) {
  46318. case NormalBlending:
  46319. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46320. break;
  46321. case AdditiveBlending:
  46322. gl.blendFunc( gl.ONE, gl.ONE );
  46323. break;
  46324. case SubtractiveBlending:
  46325. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  46326. break;
  46327. case MultiplyBlending:
  46328. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  46329. break;
  46330. default:
  46331. error( 'WebGLState: Invalid blending: ', blending );
  46332. break;
  46333. }
  46334. } else {
  46335. switch ( blending ) {
  46336. case NormalBlending:
  46337. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46338. break;
  46339. case AdditiveBlending:
  46340. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  46341. break;
  46342. case SubtractiveBlending:
  46343. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  46344. break;
  46345. case MultiplyBlending:
  46346. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  46347. break;
  46348. default:
  46349. error( 'WebGLState: Invalid blending: ', blending );
  46350. break;
  46351. }
  46352. }
  46353. this.currentBlendSrc = null;
  46354. this.currentBlendDst = null;
  46355. this.currentBlendSrcAlpha = null;
  46356. this.currentBlendDstAlpha = null;
  46357. this.currentBlending = blending;
  46358. this.currentPremultipledAlpha = premultipliedAlpha;
  46359. }
  46360. return;
  46361. }
  46362. // custom blending
  46363. blendEquationAlpha = blendEquationAlpha || blendEquation;
  46364. blendSrcAlpha = blendSrcAlpha || blendSrc;
  46365. blendDstAlpha = blendDstAlpha || blendDst;
  46366. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  46367. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  46368. this.currentBlendEquation = blendEquation;
  46369. this.currentBlendEquationAlpha = blendEquationAlpha;
  46370. }
  46371. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  46372. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  46373. this.currentBlendSrc = blendSrc;
  46374. this.currentBlendDst = blendDst;
  46375. this.currentBlendSrcAlpha = blendSrcAlpha;
  46376. this.currentBlendDstAlpha = blendDstAlpha;
  46377. }
  46378. this.currentBlending = blending;
  46379. this.currentPremultipledAlpha = false;
  46380. }
  46381. /**
  46382. * Specifies whether colors can be written when rendering
  46383. * into a framebuffer or not.
  46384. *
  46385. * This method caches the state so `gl.colorMask()` is only
  46386. * called when necessary.
  46387. *
  46388. * @param {boolean} colorMask - The color mask.
  46389. */
  46390. setColorMask( colorMask ) {
  46391. if ( this.currentColorMask !== colorMask ) {
  46392. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  46393. this.currentColorMask = colorMask;
  46394. }
  46395. }
  46396. /**
  46397. * Specifies whether the depth test is enabled or not.
  46398. *
  46399. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  46400. */
  46401. setDepthTest( depthTest ) {
  46402. const { gl } = this;
  46403. if ( depthTest ) {
  46404. this.enable( gl.DEPTH_TEST );
  46405. } else {
  46406. this.disable( gl.DEPTH_TEST );
  46407. }
  46408. }
  46409. /**
  46410. * Configures the WebGL state to use a reversed depth buffer.
  46411. *
  46412. * @param {boolean} reversed - Whether the depth buffer is reversed or not.
  46413. */
  46414. setReversedDepth( reversed ) {
  46415. if ( this.currentDepthReversed !== reversed ) {
  46416. const ext = this.backend.extensions.get( 'EXT_clip_control' );
  46417. if ( reversed ) {
  46418. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  46419. } else {
  46420. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  46421. }
  46422. this.currentDepthReversed = reversed;
  46423. }
  46424. }
  46425. /**
  46426. * Specifies whether depth values can be written when rendering
  46427. * into a framebuffer or not.
  46428. *
  46429. * This method caches the state so `gl.depthMask()` is only
  46430. * called when necessary.
  46431. *
  46432. * @param {boolean} depthMask - The depth mask.
  46433. */
  46434. setDepthMask( depthMask ) {
  46435. if ( this.currentDepthMask !== depthMask ) {
  46436. this.gl.depthMask( depthMask );
  46437. this.currentDepthMask = depthMask;
  46438. }
  46439. }
  46440. /**
  46441. * Specifies the depth compare function.
  46442. *
  46443. * This method caches the state so `gl.depthFunc()` is only
  46444. * called when necessary.
  46445. *
  46446. * @param {number} depthFunc - The depth compare function.
  46447. */
  46448. setDepthFunc( depthFunc ) {
  46449. if ( this.currentDepthReversed ) depthFunc = ReversedDepthFuncs[ depthFunc ];
  46450. if ( this.currentDepthFunc !== depthFunc ) {
  46451. const { gl } = this;
  46452. switch ( depthFunc ) {
  46453. case NeverDepth:
  46454. gl.depthFunc( gl.NEVER );
  46455. break;
  46456. case AlwaysDepth:
  46457. gl.depthFunc( gl.ALWAYS );
  46458. break;
  46459. case LessDepth:
  46460. gl.depthFunc( gl.LESS );
  46461. break;
  46462. case LessEqualDepth:
  46463. gl.depthFunc( gl.LEQUAL );
  46464. break;
  46465. case EqualDepth:
  46466. gl.depthFunc( gl.EQUAL );
  46467. break;
  46468. case GreaterEqualDepth:
  46469. gl.depthFunc( gl.GEQUAL );
  46470. break;
  46471. case GreaterDepth:
  46472. gl.depthFunc( gl.GREATER );
  46473. break;
  46474. case NotEqualDepth:
  46475. gl.depthFunc( gl.NOTEQUAL );
  46476. break;
  46477. default:
  46478. gl.depthFunc( gl.LEQUAL );
  46479. }
  46480. this.currentDepthFunc = depthFunc;
  46481. }
  46482. }
  46483. /**
  46484. * Specifies the scissor box.
  46485. *
  46486. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46487. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46488. * @param {number} width - The width of the viewport.
  46489. * @param {number} height - The height of the viewport.
  46490. *
  46491. */
  46492. scissor( x, y, width, height ) {
  46493. const scissor = this._tempVec4.set( x, y, width, height );
  46494. if ( this.currentScissor.equals( scissor ) === false ) {
  46495. const { gl } = this;
  46496. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  46497. this.currentScissor.copy( scissor );
  46498. }
  46499. }
  46500. /**
  46501. * Specifies the viewport.
  46502. *
  46503. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46504. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46505. * @param {number} width - The width of the viewport.
  46506. * @param {number} height - The height of the viewport.
  46507. *
  46508. */
  46509. viewport( x, y, width, height ) {
  46510. const viewport = this._tempVec4.set( x, y, width, height );
  46511. if ( this.currentViewport.equals( viewport ) === false ) {
  46512. const { gl } = this;
  46513. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  46514. this.currentViewport.copy( viewport );
  46515. }
  46516. }
  46517. /**
  46518. * Defines the scissor test.
  46519. *
  46520. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  46521. */
  46522. setScissorTest( boolean ) {
  46523. const gl = this.gl;
  46524. if ( boolean ) {
  46525. this.enable( gl.SCISSOR_TEST );
  46526. } else {
  46527. this.disable( gl.SCISSOR_TEST );
  46528. }
  46529. }
  46530. /**
  46531. * Specifies whether the stencil test is enabled or not.
  46532. *
  46533. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  46534. */
  46535. setStencilTest( stencilTest ) {
  46536. const { gl } = this;
  46537. if ( stencilTest ) {
  46538. this.enable( gl.STENCIL_TEST );
  46539. } else {
  46540. this.disable( gl.STENCIL_TEST );
  46541. }
  46542. }
  46543. /**
  46544. * Specifies whether stencil values can be written when rendering
  46545. * into a framebuffer or not.
  46546. *
  46547. * This method caches the state so `gl.stencilMask()` is only
  46548. * called when necessary.
  46549. *
  46550. * @param {boolean} stencilMask - The stencil mask.
  46551. */
  46552. setStencilMask( stencilMask ) {
  46553. if ( this.currentStencilMask !== stencilMask ) {
  46554. this.gl.stencilMask( stencilMask );
  46555. this.currentStencilMask = stencilMask;
  46556. }
  46557. }
  46558. /**
  46559. * Specifies whether the stencil test functions.
  46560. *
  46561. * This method caches the state so `gl.stencilFunc()` is only
  46562. * called when necessary.
  46563. *
  46564. * @param {number} stencilFunc - The stencil compare function.
  46565. * @param {number} stencilRef - The reference value for the stencil test.
  46566. * @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.
  46567. */
  46568. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  46569. if ( this.currentStencilFunc !== stencilFunc ||
  46570. this.currentStencilRef !== stencilRef ||
  46571. this.currentStencilFuncMask !== stencilMask ) {
  46572. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  46573. this.currentStencilFunc = stencilFunc;
  46574. this.currentStencilRef = stencilRef;
  46575. this.currentStencilFuncMask = stencilMask;
  46576. }
  46577. }
  46578. /**
  46579. * Specifies whether the stencil test operation.
  46580. *
  46581. * This method caches the state so `gl.stencilOp()` is only
  46582. * called when necessary.
  46583. *
  46584. * @param {number} stencilFail - The function to use when the stencil test fails.
  46585. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  46586. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  46587. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  46588. */
  46589. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  46590. if ( this.currentStencilFail !== stencilFail ||
  46591. this.currentStencilZFail !== stencilZFail ||
  46592. this.currentStencilZPass !== stencilZPass ) {
  46593. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  46594. this.currentStencilFail = stencilFail;
  46595. this.currentStencilZFail = stencilZFail;
  46596. this.currentStencilZPass = stencilZPass;
  46597. }
  46598. }
  46599. /**
  46600. * Configures the WebGL state for the given material.
  46601. *
  46602. * @param {Material} material - The material to configure the state for.
  46603. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  46604. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  46605. */
  46606. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  46607. const { gl } = this;
  46608. material.side === DoubleSide
  46609. ? this.disable( gl.CULL_FACE )
  46610. : this.enable( gl.CULL_FACE );
  46611. let flipSided = ( material.side === BackSide );
  46612. if ( frontFaceCW ) flipSided = ! flipSided;
  46613. this.setFlipSided( flipSided );
  46614. ( material.blending === NormalBlending && material.transparent === false )
  46615. ? this.setBlending( NoBlending )
  46616. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  46617. this.setDepthFunc( material.depthFunc );
  46618. this.setDepthTest( material.depthTest );
  46619. this.setDepthMask( material.depthWrite );
  46620. this.setColorMask( material.colorWrite );
  46621. const stencilWrite = material.stencilWrite;
  46622. this.setStencilTest( stencilWrite );
  46623. if ( stencilWrite ) {
  46624. this.setStencilMask( material.stencilWriteMask );
  46625. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  46626. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  46627. }
  46628. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  46629. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  46630. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  46631. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  46632. if ( hardwareClippingPlanes > 0 ) {
  46633. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  46634. const CLIP_DISTANCE0_WEBGL = 0x3000;
  46635. for ( let i = 0; i < 8; i ++ ) {
  46636. if ( i < hardwareClippingPlanes ) {
  46637. this.enable( CLIP_DISTANCE0_WEBGL + i );
  46638. } else {
  46639. this.disable( CLIP_DISTANCE0_WEBGL + i );
  46640. }
  46641. }
  46642. }
  46643. }
  46644. }
  46645. /**
  46646. * Specifies the polygon offset.
  46647. *
  46648. * This method caches the state so `gl.polygonOffset()` is only
  46649. * called when necessary.
  46650. *
  46651. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  46652. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  46653. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  46654. */
  46655. setPolygonOffset( polygonOffset, factor, units ) {
  46656. const { gl } = this;
  46657. if ( polygonOffset ) {
  46658. this.enable( gl.POLYGON_OFFSET_FILL );
  46659. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  46660. gl.polygonOffset( factor, units );
  46661. this.currentPolygonOffsetFactor = factor;
  46662. this.currentPolygonOffsetUnits = units;
  46663. }
  46664. } else {
  46665. this.disable( gl.POLYGON_OFFSET_FILL );
  46666. }
  46667. }
  46668. /**
  46669. * Defines the usage of the given WebGL program.
  46670. *
  46671. * This method caches the state so `gl.useProgram()` is only
  46672. * called when necessary.
  46673. *
  46674. * @param {WebGLProgram} program - The WebGL program to use.
  46675. * @return {boolean} Whether a program change has been executed or not.
  46676. */
  46677. useProgram( program ) {
  46678. if ( this.currentProgram !== program ) {
  46679. this.gl.useProgram( program );
  46680. this.currentProgram = program;
  46681. return true;
  46682. }
  46683. return false;
  46684. }
  46685. /**
  46686. * Sets the vertex state by binding the given VAO and element buffer.
  46687. *
  46688. * @param {WebGLVertexArrayObject} vao - The VAO.
  46689. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  46690. * @return {boolean} Whether a vertex state has been changed or not.
  46691. */
  46692. setVertexState( vao, indexBuffer = null ) {
  46693. const gl = this.gl;
  46694. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  46695. gl.bindVertexArray( vao );
  46696. if ( indexBuffer !== null ) {
  46697. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  46698. }
  46699. this.currentVAO = vao;
  46700. this.currentIndex = indexBuffer;
  46701. return true;
  46702. }
  46703. return false;
  46704. }
  46705. /**
  46706. * Resets the vertex array state by resetting the VAO and element buffer.
  46707. */
  46708. resetVertexState() {
  46709. const gl = this.gl;
  46710. gl.bindVertexArray( null );
  46711. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  46712. this.currentVAO = null;
  46713. this.currentIndex = null;
  46714. }
  46715. // framebuffer
  46716. /**
  46717. * Binds the given framebuffer.
  46718. *
  46719. * This method caches the state so `gl.bindFramebuffer()` is only
  46720. * called when necessary.
  46721. *
  46722. * @param {number} target - The binding point (target).
  46723. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  46724. * @return {boolean} Whether a bind has been executed or not.
  46725. */
  46726. bindFramebuffer( target, framebuffer ) {
  46727. const { gl, currentBoundFramebuffers } = this;
  46728. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  46729. gl.bindFramebuffer( target, framebuffer );
  46730. currentBoundFramebuffers[ target ] = framebuffer;
  46731. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  46732. if ( target === gl.DRAW_FRAMEBUFFER ) {
  46733. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  46734. }
  46735. if ( target === gl.FRAMEBUFFER ) {
  46736. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  46737. }
  46738. return true;
  46739. }
  46740. return false;
  46741. }
  46742. /**
  46743. * Defines draw buffers to which fragment colors are written into.
  46744. * Configures the MRT setup of custom framebuffers.
  46745. *
  46746. * This method caches the state so `gl.drawBuffers()` is only
  46747. * called when necessary.
  46748. *
  46749. * @param {RenderContext} renderContext - The render context.
  46750. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  46751. */
  46752. drawBuffers( renderContext, framebuffer ) {
  46753. const { gl } = this;
  46754. let drawBuffers = [];
  46755. let needsUpdate = false;
  46756. if ( renderContext.textures !== null ) {
  46757. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  46758. if ( drawBuffers === undefined ) {
  46759. drawBuffers = [];
  46760. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  46761. }
  46762. const textures = renderContext.textures;
  46763. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  46764. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  46765. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  46766. }
  46767. drawBuffers.length = textures.length;
  46768. needsUpdate = true;
  46769. }
  46770. } else {
  46771. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  46772. drawBuffers[ 0 ] = gl.BACK;
  46773. needsUpdate = true;
  46774. }
  46775. }
  46776. if ( needsUpdate ) {
  46777. gl.drawBuffers( drawBuffers );
  46778. }
  46779. }
  46780. // texture
  46781. /**
  46782. * Makes the given texture unit active.
  46783. *
  46784. * This method caches the state so `gl.activeTexture()` is only
  46785. * called when necessary.
  46786. *
  46787. * @param {number} webglSlot - The texture unit to make active.
  46788. */
  46789. activeTexture( webglSlot ) {
  46790. const { gl, currentTextureSlot, maxTextures } = this;
  46791. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  46792. if ( currentTextureSlot !== webglSlot ) {
  46793. gl.activeTexture( webglSlot );
  46794. this.currentTextureSlot = webglSlot;
  46795. }
  46796. }
  46797. /**
  46798. * Binds the given WebGL texture to a target.
  46799. *
  46800. * This method caches the state so `gl.bindTexture()` is only
  46801. * called when necessary.
  46802. *
  46803. * @param {number} webglType - The binding point (target).
  46804. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  46805. * @param {number} webglSlot - The texture.
  46806. */
  46807. bindTexture( webglType, webglTexture, webglSlot ) {
  46808. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  46809. if ( webglSlot === undefined ) {
  46810. if ( currentTextureSlot === null ) {
  46811. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  46812. } else {
  46813. webglSlot = currentTextureSlot;
  46814. }
  46815. }
  46816. let boundTexture = currentBoundTextures[ webglSlot ];
  46817. if ( boundTexture === undefined ) {
  46818. boundTexture = { type: undefined, texture: undefined };
  46819. currentBoundTextures[ webglSlot ] = boundTexture;
  46820. }
  46821. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  46822. if ( currentTextureSlot !== webglSlot ) {
  46823. gl.activeTexture( webglSlot );
  46824. this.currentTextureSlot = webglSlot;
  46825. }
  46826. gl.bindTexture( webglType, webglTexture );
  46827. boundTexture.type = webglType;
  46828. boundTexture.texture = webglTexture;
  46829. }
  46830. }
  46831. /**
  46832. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  46833. *
  46834. * This method caches the state so `gl.bindBufferBase()` is only
  46835. * called when necessary.
  46836. *
  46837. * @param {number} target - The target for the bind operation.
  46838. * @param {number} index - The index of the target.
  46839. * @param {WebGLBuffer} buffer - The WebGL buffer.
  46840. * @return {boolean} Whether a bind has been executed or not.
  46841. */
  46842. bindBufferBase( target, index, buffer ) {
  46843. const { gl } = this;
  46844. const key = `${target}-${index}`;
  46845. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  46846. gl.bindBufferBase( target, index, buffer );
  46847. this.currentBoundBufferBases[ key ] = buffer;
  46848. return true;
  46849. }
  46850. return false;
  46851. }
  46852. /**
  46853. * Unbinds the current bound texture.
  46854. *
  46855. * This method caches the state so `gl.bindTexture()` is only
  46856. * called when necessary.
  46857. */
  46858. unbindTexture() {
  46859. const { gl, currentTextureSlot, currentBoundTextures } = this;
  46860. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  46861. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  46862. gl.bindTexture( boundTexture.type, null );
  46863. boundTexture.type = undefined;
  46864. boundTexture.texture = undefined;
  46865. }
  46866. }
  46867. }
  46868. /**
  46869. * A WebGL 2 backend utility module with common helpers.
  46870. *
  46871. * @private
  46872. */
  46873. class WebGLUtils {
  46874. /**
  46875. * Constructs a new utility object.
  46876. *
  46877. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46878. */
  46879. constructor( backend ) {
  46880. /**
  46881. * A reference to the WebGL 2 backend.
  46882. *
  46883. * @type {WebGLBackend}
  46884. */
  46885. this.backend = backend;
  46886. /**
  46887. * A reference to the rendering context.
  46888. *
  46889. * @type {WebGL2RenderingContext}
  46890. */
  46891. this.gl = this.backend.gl;
  46892. /**
  46893. * A reference to a backend module holding extension-related
  46894. * utility functions.
  46895. *
  46896. * @type {WebGLExtensions}
  46897. */
  46898. this.extensions = backend.extensions;
  46899. }
  46900. /**
  46901. * Converts the given three.js constant into a WebGL constant.
  46902. * The method currently supports the conversion of texture formats
  46903. * and types.
  46904. *
  46905. * @param {number} p - The three.js constant.
  46906. * @param {string} [colorSpace=NoColorSpace] - The color space.
  46907. * @return {?number} The corresponding WebGL constant.
  46908. */
  46909. convert( p, colorSpace = NoColorSpace ) {
  46910. const { gl, extensions } = this;
  46911. let extension;
  46912. const transfer = ColorManagement.getTransfer( colorSpace );
  46913. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  46914. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  46915. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  46916. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  46917. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  46918. if ( p === ByteType ) return gl.BYTE;
  46919. if ( p === ShortType ) return gl.SHORT;
  46920. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  46921. if ( p === IntType ) return gl.INT;
  46922. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  46923. if ( p === FloatType ) return gl.FLOAT;
  46924. if ( p === HalfFloatType ) {
  46925. return gl.HALF_FLOAT;
  46926. }
  46927. if ( p === AlphaFormat ) return gl.ALPHA;
  46928. if ( p === RGBFormat ) return gl.RGB;
  46929. if ( p === RGBAFormat ) return gl.RGBA;
  46930. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  46931. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  46932. // WebGL2 formats.
  46933. if ( p === RedFormat ) return gl.RED;
  46934. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  46935. if ( p === RGFormat ) return gl.RG;
  46936. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  46937. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  46938. // S3TC
  46939. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  46940. if ( transfer === SRGBTransfer ) {
  46941. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  46942. if ( extension !== null ) {
  46943. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  46944. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  46945. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  46946. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  46947. } else {
  46948. return null;
  46949. }
  46950. } else {
  46951. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  46952. if ( extension !== null ) {
  46953. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  46954. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  46955. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  46956. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  46957. } else {
  46958. return null;
  46959. }
  46960. }
  46961. }
  46962. // PVRTC
  46963. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  46964. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  46965. if ( extension !== null ) {
  46966. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  46967. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  46968. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  46969. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  46970. } else {
  46971. return null;
  46972. }
  46973. }
  46974. // ETC
  46975. 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 ) {
  46976. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  46977. if ( extension !== null ) {
  46978. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  46979. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  46980. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  46981. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  46982. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  46983. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  46984. } else {
  46985. return null;
  46986. }
  46987. }
  46988. // ASTC
  46989. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  46990. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  46991. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  46992. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  46993. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  46994. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  46995. if ( extension !== null ) {
  46996. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  46997. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  46998. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  46999. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  47000. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  47001. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  47002. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  47003. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  47004. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  47005. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  47006. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  47007. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  47008. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  47009. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  47010. } else {
  47011. return null;
  47012. }
  47013. }
  47014. // BPTC
  47015. if ( p === RGBA_BPTC_Format ) {
  47016. extension = extensions.get( 'EXT_texture_compression_bptc' );
  47017. if ( extension !== null ) {
  47018. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  47019. } else {
  47020. return null;
  47021. }
  47022. }
  47023. // RGTC
  47024. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  47025. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  47026. if ( extension !== null ) {
  47027. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  47028. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  47029. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  47030. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  47031. } else {
  47032. return null;
  47033. }
  47034. }
  47035. //
  47036. if ( p === UnsignedInt248Type ) {
  47037. return gl.UNSIGNED_INT_24_8;
  47038. }
  47039. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  47040. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  47041. }
  47042. /**
  47043. * This method can be used to synchronize the CPU with the GPU by waiting until
  47044. * ongoing GPU commands have been completed.
  47045. *
  47046. * @private
  47047. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  47048. */
  47049. _clientWaitAsync() {
  47050. const { gl } = this;
  47051. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  47052. gl.flush();
  47053. return new Promise( ( resolve, reject ) => {
  47054. function test() {
  47055. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  47056. if ( res === gl.WAIT_FAILED ) {
  47057. gl.deleteSync( sync );
  47058. reject();
  47059. return;
  47060. }
  47061. if ( res === gl.TIMEOUT_EXPIRED ) {
  47062. requestAnimationFrame( test );
  47063. return;
  47064. }
  47065. gl.deleteSync( sync );
  47066. resolve();
  47067. }
  47068. test();
  47069. } );
  47070. }
  47071. }
  47072. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  47073. /**
  47074. * A WebGL 2 backend utility module for managing textures.
  47075. *
  47076. * @private
  47077. */
  47078. class WebGLTextureUtils {
  47079. /**
  47080. * Constructs a new utility object.
  47081. *
  47082. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47083. */
  47084. constructor( backend ) {
  47085. /**
  47086. * A reference to the WebGL 2 backend.
  47087. *
  47088. * @type {WebGLBackend}
  47089. */
  47090. this.backend = backend;
  47091. /**
  47092. * A reference to the rendering context.
  47093. *
  47094. * @type {WebGL2RenderingContext}
  47095. */
  47096. this.gl = backend.gl;
  47097. /**
  47098. * A reference to a backend module holding extension-related
  47099. * utility functions.
  47100. *
  47101. * @type {WebGLExtensions}
  47102. */
  47103. this.extensions = backend.extensions;
  47104. /**
  47105. * A dictionary for managing default textures. The key
  47106. * is the binding point (target), the value the WEbGL texture object.
  47107. *
  47108. * @type {Object<GLenum,WebGLTexture>}
  47109. */
  47110. this.defaultTextures = {};
  47111. /**
  47112. * A scratch framebuffer used for attaching the source texture in
  47113. * {@link copyTextureToTexture}.
  47114. *
  47115. * @private
  47116. * @type {?WebGLFramebuffer}
  47117. */
  47118. this._srcFramebuffer = null;
  47119. /**
  47120. * A scratch framebuffer used for attaching the destination texture in
  47121. * {@link copyTextureToTexture}.
  47122. *
  47123. * @private
  47124. * @type {?WebGLFramebuffer}
  47125. */
  47126. this._dstFramebuffer = null;
  47127. if ( initialized === false ) {
  47128. this._init();
  47129. initialized = true;
  47130. }
  47131. }
  47132. /**
  47133. * Inits the state of the utility.
  47134. *
  47135. * @private
  47136. */
  47137. _init() {
  47138. const gl = this.gl;
  47139. // Store only WebGL constants here.
  47140. wrappingToGL = {
  47141. [ RepeatWrapping ]: gl.REPEAT,
  47142. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  47143. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  47144. };
  47145. filterToGL = {
  47146. [ NearestFilter ]: gl.NEAREST,
  47147. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  47148. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  47149. [ LinearFilter ]: gl.LINEAR,
  47150. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  47151. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  47152. };
  47153. compareToGL = {
  47154. [ NeverCompare ]: gl.NEVER,
  47155. [ AlwaysCompare ]: gl.ALWAYS,
  47156. [ LessCompare ]: gl.LESS,
  47157. [ LessEqualCompare ]: gl.LEQUAL,
  47158. [ EqualCompare ]: gl.EQUAL,
  47159. [ GreaterEqualCompare ]: gl.GEQUAL,
  47160. [ GreaterCompare ]: gl.GREATER,
  47161. [ NotEqualCompare ]: gl.NOTEQUAL
  47162. };
  47163. }
  47164. /**
  47165. * Returns the native texture type for the given texture.
  47166. *
  47167. * @param {Texture} texture - The texture.
  47168. * @return {GLenum} The native texture type.
  47169. */
  47170. getGLTextureType( texture ) {
  47171. const { gl } = this;
  47172. let glTextureType;
  47173. if ( texture.isCubeTexture === true ) {
  47174. glTextureType = gl.TEXTURE_CUBE_MAP;
  47175. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  47176. glTextureType = gl.TEXTURE_2D_ARRAY;
  47177. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  47178. glTextureType = gl.TEXTURE_3D;
  47179. } else {
  47180. glTextureType = gl.TEXTURE_2D;
  47181. }
  47182. return glTextureType;
  47183. }
  47184. /**
  47185. * Returns the native texture type for the given texture.
  47186. *
  47187. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  47188. * @param {GLenum} glFormat - The WebGL format.
  47189. * @param {GLenum} glType - The WebGL type.
  47190. * @param {string} colorSpace - The texture's color space.
  47191. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  47192. * @return {GLenum} The internal format.
  47193. */
  47194. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  47195. const { gl, extensions } = this;
  47196. if ( internalFormatName !== null ) {
  47197. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  47198. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  47199. }
  47200. let internalFormat = glFormat;
  47201. if ( glFormat === gl.RED ) {
  47202. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  47203. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  47204. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  47205. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  47206. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  47207. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  47208. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  47209. if ( glType === gl.INT ) internalFormat = gl.R32I;
  47210. }
  47211. if ( glFormat === gl.RED_INTEGER ) {
  47212. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  47213. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  47214. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  47215. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  47216. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  47217. if ( glType === gl.INT ) internalFormat = gl.R32I;
  47218. }
  47219. if ( glFormat === gl.RG ) {
  47220. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  47221. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  47222. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  47223. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  47224. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  47225. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  47226. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  47227. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  47228. }
  47229. if ( glFormat === gl.RG_INTEGER ) {
  47230. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  47231. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  47232. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  47233. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  47234. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  47235. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  47236. }
  47237. if ( glFormat === gl.RGB ) {
  47238. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47239. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  47240. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  47241. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  47242. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  47243. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  47244. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  47245. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  47246. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  47247. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  47248. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  47249. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  47250. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  47251. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  47252. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  47253. }
  47254. if ( glFormat === gl.RGB_INTEGER ) {
  47255. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  47256. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  47257. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  47258. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  47259. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  47260. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  47261. }
  47262. if ( glFormat === gl.RGBA ) {
  47263. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47264. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  47265. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  47266. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  47267. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  47268. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  47269. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  47270. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  47271. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  47272. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  47273. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  47274. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  47275. }
  47276. if ( glFormat === gl.RGBA_INTEGER ) {
  47277. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  47278. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  47279. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  47280. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  47281. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  47282. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  47283. }
  47284. if ( glFormat === gl.DEPTH_COMPONENT ) {
  47285. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  47286. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  47287. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  47288. }
  47289. if ( glFormat === gl.DEPTH_STENCIL ) {
  47290. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  47291. }
  47292. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  47293. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  47294. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  47295. extensions.get( 'EXT_color_buffer_float' );
  47296. }
  47297. return internalFormat;
  47298. }
  47299. /**
  47300. * Sets the texture parameters for the given texture.
  47301. *
  47302. * @param {GLenum} textureType - The texture type.
  47303. * @param {Texture} texture - The texture.
  47304. */
  47305. setTextureParameters( textureType, texture ) {
  47306. const { gl, extensions, backend } = this;
  47307. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  47308. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  47309. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  47310. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  47311. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  47312. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  47313. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  47314. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  47315. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  47316. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  47317. // WebGL 2 does not support wrapping for depth 2D array textures
  47318. if ( ! texture.isArrayTexture ) {
  47319. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  47320. }
  47321. }
  47322. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  47323. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  47324. // follow WebGPU backend mapping for texture filtering
  47325. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  47326. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  47327. if ( texture.compareFunction ) {
  47328. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  47329. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  47330. }
  47331. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  47332. if ( texture.magFilter === NearestFilter ) return;
  47333. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  47334. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  47335. if ( texture.anisotropy > 1 ) {
  47336. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  47337. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  47338. }
  47339. }
  47340. }
  47341. /**
  47342. * Creates a default texture for the given texture that can be used
  47343. * as a placeholder until the actual texture is ready for usage.
  47344. *
  47345. * @param {Texture} texture - The texture to create a default texture for.
  47346. */
  47347. createDefaultTexture( texture ) {
  47348. const { gl, backend, defaultTextures } = this;
  47349. const glTextureType = this.getGLTextureType( texture );
  47350. let textureGPU = defaultTextures[ glTextureType ];
  47351. if ( textureGPU === undefined ) {
  47352. textureGPU = gl.createTexture();
  47353. backend.state.bindTexture( glTextureType, textureGPU );
  47354. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  47355. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  47356. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  47357. defaultTextures[ glTextureType ] = textureGPU;
  47358. }
  47359. backend.set( texture, {
  47360. textureGPU,
  47361. glTextureType
  47362. } );
  47363. }
  47364. /**
  47365. * Defines a texture on the GPU for the given texture object.
  47366. *
  47367. * @param {Texture} texture - The texture.
  47368. * @param {Object} [options={}] - Optional configuration parameter.
  47369. * @return {undefined}
  47370. */
  47371. createTexture( texture, options ) {
  47372. const { gl, backend } = this;
  47373. const { levels, width, height, depth } = options;
  47374. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  47375. const glType = backend.utils.convert( texture.type );
  47376. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  47377. const textureGPU = gl.createTexture();
  47378. const glTextureType = this.getGLTextureType( texture );
  47379. backend.state.bindTexture( glTextureType, textureGPU );
  47380. this.setTextureParameters( glTextureType, texture );
  47381. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  47382. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  47383. } else if ( texture.isData3DTexture ) {
  47384. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  47385. } else if ( ! texture.isVideoTexture ) {
  47386. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  47387. }
  47388. backend.set( texture, {
  47389. textureGPU,
  47390. glTextureType,
  47391. glFormat,
  47392. glType,
  47393. glInternalFormat
  47394. } );
  47395. }
  47396. /**
  47397. * Uploads texture buffer data to the GPU memory.
  47398. *
  47399. * @param {WebGLBuffer} buffer - The buffer data.
  47400. * @param {Texture} texture - The texture,
  47401. */
  47402. copyBufferToTexture( buffer, texture ) {
  47403. const { gl, backend } = this;
  47404. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  47405. const { width, height } = texture.source.data;
  47406. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  47407. backend.state.bindTexture( glTextureType, textureGPU );
  47408. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  47409. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  47410. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  47411. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  47412. backend.state.unbindTexture();
  47413. // debug
  47414. // const framebuffer = gl.createFramebuffer();
  47415. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  47416. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  47417. // const readout = new Float32Array( width * height * 4 );
  47418. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  47419. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  47420. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  47421. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, null );
  47422. // log( readout );
  47423. }
  47424. /**
  47425. * Uploads the updated texture data to the GPU.
  47426. *
  47427. * @param {Texture} texture - The texture.
  47428. * @param {Object} [options={}] - Optional configuration parameter.
  47429. */
  47430. updateTexture( texture, options ) {
  47431. const { gl } = this;
  47432. const { width, height } = options;
  47433. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  47434. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  47435. return;
  47436. this.backend.state.bindTexture( glTextureType, textureGPU );
  47437. this.setTextureParameters( glTextureType, texture );
  47438. if ( texture.isCompressedTexture ) {
  47439. const mipmaps = texture.mipmaps;
  47440. const image = options.image;
  47441. for ( let i = 0; i < mipmaps.length; i ++ ) {
  47442. const mipmap = mipmaps[ i ];
  47443. if ( texture.isCompressedArrayTexture ) {
  47444. if ( texture.format !== gl.RGBA ) {
  47445. if ( glFormat !== null ) {
  47446. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  47447. } else {
  47448. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  47449. }
  47450. } else {
  47451. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  47452. }
  47453. } else {
  47454. if ( glFormat !== null ) {
  47455. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  47456. } else {
  47457. warn( 'WebGLBackend: Unsupported compressed texture format' );
  47458. }
  47459. }
  47460. }
  47461. } else if ( texture.isCubeTexture ) {
  47462. const images = options.images;
  47463. const mipmaps = texture.mipmaps;
  47464. for ( let i = 0; i < 6; i ++ ) {
  47465. const image = getImage( images[ i ] );
  47466. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  47467. for ( let j = 0; j < mipmaps.length; j ++ ) {
  47468. const mipmap = mipmaps[ j ];
  47469. const image = getImage( mipmap.images[ i ] );
  47470. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  47471. }
  47472. }
  47473. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  47474. const image = options.image;
  47475. if ( texture.layerUpdates.size > 0 ) {
  47476. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  47477. for ( const layerIndex of texture.layerUpdates ) {
  47478. const layerData = image.data.subarray(
  47479. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  47480. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  47481. );
  47482. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  47483. }
  47484. texture.clearLayerUpdates();
  47485. } else {
  47486. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47487. }
  47488. } else if ( texture.isData3DTexture ) {
  47489. const image = options.image;
  47490. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47491. } else if ( texture.isVideoTexture ) {
  47492. texture.update();
  47493. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  47494. } else {
  47495. const mipmaps = texture.mipmaps;
  47496. if ( mipmaps.length > 0 ) {
  47497. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  47498. const mipmap = mipmaps[ i ];
  47499. const image = getImage( mipmap );
  47500. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  47501. }
  47502. } else {
  47503. const image = getImage( options.image );
  47504. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  47505. }
  47506. }
  47507. }
  47508. /**
  47509. * Generates mipmaps for the given texture.
  47510. *
  47511. * @param {Texture} texture - The texture.
  47512. */
  47513. generateMipmaps( texture ) {
  47514. const { gl, backend } = this;
  47515. const { textureGPU, glTextureType } = backend.get( texture );
  47516. backend.state.bindTexture( glTextureType, textureGPU );
  47517. gl.generateMipmap( glTextureType );
  47518. }
  47519. /**
  47520. * Deallocates the render buffers of the given render target.
  47521. *
  47522. * @param {RenderTarget} renderTarget - The render target.
  47523. */
  47524. deallocateRenderBuffers( renderTarget ) {
  47525. const { gl, backend } = this;
  47526. // remove framebuffer reference
  47527. if ( renderTarget ) {
  47528. const renderContextData = backend.get( renderTarget );
  47529. renderContextData.renderBufferStorageSetup = undefined;
  47530. if ( renderContextData.framebuffers ) {
  47531. for ( const cacheKey in renderContextData.framebuffers ) {
  47532. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  47533. }
  47534. delete renderContextData.framebuffers;
  47535. }
  47536. if ( renderContextData.depthRenderbuffer ) {
  47537. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  47538. delete renderContextData.depthRenderbuffer;
  47539. }
  47540. if ( renderContextData.stencilRenderbuffer ) {
  47541. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  47542. delete renderContextData.stencilRenderbuffer;
  47543. }
  47544. if ( renderContextData.msaaFrameBuffer ) {
  47545. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  47546. delete renderContextData.msaaFrameBuffer;
  47547. }
  47548. if ( renderContextData.msaaRenderbuffers ) {
  47549. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  47550. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  47551. }
  47552. delete renderContextData.msaaRenderbuffers;
  47553. }
  47554. }
  47555. }
  47556. /**
  47557. * Destroys the GPU data for the given texture object.
  47558. *
  47559. * @param {Texture} texture - The texture.
  47560. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47561. */
  47562. destroyTexture( texture, isDefaultTexture = false ) {
  47563. const { gl, backend } = this;
  47564. const { textureGPU, renderTarget } = backend.get( texture );
  47565. this.deallocateRenderBuffers( renderTarget );
  47566. if ( isDefaultTexture === false ) {
  47567. gl.deleteTexture( textureGPU );
  47568. }
  47569. backend.delete( texture );
  47570. }
  47571. /**
  47572. * Copies data of the given source texture to the given destination texture.
  47573. *
  47574. * @param {Texture} srcTexture - The source texture.
  47575. * @param {Texture} dstTexture - The destination texture.
  47576. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  47577. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  47578. * @param {number} [srcLevel=0] - The source mip level to copy from.
  47579. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  47580. */
  47581. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  47582. const { gl, backend } = this;
  47583. const { state } = this.backend;
  47584. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  47585. state.bindTexture( glTextureType, dstTextureGPU );
  47586. // gather the necessary dimensions to copy
  47587. let width, height, depth, minX, minY, minZ;
  47588. let dstX, dstY, dstZ;
  47589. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  47590. if ( srcRegion !== null ) {
  47591. width = srcRegion.max.x - srcRegion.min.x;
  47592. height = srcRegion.max.y - srcRegion.min.y;
  47593. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  47594. minX = srcRegion.min.x;
  47595. minY = srcRegion.min.y;
  47596. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  47597. } else {
  47598. const levelScale = Math.pow( 2, - srcLevel );
  47599. width = Math.floor( image.width * levelScale );
  47600. height = Math.floor( image.height * levelScale );
  47601. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  47602. depth = image.depth;
  47603. } else if ( srcTexture.isData3DTexture ) {
  47604. depth = Math.floor( image.depth * levelScale );
  47605. } else {
  47606. depth = 1;
  47607. }
  47608. minX = 0;
  47609. minY = 0;
  47610. minZ = 0;
  47611. }
  47612. if ( dstPosition !== null ) {
  47613. dstX = dstPosition.x;
  47614. dstY = dstPosition.y;
  47615. dstZ = dstPosition.z;
  47616. } else {
  47617. dstX = 0;
  47618. dstY = 0;
  47619. dstZ = 0;
  47620. }
  47621. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  47622. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  47623. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  47624. // used for copying data from cpu
  47625. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  47626. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  47627. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  47628. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  47629. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  47630. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  47631. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  47632. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  47633. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  47634. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  47635. // set up the src texture
  47636. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  47637. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  47638. if ( srcTexture.isDepthTexture ) {
  47639. const srcTextureData = backend.get( srcTexture );
  47640. const dstTextureData = backend.get( dstTexture );
  47641. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  47642. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  47643. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  47644. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  47645. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  47646. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  47647. for ( let i = 0; i < depth; i ++ ) {
  47648. // if the source or destination are a 3d target then a layer needs to be bound
  47649. if ( isSrc3D ) {
  47650. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47651. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47652. }
  47653. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  47654. }
  47655. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47656. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47657. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  47658. // get the appropriate frame buffers
  47659. const srcTextureData = backend.get( srcTexture );
  47660. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  47661. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  47662. // bind the frame buffer targets
  47663. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  47664. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  47665. for ( let i = 0; i < depth; i ++ ) {
  47666. // assign the correct layers and mip maps to the frame buffers
  47667. if ( isSrc3D ) {
  47668. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47669. } else {
  47670. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  47671. }
  47672. if ( isDst3D ) {
  47673. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47674. } else {
  47675. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  47676. }
  47677. // copy the data using the fastest function that can achieve the copy
  47678. if ( srcLevel !== 0 ) {
  47679. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  47680. } else if ( isDst3D ) {
  47681. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  47682. } else {
  47683. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  47684. }
  47685. }
  47686. // unbind read, draw buffers
  47687. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47688. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47689. } else {
  47690. if ( isDst3D ) {
  47691. // copy data into the 3d texture
  47692. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  47693. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  47694. } else if ( dstTexture.isCompressedArrayTexture ) {
  47695. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  47696. } else {
  47697. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  47698. }
  47699. } else {
  47700. // copy data into the 2d texture
  47701. if ( srcTexture.isDataTexture ) {
  47702. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  47703. } else if ( srcTexture.isCompressedTexture ) {
  47704. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  47705. } else {
  47706. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  47707. }
  47708. }
  47709. }
  47710. // reset values
  47711. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  47712. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  47713. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  47714. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  47715. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  47716. // Generate mipmaps only when copying level 0
  47717. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  47718. gl.generateMipmap( glTextureType );
  47719. }
  47720. state.unbindTexture();
  47721. }
  47722. /**
  47723. * Copies the current bound framebuffer to the given texture.
  47724. *
  47725. * @param {Texture} texture - The destination texture.
  47726. * @param {RenderContext} renderContext - The render context.
  47727. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47728. */
  47729. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  47730. const { gl } = this;
  47731. const { state } = this.backend;
  47732. const { textureGPU } = this.backend.get( texture );
  47733. const { x, y, z: width, w: height } = rectangle;
  47734. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  47735. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  47736. if ( requireDrawFrameBuffer ) {
  47737. const partial = ( x !== 0 || y !== 0 );
  47738. let mask;
  47739. let attachment;
  47740. if ( texture.isDepthTexture === true ) {
  47741. mask = gl.DEPTH_BUFFER_BIT;
  47742. attachment = gl.DEPTH_ATTACHMENT;
  47743. if ( renderContext.stencil ) {
  47744. mask |= gl.STENCIL_BUFFER_BIT;
  47745. }
  47746. } else {
  47747. mask = gl.COLOR_BUFFER_BIT;
  47748. attachment = gl.COLOR_ATTACHMENT0;
  47749. }
  47750. if ( partial ) {
  47751. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  47752. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  47753. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  47754. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47755. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  47756. const flippedY = srcHeight - y - height;
  47757. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  47758. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  47759. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  47760. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  47761. state.unbindTexture();
  47762. } else {
  47763. const fb = gl.createFramebuffer();
  47764. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47765. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  47766. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  47767. gl.deleteFramebuffer( fb );
  47768. }
  47769. } else {
  47770. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  47771. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  47772. state.unbindTexture();
  47773. }
  47774. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  47775. this.backend._setFramebuffer( renderContext );
  47776. }
  47777. /**
  47778. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  47779. *
  47780. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  47781. * @param {RenderContext} renderContext - The render context.
  47782. * @param {number} samples - The MSAA sample count.
  47783. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  47784. */
  47785. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  47786. const { gl } = this;
  47787. const renderTarget = renderContext.renderTarget;
  47788. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  47789. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  47790. if ( depthBuffer && ! stencilBuffer ) {
  47791. let glInternalFormat = gl.DEPTH_COMPONENT24;
  47792. if ( useMultisampledRTT === true ) {
  47793. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  47794. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  47795. } else if ( samples > 0 ) {
  47796. if ( depthTexture && depthTexture.isDepthTexture ) {
  47797. if ( depthTexture.type === gl.FLOAT ) {
  47798. glInternalFormat = gl.DEPTH_COMPONENT32F;
  47799. }
  47800. }
  47801. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  47802. } else {
  47803. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  47804. }
  47805. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  47806. } else if ( depthBuffer && stencilBuffer ) {
  47807. if ( samples > 0 ) {
  47808. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  47809. } else {
  47810. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  47811. }
  47812. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  47813. }
  47814. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  47815. }
  47816. /**
  47817. * Returns texture data as a typed array.
  47818. *
  47819. * @async
  47820. * @param {Texture} texture - The texture to copy.
  47821. * @param {number} x - The x coordinate of the copy origin.
  47822. * @param {number} y - The y coordinate of the copy origin.
  47823. * @param {number} width - The width of the copy.
  47824. * @param {number} height - The height of the copy.
  47825. * @param {number} faceIndex - The face index.
  47826. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47827. */
  47828. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47829. const { backend, gl } = this;
  47830. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  47831. const fb = gl.createFramebuffer();
  47832. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  47833. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  47834. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  47835. const typedArrayType = this._getTypedArrayType( glType );
  47836. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  47837. const elementCount = width * height;
  47838. const byteLength = elementCount * bytesPerTexel;
  47839. const buffer = gl.createBuffer();
  47840. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  47841. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  47842. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  47843. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  47844. await backend.utils._clientWaitAsync();
  47845. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  47846. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  47847. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  47848. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  47849. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47850. gl.deleteFramebuffer( fb );
  47851. return dstBuffer;
  47852. }
  47853. /**
  47854. * Returns the corresponding typed array type for the given WebGL data type.
  47855. *
  47856. * @private
  47857. * @param {GLenum} glType - The WebGL data type.
  47858. * @return {TypedArray.constructor} The typed array type.
  47859. */
  47860. _getTypedArrayType( glType ) {
  47861. const { gl } = this;
  47862. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  47863. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  47864. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  47865. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  47866. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  47867. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  47868. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  47869. if ( glType === gl.FLOAT ) return Float32Array;
  47870. throw new Error( `Unsupported WebGL type: ${glType}` );
  47871. }
  47872. /**
  47873. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  47874. *
  47875. * @private
  47876. * @param {GLenum} glType - The WebGL data type.
  47877. * @param {GLenum} glFormat - The WebGL texture format.
  47878. * @return {number} The bytes-per-texel.
  47879. */
  47880. _getBytesPerTexel( glType, glFormat ) {
  47881. const { gl } = this;
  47882. let bytesPerComponent = 0;
  47883. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  47884. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  47885. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  47886. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  47887. glType === gl.UNSIGNED_SHORT ||
  47888. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  47889. if ( glType === gl.UNSIGNED_INT ||
  47890. glType === gl.FLOAT ) bytesPerComponent = 4;
  47891. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  47892. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  47893. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  47894. }
  47895. /**
  47896. * Frees the internal resources.
  47897. */
  47898. dispose() {
  47899. const { gl } = this;
  47900. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  47901. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  47902. }
  47903. }
  47904. function getImage( source ) {
  47905. if ( source.isDataTexture ) {
  47906. return source.image.data;
  47907. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  47908. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  47909. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  47910. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  47911. return source;
  47912. }
  47913. return source.data;
  47914. }
  47915. /**
  47916. * A WebGL 2 backend utility module for managing extensions.
  47917. *
  47918. * @private
  47919. */
  47920. class WebGLExtensions {
  47921. /**
  47922. * Constructs a new utility object.
  47923. *
  47924. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47925. */
  47926. constructor( backend ) {
  47927. /**
  47928. * A reference to the WebGL 2 backend.
  47929. *
  47930. * @type {WebGLBackend}
  47931. */
  47932. this.backend = backend;
  47933. /**
  47934. * A reference to the rendering context.
  47935. *
  47936. * @type {WebGL2RenderingContext}
  47937. */
  47938. this.gl = this.backend.gl;
  47939. /**
  47940. * A list with all the supported WebGL extensions.
  47941. *
  47942. * @type {Array<string>}
  47943. */
  47944. this.availableExtensions = this.gl.getSupportedExtensions();
  47945. /**
  47946. * A dictionary with requested WebGL extensions.
  47947. * The key is the name of the extension, the value
  47948. * the requested extension object.
  47949. *
  47950. * @type {Object<string,Object>}
  47951. */
  47952. this.extensions = {};
  47953. }
  47954. /**
  47955. * Returns the extension object for the given extension name.
  47956. *
  47957. * @param {string} name - The extension name.
  47958. * @return {Object} The extension object.
  47959. */
  47960. get( name ) {
  47961. let extension = this.extensions[ name ];
  47962. if ( extension === undefined ) {
  47963. extension = this.gl.getExtension( name );
  47964. this.extensions[ name ] = extension;
  47965. }
  47966. return extension;
  47967. }
  47968. /**
  47969. * Returns `true` if the requested extension is available.
  47970. *
  47971. * @param {string} name - The extension name.
  47972. * @return {boolean} Whether the given extension is available or not.
  47973. */
  47974. has( name ) {
  47975. return this.availableExtensions.includes( name );
  47976. }
  47977. }
  47978. /**
  47979. * A WebGL 2 backend utility module for managing the device's capabilities.
  47980. *
  47981. * @private
  47982. */
  47983. class WebGLCapabilities {
  47984. /**
  47985. * Constructs a new utility object.
  47986. *
  47987. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47988. */
  47989. constructor( backend ) {
  47990. /**
  47991. * A reference to the WebGL 2 backend.
  47992. *
  47993. * @type {WebGLBackend}
  47994. */
  47995. this.backend = backend;
  47996. /**
  47997. * This value holds the cached max anisotropy value.
  47998. *
  47999. * @type {?number}
  48000. * @default null
  48001. */
  48002. this.maxAnisotropy = null;
  48003. }
  48004. /**
  48005. * Returns the maximum anisotropy texture filtering value. This value
  48006. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  48007. * WebGL extension.
  48008. *
  48009. * @return {number} The maximum anisotropy texture filtering value.
  48010. */
  48011. getMaxAnisotropy() {
  48012. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  48013. const gl = this.backend.gl;
  48014. const extensions = this.backend.extensions;
  48015. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  48016. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  48017. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  48018. } else {
  48019. this.maxAnisotropy = 0;
  48020. }
  48021. return this.maxAnisotropy;
  48022. }
  48023. }
  48024. const GLFeatureName = {
  48025. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  48026. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  48027. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  48028. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  48029. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  48030. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  48031. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  48032. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  48033. 'OVR_multiview2': 'OVR_multiview2'
  48034. };
  48035. class WebGLBufferRenderer {
  48036. constructor( backend ) {
  48037. this.gl = backend.gl;
  48038. this.extensions = backend.extensions;
  48039. this.info = backend.renderer.info;
  48040. this.mode = null;
  48041. this.index = 0;
  48042. this.type = null;
  48043. this.object = null;
  48044. }
  48045. render( start, count ) {
  48046. const { gl, mode, object, type, info, index } = this;
  48047. if ( index !== 0 ) {
  48048. gl.drawElements( mode, count, type, start );
  48049. } else {
  48050. gl.drawArrays( mode, start, count );
  48051. }
  48052. info.update( object, count, 1 );
  48053. }
  48054. renderInstances( start, count, primcount ) {
  48055. const { gl, mode, type, index, object, info } = this;
  48056. if ( primcount === 0 ) return;
  48057. if ( index !== 0 ) {
  48058. gl.drawElementsInstanced( mode, count, type, start, primcount );
  48059. } else {
  48060. gl.drawArraysInstanced( mode, start, count, primcount );
  48061. }
  48062. info.update( object, count, primcount );
  48063. }
  48064. renderMultiDraw( starts, counts, drawCount ) {
  48065. const { extensions, mode, object, info } = this;
  48066. if ( drawCount === 0 ) return;
  48067. const extension = extensions.get( 'WEBGL_multi_draw' );
  48068. if ( extension === null ) {
  48069. for ( let i = 0; i < drawCount; i ++ ) {
  48070. this.render( starts[ i ], counts[ i ] );
  48071. }
  48072. } else {
  48073. if ( this.index !== 0 ) {
  48074. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  48075. } else {
  48076. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  48077. }
  48078. let elementCount = 0;
  48079. for ( let i = 0; i < drawCount; i ++ ) {
  48080. elementCount += counts[ i ];
  48081. }
  48082. info.update( object, elementCount, 1 );
  48083. }
  48084. }
  48085. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  48086. const { extensions, mode, object, info } = this;
  48087. if ( drawCount === 0 ) return;
  48088. const extension = extensions.get( 'WEBGL_multi_draw' );
  48089. if ( extension === null ) {
  48090. for ( let i = 0; i < drawCount; i ++ ) {
  48091. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  48092. }
  48093. } else {
  48094. if ( this.index !== 0 ) {
  48095. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  48096. } else {
  48097. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  48098. }
  48099. let elementCount = 0;
  48100. for ( let i = 0; i < drawCount; i ++ ) {
  48101. elementCount += counts[ i ] * primcount[ i ];
  48102. }
  48103. info.update( object, elementCount, 1 );
  48104. }
  48105. }
  48106. //
  48107. }
  48108. /**
  48109. * Abstract base class of a timestamp query pool.
  48110. *
  48111. * @abstract
  48112. */
  48113. class TimestampQueryPool {
  48114. /**
  48115. * Creates a new timestamp query pool.
  48116. *
  48117. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  48118. */
  48119. constructor( maxQueries = 256 ) {
  48120. /**
  48121. * Whether to track timestamps or not.
  48122. *
  48123. * @type {boolean}
  48124. * @default true
  48125. */
  48126. this.trackTimestamp = true;
  48127. /**
  48128. * Maximum number of queries this pool can hold.
  48129. *
  48130. * @type {number}
  48131. * @default 256
  48132. */
  48133. this.maxQueries = maxQueries;
  48134. /**
  48135. * How many queries allocated so far.
  48136. *
  48137. * @type {number}
  48138. * @default 0
  48139. */
  48140. this.currentQueryIndex = 0;
  48141. /**
  48142. * Tracks offsets for different contexts.
  48143. *
  48144. * @type {Map<string, number>}
  48145. */
  48146. this.queryOffsets = new Map();
  48147. /**
  48148. * Whether the pool has been disposed or not.
  48149. *
  48150. * @type {boolean}
  48151. * @default false
  48152. */
  48153. this.isDisposed = false;
  48154. /**
  48155. * The total frame duration until the next update.
  48156. *
  48157. * @type {number}
  48158. * @default 0
  48159. */
  48160. this.lastValue = 0;
  48161. /**
  48162. * Stores all timestamp frames.
  48163. *
  48164. * @type {Array<number>}
  48165. */
  48166. this.frames = [];
  48167. /**
  48168. * This property is used to avoid multiple concurrent resolve operations.
  48169. * The WebGL backend uses it as a boolean flag. In context of WebGPU, it holds
  48170. * the promise of the current resolve operation.
  48171. *
  48172. * @type {boolean|Promise<number>}
  48173. * @default false
  48174. */
  48175. this.pendingResolve = false;
  48176. /**
  48177. * Stores the latest timestamp for each render context.
  48178. *
  48179. * @type {Map<string, number>}
  48180. */
  48181. this.timestamps = new Map();
  48182. }
  48183. /**
  48184. * Returns all timestamp frames.
  48185. *
  48186. * @return {Array<number>} The timestamp frames.
  48187. */
  48188. getTimestampFrames() {
  48189. return this.frames;
  48190. }
  48191. /**
  48192. * Returns the timestamp for a given render context.
  48193. *
  48194. * @param {string} uid - A unique identifier for the render context.
  48195. * @return {?number} The timestamp, or undefined if not available.
  48196. */
  48197. getTimestamp( uid ) {
  48198. let timestamp = this.timestamps.get( uid );
  48199. if ( timestamp === undefined ) {
  48200. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  48201. timestamp = 0;
  48202. }
  48203. return timestamp;
  48204. }
  48205. /**
  48206. * Returns whether a timestamp is available for a given render context.
  48207. *
  48208. * @param {string} uid - A unique identifier for the render context.
  48209. * @return {boolean} True if a timestamp is available, false otherwise.
  48210. */
  48211. hasTimestamp( uid ) {
  48212. return this.timestamps.has( uid );
  48213. }
  48214. /**
  48215. * Allocate queries for a specific uid.
  48216. *
  48217. * @abstract
  48218. * @param {string} uid - A unique identifier for the render context.
  48219. * @param {number} frameId - The current frame identifier.
  48220. * @returns {?number}
  48221. */
  48222. allocateQueriesForContext( /* uid, frameId */ ) {}
  48223. /**
  48224. * Resolve all timestamps and return data (or process them).
  48225. *
  48226. * @abstract
  48227. * @async
  48228. * @returns {Promise<number>|number} The resolved timestamp value.
  48229. */
  48230. async resolveQueriesAsync() {}
  48231. /**
  48232. * Dispose of the query pool.
  48233. *
  48234. * @abstract
  48235. */
  48236. dispose() {}
  48237. }
  48238. /**
  48239. * Manages a pool of WebGL timestamp queries for performance measurement.
  48240. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  48241. *
  48242. * @augments TimestampQueryPool
  48243. */
  48244. class WebGLTimestampQueryPool extends TimestampQueryPool {
  48245. /**
  48246. * Creates a new WebGL timestamp query pool.
  48247. *
  48248. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  48249. * @param {string} type - The type identifier for this query pool.
  48250. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  48251. */
  48252. constructor( gl, type, maxQueries = 2048 ) {
  48253. super( maxQueries );
  48254. this.gl = gl;
  48255. this.type = type;
  48256. // Check for timer query extensions
  48257. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  48258. gl.getExtension( 'EXT_disjoint_timer_query' );
  48259. if ( ! this.ext ) {
  48260. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  48261. this.trackTimestamp = false;
  48262. return;
  48263. }
  48264. // Create query objects
  48265. this.queries = [];
  48266. for ( let i = 0; i < this.maxQueries; i ++ ) {
  48267. this.queries.push( gl.createQuery() );
  48268. }
  48269. this.activeQuery = null;
  48270. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  48271. }
  48272. /**
  48273. * Allocates a pair of queries for a given render context.
  48274. *
  48275. * @param {string} uid - A unique identifier for the render context.
  48276. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  48277. */
  48278. allocateQueriesForContext( uid ) {
  48279. if ( ! this.trackTimestamp ) return null;
  48280. // Check if we have enough space for a new query pair
  48281. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  48282. 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() } ).` );
  48283. return null;
  48284. }
  48285. const baseOffset = this.currentQueryIndex;
  48286. this.currentQueryIndex += 2;
  48287. // Initialize query states
  48288. this.queryStates.set( baseOffset, 'inactive' );
  48289. this.queryOffsets.set( uid, baseOffset );
  48290. return baseOffset;
  48291. }
  48292. /**
  48293. * Begins a timestamp query for the specified render context.
  48294. *
  48295. * @param {string} uid - A unique identifier for the render context.
  48296. */
  48297. beginQuery( uid ) {
  48298. if ( ! this.trackTimestamp || this.isDisposed ) {
  48299. return;
  48300. }
  48301. const baseOffset = this.queryOffsets.get( uid );
  48302. if ( baseOffset == null ) {
  48303. return;
  48304. }
  48305. // Don't start a new query if there's an active one
  48306. if ( this.activeQuery !== null ) {
  48307. return;
  48308. }
  48309. const query = this.queries[ baseOffset ];
  48310. if ( ! query ) {
  48311. return;
  48312. }
  48313. try {
  48314. // Only begin if query is inactive
  48315. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  48316. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  48317. this.activeQuery = baseOffset;
  48318. this.queryStates.set( baseOffset, 'started' );
  48319. }
  48320. } catch ( e ) {
  48321. error( 'Error in beginQuery:', e );
  48322. this.activeQuery = null;
  48323. this.queryStates.set( baseOffset, 'inactive' );
  48324. }
  48325. }
  48326. /**
  48327. * Ends the active timestamp query for the specified render context.
  48328. *
  48329. * @param {string} uid - A unique identifier for the render context.
  48330. */
  48331. endQuery( uid ) {
  48332. if ( ! this.trackTimestamp || this.isDisposed ) {
  48333. return;
  48334. }
  48335. const baseOffset = this.queryOffsets.get( uid );
  48336. if ( baseOffset == null ) {
  48337. return;
  48338. }
  48339. // Only end if this is the active query
  48340. if ( this.activeQuery !== baseOffset ) {
  48341. return;
  48342. }
  48343. try {
  48344. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  48345. this.queryStates.set( baseOffset, 'ended' );
  48346. this.activeQuery = null;
  48347. } catch ( e ) {
  48348. error( 'Error in endQuery:', e );
  48349. // Reset state on error
  48350. this.queryStates.set( baseOffset, 'inactive' );
  48351. this.activeQuery = null;
  48352. }
  48353. }
  48354. /**
  48355. * Asynchronously resolves all completed queries and returns the total duration.
  48356. *
  48357. * @async
  48358. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  48359. */
  48360. async resolveQueriesAsync() {
  48361. if ( ! this.trackTimestamp || this.pendingResolve ) {
  48362. return this.lastValue;
  48363. }
  48364. this.pendingResolve = true;
  48365. try {
  48366. // Wait for all ended queries to complete
  48367. const resolvePromises = new Map();
  48368. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  48369. const state = this.queryStates.get( baseOffset );
  48370. if ( state === 'ended' ) {
  48371. const query = this.queries[ baseOffset ];
  48372. resolvePromises.set( uid, this.resolveQuery( query ) );
  48373. }
  48374. }
  48375. if ( resolvePromises.size === 0 ) {
  48376. return this.lastValue;
  48377. }
  48378. //
  48379. const framesDuration = {};
  48380. const frames = [];
  48381. for ( const [ uid, promise ] of resolvePromises ) {
  48382. const match = uid.match( /^(.*):f(\d+)$/ );
  48383. const frame = parseInt( match[ 2 ] );
  48384. if ( frames.includes( frame ) === false ) {
  48385. frames.push( frame );
  48386. }
  48387. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  48388. const duration = await promise;
  48389. this.timestamps.set( uid, duration );
  48390. framesDuration[ frame ] += duration;
  48391. }
  48392. // Return the total duration of the last frame
  48393. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  48394. // Store the last valid result
  48395. this.lastValue = totalDuration;
  48396. this.frames = frames;
  48397. // Reset states
  48398. this.currentQueryIndex = 0;
  48399. this.queryOffsets.clear();
  48400. this.queryStates.clear();
  48401. this.activeQuery = null;
  48402. return totalDuration;
  48403. } catch ( e ) {
  48404. error( 'Error resolving queries:', e );
  48405. return this.lastValue;
  48406. } finally {
  48407. this.pendingResolve = false;
  48408. }
  48409. }
  48410. /**
  48411. * Resolves a single query, checking for completion and disjoint operation.
  48412. *
  48413. * @async
  48414. * @param {WebGLQuery} query - The query object to resolve.
  48415. * @returns {Promise<number>} The elapsed time in milliseconds.
  48416. */
  48417. async resolveQuery( query ) {
  48418. return new Promise( ( resolve ) => {
  48419. if ( this.isDisposed ) {
  48420. resolve( this.lastValue );
  48421. return;
  48422. }
  48423. let timeoutId;
  48424. let isResolved = false;
  48425. const cleanup = () => {
  48426. if ( timeoutId ) {
  48427. clearTimeout( timeoutId );
  48428. timeoutId = null;
  48429. }
  48430. };
  48431. const finalizeResolution = ( value ) => {
  48432. if ( ! isResolved ) {
  48433. isResolved = true;
  48434. cleanup();
  48435. resolve( value );
  48436. }
  48437. };
  48438. const checkQuery = () => {
  48439. if ( this.isDisposed ) {
  48440. finalizeResolution( this.lastValue );
  48441. return;
  48442. }
  48443. try {
  48444. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  48445. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  48446. if ( disjoint ) {
  48447. finalizeResolution( this.lastValue );
  48448. return;
  48449. }
  48450. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  48451. if ( ! available ) {
  48452. timeoutId = setTimeout( checkQuery, 1 );
  48453. return;
  48454. }
  48455. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  48456. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  48457. } catch ( e ) {
  48458. error( 'Error checking query:', e );
  48459. resolve( this.lastValue );
  48460. }
  48461. };
  48462. checkQuery();
  48463. } );
  48464. }
  48465. /**
  48466. * Releases all resources held by this query pool.
  48467. * This includes deleting all query objects and clearing internal state.
  48468. */
  48469. dispose() {
  48470. if ( this.isDisposed ) {
  48471. return;
  48472. }
  48473. this.isDisposed = true;
  48474. if ( ! this.trackTimestamp ) return;
  48475. for ( const query of this.queries ) {
  48476. this.gl.deleteQuery( query );
  48477. }
  48478. this.queries = [];
  48479. this.queryStates.clear();
  48480. this.queryOffsets.clear();
  48481. this.lastValue = 0;
  48482. this.activeQuery = null;
  48483. }
  48484. }
  48485. /**
  48486. * A backend implementation targeting WebGL 2.
  48487. *
  48488. * @private
  48489. * @augments Backend
  48490. */
  48491. class WebGLBackend extends Backend {
  48492. /**
  48493. * WebGLBackend options.
  48494. *
  48495. * @typedef {Object} WebGLBackend~Options
  48496. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  48497. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  48498. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  48499. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  48500. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  48501. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  48502. * @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.
  48503. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  48504. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  48505. */
  48506. /**
  48507. * Constructs a new WebGPU backend.
  48508. *
  48509. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  48510. */
  48511. constructor( parameters = {} ) {
  48512. super( parameters );
  48513. /**
  48514. * This flag can be used for type testing.
  48515. *
  48516. * @type {boolean}
  48517. * @readonly
  48518. * @default true
  48519. */
  48520. this.isWebGLBackend = true;
  48521. /**
  48522. * A reference to a backend module holding shader attribute-related
  48523. * utility functions.
  48524. *
  48525. * @type {?WebGLAttributeUtils}
  48526. * @default null
  48527. */
  48528. this.attributeUtils = null;
  48529. /**
  48530. * A reference to a backend module holding extension-related
  48531. * utility functions.
  48532. *
  48533. * @type {?WebGLExtensions}
  48534. * @default null
  48535. */
  48536. this.extensions = null;
  48537. /**
  48538. * A reference to a backend module holding capability-related
  48539. * utility functions.
  48540. *
  48541. * @type {?WebGLCapabilities}
  48542. * @default null
  48543. */
  48544. this.capabilities = null;
  48545. /**
  48546. * A reference to a backend module holding texture-related
  48547. * utility functions.
  48548. *
  48549. * @type {?WebGLTextureUtils}
  48550. * @default null
  48551. */
  48552. this.textureUtils = null;
  48553. /**
  48554. * A reference to a backend module holding renderer-related
  48555. * utility functions.
  48556. *
  48557. * @type {?WebGLBufferRenderer}
  48558. * @default null
  48559. */
  48560. this.bufferRenderer = null;
  48561. /**
  48562. * A reference to the rendering context.
  48563. *
  48564. * @type {?WebGL2RenderingContext}
  48565. * @default null
  48566. */
  48567. this.gl = null;
  48568. /**
  48569. * A reference to a backend module holding state-related
  48570. * utility functions.
  48571. *
  48572. * @type {?WebGLState}
  48573. * @default null
  48574. */
  48575. this.state = null;
  48576. /**
  48577. * A reference to a backend module holding common
  48578. * utility functions.
  48579. *
  48580. * @type {?WebGLUtils}
  48581. * @default null
  48582. */
  48583. this.utils = null;
  48584. /**
  48585. * Dictionary for caching VAOs.
  48586. *
  48587. * @type {Object<string,WebGLVertexArrayObject>}
  48588. */
  48589. this.vaoCache = {};
  48590. /**
  48591. * Dictionary for caching transform feedback objects.
  48592. *
  48593. * @type {Object<string,WebGLTransformFeedback>}
  48594. */
  48595. this.transformFeedbackCache = {};
  48596. /**
  48597. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  48598. * Only relevant when using compute shaders.
  48599. *
  48600. * @type {boolean}
  48601. * @default false
  48602. */
  48603. this.discard = false;
  48604. /**
  48605. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  48606. * device does not support the extension.
  48607. *
  48608. * @type {?EXTDisjointTimerQueryWebGL2}
  48609. * @default null
  48610. */
  48611. this.disjoint = null;
  48612. /**
  48613. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  48614. * device does not support the extension.
  48615. *
  48616. * @type {?KHRParallelShaderCompile}
  48617. * @default null
  48618. */
  48619. this.parallel = null;
  48620. /**
  48621. * A reference to the current render context.
  48622. *
  48623. * @private
  48624. * @type {RenderContext}
  48625. * @default null
  48626. */
  48627. this._currentContext = null;
  48628. /**
  48629. * A unique collection of bindings.
  48630. *
  48631. * @private
  48632. * @type {WeakSet<Array<BindGroup>>}
  48633. */
  48634. this._knownBindings = new WeakSet();
  48635. /**
  48636. * Whether the device supports framebuffers invalidation or not.
  48637. *
  48638. * @private
  48639. * @type {boolean}
  48640. */
  48641. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  48642. /**
  48643. * The target framebuffer when rendering with
  48644. * the WebXR device API.
  48645. *
  48646. * @private
  48647. * @type {?WebGLFramebuffer}
  48648. * @default null
  48649. */
  48650. this._xrFramebuffer = null;
  48651. }
  48652. /**
  48653. * Initializes the backend so it is ready for usage.
  48654. *
  48655. * @param {Renderer} renderer - The renderer.
  48656. */
  48657. init( renderer ) {
  48658. super.init( renderer );
  48659. //
  48660. const parameters = this.parameters;
  48661. const contextAttributes = {
  48662. antialias: renderer.currentSamples > 0,
  48663. alpha: true, // always true for performance reasons
  48664. depth: renderer.depth,
  48665. stencil: renderer.stencil
  48666. };
  48667. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  48668. function onContextLost( event ) {
  48669. event.preventDefault();
  48670. const contextLossInfo = {
  48671. api: 'WebGL',
  48672. message: event.statusMessage || 'Unknown reason',
  48673. reason: null,
  48674. originalEvent: event
  48675. };
  48676. renderer.onDeviceLost( contextLossInfo );
  48677. }
  48678. this._onContextLost = onContextLost;
  48679. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  48680. this.gl = glContext;
  48681. this.extensions = new WebGLExtensions( this );
  48682. this.capabilities = new WebGLCapabilities( this );
  48683. this.attributeUtils = new WebGLAttributeUtils( this );
  48684. this.textureUtils = new WebGLTextureUtils( this );
  48685. this.bufferRenderer = new WebGLBufferRenderer( this );
  48686. this.state = new WebGLState( this );
  48687. this.utils = new WebGLUtils( this );
  48688. this.extensions.get( 'EXT_color_buffer_float' );
  48689. this.extensions.get( 'WEBGL_clip_cull_distance' );
  48690. this.extensions.get( 'OES_texture_float_linear' );
  48691. this.extensions.get( 'EXT_color_buffer_half_float' );
  48692. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48693. this.extensions.get( 'WEBGL_render_shared_exponent' );
  48694. this.extensions.get( 'WEBGL_multi_draw' );
  48695. this.extensions.get( 'OVR_multiview2' );
  48696. this.extensions.get( 'EXT_clip_control' );
  48697. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  48698. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  48699. this.drawBuffersIndexedExt = this.extensions.get( 'OES_draw_buffers_indexed' );
  48700. if ( parameters.reversedDepthBuffer === true && this.extensions.has( 'EXT_clip_control' ) ) {
  48701. this.state.setReversedDepth( true );
  48702. }
  48703. }
  48704. /**
  48705. * The coordinate system of the backend.
  48706. *
  48707. * @type {number}
  48708. * @readonly
  48709. */
  48710. get coordinateSystem() {
  48711. return WebGLCoordinateSystem;
  48712. }
  48713. /**
  48714. * This method performs a readback operation by moving buffer data from
  48715. * a storage buffer attribute from the GPU to the CPU.
  48716. *
  48717. * @async
  48718. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48719. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48720. */
  48721. async getArrayBufferAsync( attribute ) {
  48722. return await this.attributeUtils.getArrayBufferAsync( attribute );
  48723. }
  48724. /**
  48725. * Ensures the backend is XR compatible.
  48726. *
  48727. * @async
  48728. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  48729. */
  48730. async makeXRCompatible() {
  48731. const attributes = this.gl.getContextAttributes();
  48732. if ( attributes.xrCompatible !== true ) {
  48733. await this.gl.makeXRCompatible();
  48734. }
  48735. }
  48736. /**
  48737. * Sets the XR rendering destination.
  48738. *
  48739. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  48740. */
  48741. setXRTarget( xrFramebuffer ) {
  48742. this._xrFramebuffer = xrFramebuffer;
  48743. }
  48744. /**
  48745. * Configures the given XR render target with external textures.
  48746. *
  48747. * This method is only relevant when using the WebXR Layers API.
  48748. *
  48749. * @param {XRRenderTarget} renderTarget - The XR render target.
  48750. * @param {WebGLTexture} colorTexture - A native color texture.
  48751. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  48752. */
  48753. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  48754. const gl = this.gl;
  48755. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  48756. if ( depthTexture !== null ) {
  48757. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  48758. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  48759. // The multisample_render_to_texture extension doesn't work properly if there
  48760. // are midframe flushes and an external depth texture.
  48761. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  48762. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  48763. }
  48764. renderTarget._autoAllocateDepthBuffer = false;
  48765. }
  48766. }
  48767. /**
  48768. * Inits a time stamp query for the given render context.
  48769. *
  48770. * @param {string} type - The type of the timestamp query.
  48771. * @param {string} uid - A unique identifier for the timestamp query.
  48772. */
  48773. initTimestampQuery( type, uid ) {
  48774. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  48775. if ( ! this.timestampQueryPool[ type ] ) {
  48776. // TODO: Variable maxQueries?
  48777. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  48778. }
  48779. const timestampQueryPool = this.timestampQueryPool[ type ];
  48780. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  48781. if ( baseOffset !== null ) {
  48782. timestampQueryPool.beginQuery( uid );
  48783. }
  48784. }
  48785. // timestamp utils
  48786. /**
  48787. * Prepares the timestamp buffer.
  48788. *
  48789. * @param {string} type - The type of the timestamp query.
  48790. * @param {string} uid - A unique identifier for the timestamp query.
  48791. */
  48792. prepareTimestampBuffer( type, uid ) {
  48793. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  48794. const timestampQueryPool = this.timestampQueryPool[ type ];
  48795. timestampQueryPool.endQuery( uid );
  48796. }
  48797. /**
  48798. * Returns the backend's rendering context.
  48799. *
  48800. * @return {WebGL2RenderingContext} The rendering context.
  48801. */
  48802. getContext() {
  48803. return this.gl;
  48804. }
  48805. /**
  48806. * This method is executed at the beginning of a render call and prepares
  48807. * the WebGL state for upcoming render calls
  48808. *
  48809. * @param {RenderContext} renderContext - The render context.
  48810. */
  48811. beginRender( renderContext ) {
  48812. const { state } = this;
  48813. const renderContextData = this.get( renderContext );
  48814. //
  48815. if ( renderContext.viewport ) {
  48816. this.updateViewport( renderContext );
  48817. } else {
  48818. const { width, height } = this.getDrawingBufferSize();
  48819. state.viewport( 0, 0, width, height );
  48820. }
  48821. if ( renderContext.scissor ) {
  48822. this.updateScissor( renderContext );
  48823. } else {
  48824. const { width, height } = this.getDrawingBufferSize();
  48825. state.scissor( 0, 0, width, height );
  48826. }
  48827. //
  48828. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  48829. renderContextData.previousContext = this._currentContext;
  48830. this._currentContext = renderContext;
  48831. this._setFramebuffer( renderContext );
  48832. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  48833. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48834. if ( occlusionQueryCount > 0 ) {
  48835. // Get a reference to the array of objects with queries. The renderContextData property
  48836. // can be changed by another render pass before the async reading of all previous queries complete
  48837. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  48838. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  48839. renderContextData.lastOcclusionObject = null;
  48840. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  48841. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  48842. renderContextData.occlusionQueryIndex = 0;
  48843. }
  48844. }
  48845. /**
  48846. * This method is executed at the end of a render call and finalizes work
  48847. * after draw calls.
  48848. *
  48849. * @param {RenderContext} renderContext - The render context.
  48850. */
  48851. finishRender( renderContext ) {
  48852. const { gl, state } = this;
  48853. const renderContextData = this.get( renderContext );
  48854. const previousContext = renderContextData.previousContext;
  48855. state.resetVertexState();
  48856. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48857. if ( occlusionQueryCount > 0 ) {
  48858. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  48859. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  48860. }
  48861. this.resolveOccludedAsync( renderContext );
  48862. }
  48863. const textures = renderContext.textures;
  48864. if ( textures !== null ) {
  48865. for ( let i = 0; i < textures.length; i ++ ) {
  48866. const texture = textures[ i ];
  48867. if ( texture.generateMipmaps ) {
  48868. this.generateMipmaps( texture );
  48869. }
  48870. }
  48871. }
  48872. this._currentContext = previousContext;
  48873. this._resolveRenderTarget( renderContext );
  48874. if ( previousContext !== null ) {
  48875. this._setFramebuffer( previousContext );
  48876. if ( previousContext.viewport ) {
  48877. this.updateViewport( previousContext );
  48878. } else {
  48879. const { width, height } = this.getDrawingBufferSize();
  48880. state.viewport( 0, 0, width, height );
  48881. }
  48882. if ( previousContext.scissor ) {
  48883. this.updateScissor( previousContext );
  48884. } else {
  48885. const { width, height } = this.getDrawingBufferSize();
  48886. state.scissor( 0, 0, width, height );
  48887. }
  48888. }
  48889. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  48890. }
  48891. /**
  48892. * This method processes the result of occlusion queries and writes it
  48893. * into render context data.
  48894. *
  48895. * @async
  48896. * @param {RenderContext} renderContext - The render context.
  48897. */
  48898. resolveOccludedAsync( renderContext ) {
  48899. const renderContextData = this.get( renderContext );
  48900. // handle occlusion query results
  48901. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  48902. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  48903. const occluded = new WeakSet();
  48904. const { gl } = this;
  48905. renderContextData.currentOcclusionQueryObjects = null;
  48906. renderContextData.currentOcclusionQueries = null;
  48907. const check = () => {
  48908. let completed = 0;
  48909. // check all queries and requeue as appropriate
  48910. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  48911. const query = currentOcclusionQueries[ i ];
  48912. if ( query === null ) continue;
  48913. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  48914. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  48915. currentOcclusionQueries[ i ] = null;
  48916. gl.deleteQuery( query );
  48917. completed ++;
  48918. }
  48919. }
  48920. if ( completed < currentOcclusionQueries.length ) {
  48921. requestAnimationFrame( check );
  48922. } else {
  48923. renderContextData.occluded = occluded;
  48924. }
  48925. };
  48926. check();
  48927. }
  48928. }
  48929. /**
  48930. * Returns `true` if the given 3D object is fully occluded by other
  48931. * 3D objects in the scene.
  48932. *
  48933. * @param {RenderContext} renderContext - The render context.
  48934. * @param {Object3D} object - The 3D object to test.
  48935. * @return {boolean} Whether the 3D object is fully occluded or not.
  48936. */
  48937. isOccluded( renderContext, object ) {
  48938. const renderContextData = this.get( renderContext );
  48939. return renderContextData.occluded && renderContextData.occluded.has( object );
  48940. }
  48941. /**
  48942. * Updates the viewport with the values from the given render context.
  48943. *
  48944. * @param {RenderContext} renderContext - The render context.
  48945. */
  48946. updateViewport( renderContext ) {
  48947. const { state } = this;
  48948. const { x, y, width, height } = renderContext.viewportValue;
  48949. state.viewport( x, renderContext.height - height - y, width, height );
  48950. }
  48951. /**
  48952. * Updates the scissor with the values from the given render context.
  48953. *
  48954. * @param {RenderContext} renderContext - The render context.
  48955. */
  48956. updateScissor( renderContext ) {
  48957. const { state } = this;
  48958. const { x, y, width, height } = renderContext.scissorValue;
  48959. state.scissor( x, renderContext.height - height - y, width, height );
  48960. }
  48961. /**
  48962. * Defines the scissor test.
  48963. *
  48964. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  48965. */
  48966. setScissorTest( boolean ) {
  48967. const state = this.state;
  48968. state.setScissorTest( boolean );
  48969. }
  48970. /**
  48971. * Returns the clear color and alpha into a single
  48972. * color object.
  48973. *
  48974. * @return {Color4} The clear color.
  48975. */
  48976. getClearColor() {
  48977. const clearColor = super.getClearColor();
  48978. // Since the canvas is always created with alpha: true,
  48979. // WebGL must always premultiply the clear color.
  48980. clearColor.r *= clearColor.a;
  48981. clearColor.g *= clearColor.a;
  48982. clearColor.b *= clearColor.a;
  48983. return clearColor;
  48984. }
  48985. /**
  48986. * Performs a clear operation.
  48987. *
  48988. * @param {boolean} color - Whether the color buffer should be cleared or not.
  48989. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  48990. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  48991. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  48992. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  48993. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  48994. * or not. Only relevant for explicit clears.
  48995. */
  48996. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  48997. const { gl, renderer } = this;
  48998. if ( descriptor === null ) {
  48999. const clearColor = this.getClearColor();
  49000. descriptor = {
  49001. textures: null,
  49002. clearColorValue: clearColor
  49003. };
  49004. }
  49005. //
  49006. let clear = 0;
  49007. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  49008. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  49009. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  49010. if ( clear !== 0 ) {
  49011. let clearColor;
  49012. if ( descriptor.clearColorValue ) {
  49013. clearColor = descriptor.clearColorValue;
  49014. } else {
  49015. clearColor = this.getClearColor();
  49016. }
  49017. const clearDepth = renderer.getClearDepth();
  49018. const clearStencil = renderer.getClearStencil();
  49019. if ( depth ) this.state.setDepthMask( true );
  49020. if ( descriptor.textures === null ) {
  49021. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  49022. gl.clear( clear );
  49023. } else {
  49024. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  49025. if ( color ) {
  49026. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  49027. if ( i === 0 ) {
  49028. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  49029. } else {
  49030. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  49031. }
  49032. }
  49033. }
  49034. if ( depth && stencil ) {
  49035. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  49036. } else if ( depth ) {
  49037. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  49038. } else if ( stencil ) {
  49039. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  49040. }
  49041. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  49042. }
  49043. }
  49044. }
  49045. /**
  49046. * This method is executed at the beginning of a compute call and
  49047. * prepares the state for upcoming compute tasks.
  49048. *
  49049. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  49050. */
  49051. beginCompute( computeGroup ) {
  49052. const { state, gl } = this;
  49053. //
  49054. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  49055. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  49056. }
  49057. /**
  49058. * Executes a compute command for the given compute node.
  49059. *
  49060. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  49061. * @param {Node} computeNode - The compute node.
  49062. * @param {Array<BindGroup>} bindings - The bindings.
  49063. * @param {ComputePipeline} pipeline - The compute pipeline.
  49064. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  49065. */
  49066. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  49067. const { state, gl } = this;
  49068. if ( this.discard === false ) {
  49069. // required here to handle async behaviour of render.compute()
  49070. state.enable( gl.RASTERIZER_DISCARD );
  49071. this.discard = true;
  49072. }
  49073. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  49074. const vaoKey = this._getVaoKey( attributes );
  49075. const vaoGPU = this.vaoCache[ vaoKey ];
  49076. if ( vaoGPU === undefined ) {
  49077. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  49078. } else {
  49079. state.setVertexState( vaoGPU );
  49080. }
  49081. state.useProgram( programGPU );
  49082. this._bindUniforms( bindings );
  49083. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  49084. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  49085. gl.beginTransformFeedback( gl.POINTS );
  49086. count = ( count !== null ) ? count : computeNode.count;
  49087. if ( Array.isArray( count ) ) {
  49088. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  49089. count = count[ 0 ];
  49090. } else if ( count && typeof count === 'object' && count.isIndirectStorageBufferAttribute ) {
  49091. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute' );
  49092. count = computeNode.count;
  49093. }
  49094. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  49095. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  49096. } else {
  49097. gl.drawArrays( gl.POINTS, 0, count );
  49098. }
  49099. gl.endTransformFeedback();
  49100. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  49101. // switch active buffers
  49102. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  49103. const dualAttributeData = transformBuffers[ i ];
  49104. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  49105. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  49106. }
  49107. dualAttributeData.switchBuffers();
  49108. }
  49109. }
  49110. /**
  49111. * This method is executed at the end of a compute call and
  49112. * finalizes work after compute tasks.
  49113. *
  49114. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  49115. */
  49116. finishCompute( computeGroup ) {
  49117. const { state, gl } = this;
  49118. this.discard = false;
  49119. state.disable( gl.RASTERIZER_DISCARD );
  49120. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  49121. if ( this._currentContext ) {
  49122. this._setFramebuffer( this._currentContext );
  49123. }
  49124. }
  49125. /**
  49126. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  49127. *
  49128. * @param {RenderContext} renderContext - The render context.
  49129. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  49130. *
  49131. * @private
  49132. */
  49133. _isRenderCameraDepthArray( renderContext ) {
  49134. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  49135. }
  49136. /**
  49137. * Executes a draw command for the given render object.
  49138. *
  49139. * @param {RenderObject} renderObject - The render object to draw.
  49140. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  49141. */
  49142. draw( renderObject/*, info*/ ) {
  49143. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  49144. const { programGPU } = this.get( pipeline );
  49145. const { gl, state } = this;
  49146. const contextData = this.get( context );
  49147. const drawParams = renderObject.getDrawParameters();
  49148. if ( drawParams === null ) return;
  49149. //
  49150. this._bindUniforms( renderObject.getBindings() );
  49151. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  49152. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  49153. if ( context.mrt !== null && context.textures !== null ) {
  49154. state.setMRTBlending( context.textures, context.mrt, material );
  49155. }
  49156. state.useProgram( programGPU );
  49157. // vertex state
  49158. const attributes = renderObject.getAttributes();
  49159. const attributesData = this.get( attributes );
  49160. let vaoGPU = attributesData.vaoGPU;
  49161. if ( vaoGPU === undefined ) {
  49162. const vaoKey = this._getVaoKey( attributes );
  49163. vaoGPU = this.vaoCache[ vaoKey ];
  49164. if ( vaoGPU === undefined ) {
  49165. vaoGPU = this._createVao( attributes );
  49166. this.vaoCache[ vaoKey ] = vaoGPU;
  49167. attributesData.vaoGPU = vaoGPU;
  49168. }
  49169. }
  49170. const index = renderObject.getIndex();
  49171. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  49172. state.setVertexState( vaoGPU, indexGPU );
  49173. //
  49174. const lastObject = contextData.lastOcclusionObject;
  49175. if ( lastObject !== object && lastObject !== undefined ) {
  49176. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  49177. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  49178. contextData.occlusionQueryIndex ++;
  49179. }
  49180. if ( object.occlusionTest === true ) {
  49181. const query = gl.createQuery();
  49182. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  49183. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  49184. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  49185. }
  49186. contextData.lastOcclusionObject = object;
  49187. }
  49188. //
  49189. const renderer = this.bufferRenderer;
  49190. if ( object.isPoints ) renderer.mode = gl.POINTS;
  49191. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  49192. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  49193. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  49194. else {
  49195. if ( material.wireframe === true ) {
  49196. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  49197. renderer.mode = gl.LINES;
  49198. } else {
  49199. renderer.mode = gl.TRIANGLES;
  49200. }
  49201. }
  49202. //
  49203. const { vertexCount, instanceCount } = drawParams;
  49204. let { firstVertex } = drawParams;
  49205. renderer.object = object;
  49206. if ( index !== null ) {
  49207. firstVertex *= index.array.BYTES_PER_ELEMENT;
  49208. const indexData = this.get( index );
  49209. renderer.index = index.count;
  49210. renderer.type = indexData.type;
  49211. } else {
  49212. renderer.index = 0;
  49213. }
  49214. const draw = () => {
  49215. if ( object.isBatchedMesh ) {
  49216. if ( object._multiDrawInstances !== null ) {
  49217. // @deprecated, r174
  49218. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  49219. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  49220. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  49221. warnOnce( 'WebGLBackend: WEBGL_multi_draw not supported.' );
  49222. } else {
  49223. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  49224. }
  49225. } else if ( instanceCount > 1 ) {
  49226. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  49227. } else {
  49228. renderer.render( firstVertex, vertexCount );
  49229. }
  49230. };
  49231. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  49232. const cameraData = this.get( renderObject.camera );
  49233. const cameras = renderObject.camera.cameras;
  49234. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  49235. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  49236. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  49237. const indexesGPU = [];
  49238. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49239. const bufferGPU = gl.createBuffer();
  49240. data[ 0 ] = i;
  49241. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49242. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  49243. indexesGPU.push( bufferGPU );
  49244. }
  49245. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  49246. }
  49247. const cameraIndexData = this.get( cameraIndex );
  49248. const pixelRatio = this.renderer.getPixelRatio();
  49249. const renderTarget = this._currentContext.renderTarget;
  49250. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  49251. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  49252. if ( isRenderCameraDepthArray ) {
  49253. // Clear the depth texture
  49254. const textureData = this.get( renderTarget.depthTexture );
  49255. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  49256. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  49257. const { stencilBuffer } = renderTarget;
  49258. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49259. this.renderer._activeCubeFace = i;
  49260. this._currentContext.activeCubeFace = i;
  49261. this._setFramebuffer( this._currentContext );
  49262. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  49263. }
  49264. this.renderer._activeCubeFace = prevActiveCubeFace;
  49265. this._currentContext.activeCubeFace = prevActiveCubeFace;
  49266. }
  49267. }
  49268. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49269. const subCamera = cameras[ i ];
  49270. if ( object.layers.test( subCamera.layers ) ) {
  49271. if ( isRenderCameraDepthArray ) {
  49272. // Update the active layer
  49273. this.renderer._activeCubeFace = i;
  49274. this._currentContext.activeCubeFace = i;
  49275. this._setFramebuffer( this._currentContext );
  49276. }
  49277. const vp = subCamera.viewport;
  49278. if ( vp !== undefined ) {
  49279. const x = vp.x * pixelRatio;
  49280. const y = vp.y * pixelRatio;
  49281. const width = vp.width * pixelRatio;
  49282. const height = vp.height * pixelRatio;
  49283. state.viewport(
  49284. Math.floor( x ),
  49285. Math.floor( renderObject.context.height - height - y ),
  49286. Math.floor( width ),
  49287. Math.floor( height )
  49288. );
  49289. }
  49290. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  49291. draw();
  49292. }
  49293. this._currentContext.activeCubeFace = prevActiveCubeFace;
  49294. this.renderer._activeCubeFace = prevActiveCubeFace;
  49295. }
  49296. } else {
  49297. draw();
  49298. }
  49299. }
  49300. /**
  49301. * Explain why always null is returned.
  49302. *
  49303. * @param {RenderObject} renderObject - The render object.
  49304. * @return {boolean} Whether the render pipeline requires an update or not.
  49305. */
  49306. needsRenderUpdate( /*renderObject*/ ) {
  49307. return false;
  49308. }
  49309. /**
  49310. * Explain why no cache key is computed.
  49311. *
  49312. * @param {RenderObject} renderObject - The render object.
  49313. * @return {string} The cache key.
  49314. */
  49315. getRenderCacheKey( /*renderObject*/ ) {
  49316. return '';
  49317. }
  49318. // textures
  49319. /**
  49320. * Creates a default texture for the given texture that can be used
  49321. * as a placeholder until the actual texture is ready for usage.
  49322. *
  49323. * @param {Texture} texture - The texture to create a default texture for.
  49324. */
  49325. createDefaultTexture( texture ) {
  49326. this.textureUtils.createDefaultTexture( texture );
  49327. }
  49328. /**
  49329. * Defines a texture on the GPU for the given texture object.
  49330. *
  49331. * @param {Texture} texture - The texture.
  49332. * @param {Object} [options={}] - Optional configuration parameter.
  49333. */
  49334. createTexture( texture, options ) {
  49335. this.textureUtils.createTexture( texture, options );
  49336. }
  49337. /**
  49338. * Uploads the updated texture data to the GPU.
  49339. *
  49340. * @param {Texture} texture - The texture.
  49341. * @param {Object} [options={}] - Optional configuration parameter.
  49342. */
  49343. updateTexture( texture, options ) {
  49344. this.textureUtils.updateTexture( texture, options );
  49345. }
  49346. /**
  49347. * Generates mipmaps for the given texture.
  49348. *
  49349. * @param {Texture} texture - The texture.
  49350. */
  49351. generateMipmaps( texture ) {
  49352. this.textureUtils.generateMipmaps( texture );
  49353. }
  49354. /**
  49355. * Destroys the GPU data for the given texture object.
  49356. *
  49357. * @param {Texture} texture - The texture.
  49358. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49359. */
  49360. destroyTexture( texture, isDefaultTexture = false ) {
  49361. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  49362. }
  49363. /**
  49364. * Returns texture data as a typed array.
  49365. *
  49366. * @async
  49367. * @param {Texture} texture - The texture to copy.
  49368. * @param {number} x - The x coordinate of the copy origin.
  49369. * @param {number} y - The y coordinate of the copy origin.
  49370. * @param {number} width - The width of the copy.
  49371. * @param {number} height - The height of the copy.
  49372. * @param {number} faceIndex - The face index.
  49373. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49374. */
  49375. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49376. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  49377. }
  49378. /**
  49379. * This method does nothing since WebGL 2 has no concept of samplers.
  49380. *
  49381. * @param {Texture} texture - The texture to update the sampler for.
  49382. * @return {string} The current sampler key.
  49383. */
  49384. updateSampler( /*texture*/ ) {
  49385. return '';
  49386. }
  49387. // node builder
  49388. /**
  49389. * Returns a node builder for the given render object.
  49390. *
  49391. * @param {RenderObject} object - The render object.
  49392. * @param {Renderer} renderer - The renderer.
  49393. * @return {GLSLNodeBuilder} The node builder.
  49394. */
  49395. createNodeBuilder( object, renderer ) {
  49396. return new GLSLNodeBuilder( object, renderer );
  49397. }
  49398. // program
  49399. /**
  49400. * Creates a shader program from the given programmable stage.
  49401. *
  49402. * @param {ProgrammableStage} program - The programmable stage.
  49403. */
  49404. createProgram( program ) {
  49405. const gl = this.gl;
  49406. const { stage, code } = program;
  49407. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  49408. gl.shaderSource( shader, code );
  49409. gl.compileShader( shader );
  49410. this.set( program, {
  49411. shaderGPU: shader
  49412. } );
  49413. }
  49414. /**
  49415. * Destroys the shader program of the given programmable stage.
  49416. *
  49417. * @param {ProgrammableStage} program - The programmable stage.
  49418. */
  49419. destroyProgram( program ) {
  49420. this.delete( program );
  49421. }
  49422. /**
  49423. * Creates a render pipeline for the given render object.
  49424. *
  49425. * @param {RenderObject} renderObject - The render object.
  49426. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  49427. */
  49428. createRenderPipeline( renderObject, promises ) {
  49429. const gl = this.gl;
  49430. const pipeline = renderObject.pipeline;
  49431. // Program
  49432. const { fragmentProgram, vertexProgram } = pipeline;
  49433. const programGPU = gl.createProgram();
  49434. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  49435. const vertexShader = this.get( vertexProgram ).shaderGPU;
  49436. gl.attachShader( programGPU, fragmentShader );
  49437. gl.attachShader( programGPU, vertexShader );
  49438. gl.linkProgram( programGPU );
  49439. this.set( pipeline, {
  49440. programGPU,
  49441. fragmentShader,
  49442. vertexShader
  49443. } );
  49444. if ( promises !== null && this.parallel ) {
  49445. const p = new Promise( ( resolve /*, reject*/ ) => {
  49446. const parallel = this.parallel;
  49447. const checkStatus = () => {
  49448. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  49449. this._completeCompile( renderObject, pipeline );
  49450. resolve();
  49451. } else {
  49452. requestAnimationFrame( checkStatus );
  49453. }
  49454. };
  49455. checkStatus();
  49456. } );
  49457. promises.push( p );
  49458. return;
  49459. }
  49460. this._completeCompile( renderObject, pipeline );
  49461. }
  49462. /**
  49463. * Formats the source code of error messages.
  49464. *
  49465. * @private
  49466. * @param {string} string - The code.
  49467. * @param {number} errorLine - The error line.
  49468. * @return {string} The formatted code.
  49469. */
  49470. _handleSource( string, errorLine ) {
  49471. const lines = string.split( '\n' );
  49472. const lines2 = [];
  49473. const from = Math.max( errorLine - 6, 0 );
  49474. const to = Math.min( errorLine + 6, lines.length );
  49475. for ( let i = from; i < to; i ++ ) {
  49476. const line = i + 1;
  49477. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  49478. }
  49479. return lines2.join( '\n' );
  49480. }
  49481. /**
  49482. * Gets the shader compilation errors from the info log.
  49483. *
  49484. * @private
  49485. * @param {WebGL2RenderingContext} gl - The rendering context.
  49486. * @param {WebGLShader} shader - The WebGL shader object.
  49487. * @param {string} type - The shader type.
  49488. * @return {string} The shader errors.
  49489. */
  49490. _getShaderErrors( gl, shader, type ) {
  49491. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  49492. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  49493. const errors = shaderInfoLog.trim();
  49494. if ( status && errors === '' ) return '';
  49495. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  49496. if ( errorMatches ) {
  49497. const errorLine = parseInt( errorMatches[ 1 ] );
  49498. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  49499. } else {
  49500. return errors;
  49501. }
  49502. }
  49503. /**
  49504. * Logs shader compilation errors.
  49505. *
  49506. * @private
  49507. * @param {WebGLProgram} programGPU - The WebGL program.
  49508. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  49509. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  49510. */
  49511. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  49512. if ( this.renderer.debug.checkShaderErrors ) {
  49513. const gl = this.gl;
  49514. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  49515. const programLog = programInfoLog.trim();
  49516. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49517. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  49518. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  49519. } else {
  49520. // default error reporting
  49521. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  49522. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  49523. error(
  49524. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  49525. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  49526. 'Program Info Log: ' + programLog + '\n' +
  49527. vertexErrors + '\n' +
  49528. fragmentErrors
  49529. );
  49530. }
  49531. } else if ( programLog !== '' ) {
  49532. warn( 'WebGLProgram: Program Info Log:', programLog );
  49533. }
  49534. }
  49535. }
  49536. /**
  49537. * Completes the shader program setup for the given render object.
  49538. *
  49539. * @private
  49540. * @param {RenderObject} renderObject - The render object.
  49541. * @param {RenderPipeline} pipeline - The render pipeline.
  49542. */
  49543. _completeCompile( renderObject, pipeline ) {
  49544. const { state, gl } = this;
  49545. const pipelineData = this.get( pipeline );
  49546. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  49547. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49548. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49549. }
  49550. state.useProgram( programGPU );
  49551. // Bindings
  49552. const bindings = renderObject.getBindings();
  49553. this._setupBindings( bindings, programGPU );
  49554. //
  49555. this.set( pipeline, {
  49556. programGPU
  49557. } );
  49558. }
  49559. /**
  49560. * Creates a compute pipeline for the given compute node.
  49561. *
  49562. * @param {ComputePipeline} computePipeline - The compute pipeline.
  49563. * @param {Array<BindGroup>} bindings - The bindings.
  49564. */
  49565. createComputePipeline( computePipeline, bindings ) {
  49566. const { state, gl } = this;
  49567. // Program
  49568. const fragmentProgram = {
  49569. stage: 'fragment',
  49570. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  49571. };
  49572. this.createProgram( fragmentProgram );
  49573. const { computeProgram } = computePipeline;
  49574. const programGPU = gl.createProgram();
  49575. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  49576. const vertexShader = this.get( computeProgram ).shaderGPU;
  49577. const transforms = computeProgram.transforms;
  49578. const transformVaryingNames = [];
  49579. const transformAttributeNodes = [];
  49580. for ( let i = 0; i < transforms.length; i ++ ) {
  49581. const transform = transforms[ i ];
  49582. transformVaryingNames.push( transform.varyingName );
  49583. transformAttributeNodes.push( transform.attributeNode );
  49584. }
  49585. gl.attachShader( programGPU, fragmentShader );
  49586. gl.attachShader( programGPU, vertexShader );
  49587. gl.transformFeedbackVaryings(
  49588. programGPU,
  49589. transformVaryingNames,
  49590. gl.SEPARATE_ATTRIBS
  49591. );
  49592. gl.linkProgram( programGPU );
  49593. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49594. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49595. }
  49596. state.useProgram( programGPU );
  49597. // Bindings
  49598. this._setupBindings( bindings, programGPU );
  49599. const attributeNodes = computeProgram.attributes;
  49600. const attributes = [];
  49601. const transformBuffers = [];
  49602. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  49603. const attribute = attributeNodes[ i ].node.attribute;
  49604. attributes.push( attribute );
  49605. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49606. }
  49607. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  49608. const attribute = transformAttributeNodes[ i ].attribute;
  49609. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49610. const attributeData = this.get( attribute );
  49611. transformBuffers.push( attributeData );
  49612. }
  49613. //
  49614. this.set( computePipeline, {
  49615. programGPU,
  49616. transformBuffers,
  49617. attributes
  49618. } );
  49619. }
  49620. /**
  49621. * Creates bindings from the given bind group definition.
  49622. *
  49623. * @param {BindGroup} bindGroup - The bind group.
  49624. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49625. * @param {number} cacheIndex - The cache index.
  49626. * @param {number} version - The version.
  49627. */
  49628. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  49629. if ( this._knownBindings.has( bindings ) === false ) {
  49630. this._knownBindings.add( bindings );
  49631. let uniformBuffers = 0;
  49632. let textures = 0;
  49633. for ( const bindGroup of bindings ) {
  49634. this.set( bindGroup, {
  49635. textures: textures,
  49636. uniformBuffers: uniformBuffers
  49637. } );
  49638. for ( const binding of bindGroup.bindings ) {
  49639. if ( binding.isUniformBuffer ) uniformBuffers ++;
  49640. if ( binding.isSampledTexture ) textures ++;
  49641. }
  49642. }
  49643. }
  49644. this.updateBindings( bindGroup, bindings );
  49645. }
  49646. /**
  49647. * Updates the given bind group definition.
  49648. *
  49649. * @param {BindGroup} bindGroup - The bind group.
  49650. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49651. * @param {number} cacheIndex - The cache index.
  49652. * @param {number} version - The version.
  49653. */
  49654. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  49655. const { gl } = this;
  49656. const bindGroupData = this.get( bindGroup );
  49657. let i = bindGroupData.uniformBuffers;
  49658. let t = bindGroupData.textures;
  49659. for ( const binding of bindGroup.bindings ) {
  49660. const map = this.get( binding );
  49661. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49662. const array = binding.buffer;
  49663. let { bufferGPU } = this.get( array );
  49664. if ( bufferGPU === undefined ) {
  49665. // create
  49666. bufferGPU = gl.createBuffer();
  49667. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49668. gl.bufferData( gl.UNIFORM_BUFFER, array.byteLength, gl.DYNAMIC_DRAW );
  49669. this.set( array, { bufferGPU } );
  49670. } else {
  49671. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49672. }
  49673. // update
  49674. const updateRanges = binding.updateRanges;
  49675. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49676. if ( updateRanges.length === 0 ) {
  49677. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49678. } else {
  49679. const isTyped = isTypedArray( array );
  49680. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49681. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49682. const range = updateRanges[ i ];
  49683. const dataOffset = range.start * byteOffsetFactor;
  49684. const size = range.count * byteOffsetFactor;
  49685. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49686. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49687. }
  49688. }
  49689. map.index = i ++;
  49690. map.bufferGPU = bufferGPU;
  49691. this.set( binding, map );
  49692. } else if ( binding.isSampledTexture ) {
  49693. const { textureGPU, glTextureType } = this.get( binding.texture );
  49694. map.index = t ++;
  49695. map.textureGPU = textureGPU;
  49696. map.glTextureType = glTextureType;
  49697. this.set( binding, map );
  49698. }
  49699. }
  49700. }
  49701. /**
  49702. * Updates a buffer binding.
  49703. *
  49704. * @param {Buffer} binding - The buffer binding to update.
  49705. */
  49706. updateBinding( binding ) {
  49707. const gl = this.gl;
  49708. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49709. const bindingData = this.get( binding );
  49710. const bufferGPU = bindingData.bufferGPU;
  49711. const array = binding.buffer;
  49712. const updateRanges = binding.updateRanges;
  49713. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49714. if ( updateRanges.length === 0 ) {
  49715. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49716. } else {
  49717. const isTyped = isTypedArray( array );
  49718. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49719. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49720. const range = updateRanges[ i ];
  49721. const dataOffset = range.start * byteOffsetFactor;
  49722. const size = range.count * byteOffsetFactor;
  49723. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49724. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49725. }
  49726. }
  49727. }
  49728. }
  49729. // attributes
  49730. /**
  49731. * Creates the GPU buffer of an indexed shader attribute.
  49732. *
  49733. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  49734. */
  49735. createIndexAttribute( attribute ) {
  49736. const gl = this.gl;
  49737. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  49738. }
  49739. /**
  49740. * Creates the GPU buffer of a shader attribute.
  49741. *
  49742. * @param {BufferAttribute} attribute - The buffer attribute.
  49743. */
  49744. createAttribute( attribute ) {
  49745. if ( this.has( attribute ) ) return;
  49746. const gl = this.gl;
  49747. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49748. }
  49749. /**
  49750. * Creates the GPU buffer of a storage attribute.
  49751. *
  49752. * @param {BufferAttribute} attribute - The buffer attribute.
  49753. */
  49754. createStorageAttribute( attribute ) {
  49755. if ( this.has( attribute ) ) return;
  49756. const gl = this.gl;
  49757. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49758. }
  49759. /**
  49760. * Updates the GPU buffer of a shader attribute.
  49761. *
  49762. * @param {BufferAttribute} attribute - The buffer attribute to update.
  49763. */
  49764. updateAttribute( attribute ) {
  49765. this.attributeUtils.updateAttribute( attribute );
  49766. }
  49767. /**
  49768. * Destroys the GPU buffer of a shader attribute.
  49769. *
  49770. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  49771. */
  49772. destroyAttribute( attribute ) {
  49773. this.attributeUtils.destroyAttribute( attribute );
  49774. }
  49775. /**
  49776. * Checks if the given feature is supported by the backend.
  49777. *
  49778. * @param {string} name - The feature's name.
  49779. * @return {boolean} Whether the feature is supported or not.
  49780. */
  49781. hasFeature( name ) {
  49782. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  49783. const extensions = this.extensions;
  49784. for ( let i = 0; i < keysMatching.length; i ++ ) {
  49785. if ( extensions.has( keysMatching[ i ] ) ) return true;
  49786. }
  49787. return false;
  49788. }
  49789. /**
  49790. * Returns the maximum anisotropy texture filtering value.
  49791. *
  49792. * @return {number} The maximum anisotropy texture filtering value.
  49793. */
  49794. getMaxAnisotropy() {
  49795. return this.capabilities.getMaxAnisotropy();
  49796. }
  49797. /**
  49798. * Copies data of the given source texture to the given destination texture.
  49799. *
  49800. * @param {Texture} srcTexture - The source texture.
  49801. * @param {Texture} dstTexture - The destination texture.
  49802. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  49803. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  49804. * @param {number} [srcLevel=0] - The source mip level to copy from.
  49805. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  49806. */
  49807. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  49808. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  49809. }
  49810. /**
  49811. * Copies the current bound framebuffer to the given texture.
  49812. *
  49813. * @param {Texture} texture - The destination texture.
  49814. * @param {RenderContext} renderContext - The render context.
  49815. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  49816. */
  49817. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  49818. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  49819. }
  49820. /**
  49821. * Checks if the given compatibility is supported by the backend.
  49822. *
  49823. * @param {string} name - The compatibility name.
  49824. * @return {boolean} Whether the compatibility is supported or not.
  49825. */
  49826. hasCompatibility( name ) {
  49827. if ( name === Compatibility.TEXTURE_COMPARE ) return true;
  49828. return super.hasCompatibility( name );
  49829. }
  49830. /**
  49831. * Initializes the render target defined in the given render context.
  49832. *
  49833. * @param {RenderContext} renderContext - The render context.
  49834. */
  49835. initRenderTarget( renderContext ) {
  49836. const { gl, state } = this;
  49837. this._setFramebuffer( renderContext );
  49838. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  49839. }
  49840. /**
  49841. * Configures the active framebuffer from the given render context.
  49842. *
  49843. * @private
  49844. * @param {RenderContext} descriptor - The render context.
  49845. */
  49846. _setFramebuffer( descriptor ) {
  49847. const { gl, state } = this;
  49848. let currentFrameBuffer = null;
  49849. if ( descriptor.textures !== null ) {
  49850. const renderTarget = descriptor.renderTarget;
  49851. const renderTargetContextData = this.get( renderTarget );
  49852. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  49853. const isCube = renderTarget.isCubeRenderTarget === true;
  49854. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  49855. const isRenderTargetArray = renderTarget.depth > 1;
  49856. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  49857. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  49858. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  49859. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  49860. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  49861. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  49862. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  49863. const cacheKey = getCacheKey( descriptor );
  49864. let fb;
  49865. if ( isCube ) {
  49866. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  49867. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  49868. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  49869. fb = this._xrFramebuffer;
  49870. } else {
  49871. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  49872. fb = renderTargetContextData.framebuffers[ cacheKey ];
  49873. }
  49874. if ( fb === undefined ) {
  49875. fb = gl.createFramebuffer();
  49876. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49877. const textures = descriptor.textures;
  49878. const depthInvalidationArray = [];
  49879. if ( isCube ) {
  49880. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  49881. const { textureGPU } = this.get( textures[ 0 ] );
  49882. const cubeFace = this.renderer._activeCubeFace;
  49883. const mipLevel = this.renderer._activeMipmapLevel;
  49884. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  49885. } else {
  49886. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  49887. for ( let i = 0; i < textures.length; i ++ ) {
  49888. const texture = textures[ i ];
  49889. const textureData = this.get( texture );
  49890. textureData.renderTarget = descriptor.renderTarget;
  49891. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  49892. const attachment = gl.COLOR_ATTACHMENT0 + i;
  49893. if ( renderTarget.multiview ) {
  49894. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  49895. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  49896. const layer = this.renderer._activeCubeFace;
  49897. const mipLevel = this.renderer._activeMipmapLevel;
  49898. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  49899. } else {
  49900. if ( useMultisampledRTT ) {
  49901. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49902. } else {
  49903. const mipLevel = this.renderer._activeMipmapLevel;
  49904. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  49905. }
  49906. }
  49907. }
  49908. }
  49909. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49910. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  49911. const renderbuffer = gl.createRenderbuffer();
  49912. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  49913. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  49914. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  49915. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49916. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  49917. } else {
  49918. if ( descriptor.depthTexture !== null ) {
  49919. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  49920. const textureData = this.get( descriptor.depthTexture );
  49921. textureData.renderTarget = descriptor.renderTarget;
  49922. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  49923. if ( renderTarget.multiview ) {
  49924. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  49925. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  49926. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49927. } else {
  49928. if ( descriptor.depthTexture.isArrayTexture ) {
  49929. const layer = this.renderer._activeCubeFace;
  49930. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  49931. } else if ( descriptor.depthTexture.isCubeTexture ) {
  49932. const cubeFace = this.renderer._activeCubeFace;
  49933. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureData.textureGPU, 0 );
  49934. } else {
  49935. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49936. }
  49937. }
  49938. }
  49939. }
  49940. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  49941. } else {
  49942. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  49943. if ( isRenderCameraDepthArray ) {
  49944. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49945. const layer = this.renderer._activeCubeFace;
  49946. const depthData = this.get( descriptor.depthTexture );
  49947. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49948. gl.framebufferTextureLayer(
  49949. gl.FRAMEBUFFER,
  49950. depthStyle,
  49951. depthData.textureGPU,
  49952. 0,
  49953. layer
  49954. );
  49955. }
  49956. // rebind external XR textures
  49957. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  49958. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49959. // rebind color
  49960. const textureData = this.get( descriptor.textures[ 0 ] );
  49961. if ( renderTarget.multiview ) {
  49962. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  49963. } else if ( useMultisampledRTT ) {
  49964. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49965. } else {
  49966. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49967. }
  49968. // rebind depth
  49969. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49970. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  49971. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  49972. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49973. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  49974. } else {
  49975. const textureData = this.get( descriptor.depthTexture );
  49976. if ( renderTarget.multiview ) {
  49977. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  49978. } else if ( useMultisampledRTT ) {
  49979. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49980. } else {
  49981. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49982. }
  49983. }
  49984. }
  49985. }
  49986. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  49987. if ( msaaFb === undefined ) {
  49988. const invalidationArray = [];
  49989. msaaFb = gl.createFramebuffer();
  49990. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  49991. const msaaRenderbuffers = [];
  49992. const textures = descriptor.textures;
  49993. for ( let i = 0; i < textures.length; i ++ ) {
  49994. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  49995. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49996. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  49997. const texture = descriptor.textures[ i ];
  49998. const textureData = this.get( texture );
  49999. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  50000. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50001. }
  50002. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  50003. renderTargetContextData.msaaFrameBuffer = msaaFb;
  50004. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  50005. if ( depthBuffer && depthRenderbuffer === undefined ) {
  50006. depthRenderbuffer = gl.createRenderbuffer();
  50007. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  50008. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  50009. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  50010. invalidationArray.push( depthStyle );
  50011. }
  50012. renderTargetContextData.invalidationArray = invalidationArray;
  50013. }
  50014. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  50015. } else {
  50016. currentFrameBuffer = fb;
  50017. }
  50018. state.drawBuffers( descriptor, fb );
  50019. }
  50020. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  50021. }
  50022. /**
  50023. * Computes the VAO key for the given index and attributes.
  50024. *
  50025. * @private
  50026. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  50027. * @return {string} The VAO key.
  50028. */
  50029. _getVaoKey( attributes ) {
  50030. let key = '';
  50031. for ( let i = 0; i < attributes.length; i ++ ) {
  50032. const attributeData = this.get( attributes[ i ] );
  50033. key += ':' + attributeData.id;
  50034. }
  50035. return key;
  50036. }
  50037. /**
  50038. * Creates a VAO from the index and attributes.
  50039. *
  50040. * @private
  50041. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  50042. * @return {Object} The VAO data.
  50043. */
  50044. _createVao( attributes ) {
  50045. const { gl } = this;
  50046. const vaoGPU = gl.createVertexArray();
  50047. gl.bindVertexArray( vaoGPU );
  50048. for ( let i = 0; i < attributes.length; i ++ ) {
  50049. const attribute = attributes[ i ];
  50050. const attributeData = this.get( attribute );
  50051. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  50052. gl.enableVertexAttribArray( i );
  50053. let stride, offset;
  50054. if ( attribute.isInterleavedBufferAttribute === true ) {
  50055. stride = attribute.data.stride * attributeData.bytesPerElement;
  50056. offset = attribute.offset * attributeData.bytesPerElement;
  50057. } else {
  50058. stride = 0;
  50059. offset = 0;
  50060. }
  50061. if ( attributeData.isInteger ) {
  50062. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  50063. } else {
  50064. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  50065. }
  50066. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  50067. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  50068. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  50069. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  50070. }
  50071. }
  50072. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  50073. return vaoGPU;
  50074. }
  50075. /**
  50076. * Creates a transform feedback from the given transform buffers.
  50077. *
  50078. * @private
  50079. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  50080. * @return {WebGLTransformFeedback} The transform feedback.
  50081. */
  50082. _getTransformFeedback( transformBuffers ) {
  50083. let key = '';
  50084. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  50085. key += ':' + transformBuffers[ i ].id;
  50086. }
  50087. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  50088. if ( transformFeedbackGPU !== undefined ) {
  50089. return transformFeedbackGPU;
  50090. }
  50091. const { gl } = this;
  50092. transformFeedbackGPU = gl.createTransformFeedback();
  50093. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  50094. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  50095. const attributeData = transformBuffers[ i ];
  50096. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  50097. }
  50098. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  50099. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  50100. return transformFeedbackGPU;
  50101. }
  50102. /**
  50103. * Setups the given bindings.
  50104. *
  50105. * @private
  50106. * @param {Array<BindGroup>} bindings - The bindings.
  50107. * @param {WebGLProgram} programGPU - The WebGL program.
  50108. */
  50109. _setupBindings( bindings, programGPU ) {
  50110. const gl = this.gl;
  50111. for ( const bindGroup of bindings ) {
  50112. for ( const binding of bindGroup.bindings ) {
  50113. const bindingData = this.get( binding );
  50114. const index = bindingData.index;
  50115. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  50116. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  50117. gl.uniformBlockBinding( programGPU, location, index );
  50118. } else if ( binding.isSampledTexture ) {
  50119. const location = gl.getUniformLocation( programGPU, binding.name );
  50120. gl.uniform1i( location, index );
  50121. }
  50122. }
  50123. }
  50124. }
  50125. /**
  50126. * Binds the given uniforms.
  50127. *
  50128. * @private
  50129. * @param {Array<BindGroup>} bindings - The bindings.
  50130. */
  50131. _bindUniforms( bindings ) {
  50132. const { gl, state } = this;
  50133. for ( const bindGroup of bindings ) {
  50134. for ( const binding of bindGroup.bindings ) {
  50135. const bindingData = this.get( binding );
  50136. const index = bindingData.index;
  50137. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  50138. // TODO USE bindBufferRange to group multiple uniform buffers
  50139. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  50140. } else if ( binding.isSampledTexture ) {
  50141. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  50142. }
  50143. }
  50144. }
  50145. }
  50146. /**
  50147. * The method ensures multisampled render targets are resolved.
  50148. *
  50149. * @private
  50150. * @param {RenderContext} renderContext - The render context.
  50151. */
  50152. _resolveRenderTarget( renderContext ) {
  50153. const { gl, state } = this;
  50154. const renderTarget = renderContext.renderTarget;
  50155. if ( renderContext.textures !== null && renderTarget ) {
  50156. const renderTargetContextData = this.get( renderTarget );
  50157. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  50158. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  50159. let mask = gl.COLOR_BUFFER_BIT;
  50160. if ( renderTarget.resolveDepthBuffer ) {
  50161. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  50162. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  50163. }
  50164. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  50165. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  50166. const textures = renderContext.textures;
  50167. const isMRT = textures.length > 1;
  50168. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  50169. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  50170. if ( isMRT ) {
  50171. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  50172. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  50173. for ( let i = 0; i < textures.length; i ++ ) {
  50174. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  50175. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  50176. }
  50177. }
  50178. for ( let i = 0; i < textures.length; i ++ ) {
  50179. if ( isMRT ) {
  50180. // configure attachment for resolve
  50181. const { textureGPU } = this.get( textures[ i ] );
  50182. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50183. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  50184. }
  50185. if ( renderContext.scissor ) {
  50186. const { x, y, width, height } = renderContext.scissorValue;
  50187. const viewY = renderContext.height - height - y;
  50188. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  50189. } else {
  50190. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  50191. }
  50192. }
  50193. if ( isMRT ) {
  50194. // restore attachments
  50195. for ( let i = 0; i < textures.length; i ++ ) {
  50196. const { textureGPU } = this.get( textures[ i ] );
  50197. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50198. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  50199. }
  50200. }
  50201. if ( this._supportsInvalidateFramebuffer === true ) {
  50202. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  50203. }
  50204. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  50205. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  50206. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  50207. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  50208. }
  50209. }
  50210. }
  50211. /**
  50212. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  50213. * should be used when MSAA is enabled.
  50214. *
  50215. * @private
  50216. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  50217. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  50218. */
  50219. _useMultisampledExtension( renderTarget ) {
  50220. if ( renderTarget.multiview === true ) {
  50221. return true;
  50222. }
  50223. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  50224. }
  50225. /**
  50226. * Frees internal resources.
  50227. */
  50228. dispose() {
  50229. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  50230. const extension = this.extensions.get( 'WEBGL_lose_context' );
  50231. if ( extension ) extension.loseContext();
  50232. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  50233. }
  50234. }
  50235. const GPUPrimitiveTopology = {
  50236. PointList: 'point-list',
  50237. LineList: 'line-list',
  50238. LineStrip: 'line-strip',
  50239. TriangleList: 'triangle-list'};
  50240. const GPUShaderStage = ( typeof self !== 'undefined' && self.GPUShaderStage ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  50241. const GPUCompareFunction = {
  50242. Never: 'never',
  50243. Less: 'less',
  50244. Equal: 'equal',
  50245. LessEqual: 'less-equal',
  50246. Greater: 'greater',
  50247. NotEqual: 'not-equal',
  50248. GreaterEqual: 'greater-equal',
  50249. Always: 'always'
  50250. };
  50251. const GPUStoreOp = {
  50252. Store: 'store'};
  50253. const GPULoadOp = {
  50254. Load: 'load',
  50255. Clear: 'clear'
  50256. };
  50257. const GPUFrontFace = {
  50258. CCW: 'ccw',
  50259. CW: 'cw'
  50260. };
  50261. const GPUCullMode = {
  50262. None: 'none',
  50263. Back: 'back'
  50264. };
  50265. const GPUIndexFormat = {
  50266. Uint16: 'uint16',
  50267. Uint32: 'uint32'
  50268. };
  50269. const GPUTextureFormat = {
  50270. // 8-bit formats
  50271. R8Unorm: 'r8unorm',
  50272. R8Snorm: 'r8snorm',
  50273. R8Uint: 'r8uint',
  50274. R8Sint: 'r8sint',
  50275. // 16-bit formats
  50276. R16Uint: 'r16uint',
  50277. R16Sint: 'r16sint',
  50278. R16Float: 'r16float',
  50279. RG8Unorm: 'rg8unorm',
  50280. RG8Snorm: 'rg8snorm',
  50281. RG8Uint: 'rg8uint',
  50282. RG8Sint: 'rg8sint',
  50283. // 32-bit formats
  50284. R32Uint: 'r32uint',
  50285. R32Sint: 'r32sint',
  50286. R32Float: 'r32float',
  50287. RG16Uint: 'rg16uint',
  50288. RG16Sint: 'rg16sint',
  50289. RG16Float: 'rg16float',
  50290. RGBA8Unorm: 'rgba8unorm',
  50291. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  50292. RGBA8Snorm: 'rgba8snorm',
  50293. RGBA8Uint: 'rgba8uint',
  50294. RGBA8Sint: 'rgba8sint',
  50295. BGRA8Unorm: 'bgra8unorm',
  50296. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  50297. // Packed 32-bit formats
  50298. RGB9E5UFloat: 'rgb9e5ufloat',
  50299. RGB10A2Unorm: 'rgb10a2unorm',
  50300. RG11B10UFloat: 'rg11b10ufloat',
  50301. // 64-bit formats
  50302. RG32Uint: 'rg32uint',
  50303. RG32Sint: 'rg32sint',
  50304. RG32Float: 'rg32float',
  50305. RGBA16Uint: 'rgba16uint',
  50306. RGBA16Sint: 'rgba16sint',
  50307. RGBA16Float: 'rgba16float',
  50308. // 128-bit formats
  50309. RGBA32Uint: 'rgba32uint',
  50310. RGBA32Sint: 'rgba32sint',
  50311. RGBA32Float: 'rgba32float',
  50312. Depth16Unorm: 'depth16unorm',
  50313. Depth24Plus: 'depth24plus',
  50314. Depth24PlusStencil8: 'depth24plus-stencil8',
  50315. Depth32Float: 'depth32float',
  50316. // 'depth32float-stencil8' extension
  50317. Depth32FloatStencil8: 'depth32float-stencil8',
  50318. // BC compressed formats usable if 'texture-compression-bc' is both
  50319. // supported by the device/user agent and enabled in requestDevice.
  50320. BC1RGBAUnorm: 'bc1-rgba-unorm',
  50321. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  50322. BC2RGBAUnorm: 'bc2-rgba-unorm',
  50323. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  50324. BC3RGBAUnorm: 'bc3-rgba-unorm',
  50325. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  50326. BC4RUnorm: 'bc4-r-unorm',
  50327. BC4RSnorm: 'bc4-r-snorm',
  50328. BC5RGUnorm: 'bc5-rg-unorm',
  50329. BC5RGSnorm: 'bc5-rg-snorm',
  50330. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  50331. BC6HRGBFloat: 'bc6h-rgb-float',
  50332. BC7RGBAUnorm: 'bc7-rgba-unorm',
  50333. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  50334. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  50335. // supported by the device/user agent and enabled in requestDevice.
  50336. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  50337. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  50338. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  50339. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  50340. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  50341. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  50342. EACR11Unorm: 'eac-r11unorm',
  50343. EACR11Snorm: 'eac-r11snorm',
  50344. EACRG11Unorm: 'eac-rg11unorm',
  50345. EACRG11Snorm: 'eac-rg11snorm',
  50346. // ASTC compressed formats usable if 'texture-compression-astc' is both
  50347. // supported by the device/user agent and enabled in requestDevice.
  50348. ASTC4x4Unorm: 'astc-4x4-unorm',
  50349. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  50350. ASTC5x4Unorm: 'astc-5x4-unorm',
  50351. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  50352. ASTC5x5Unorm: 'astc-5x5-unorm',
  50353. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  50354. ASTC6x5Unorm: 'astc-6x5-unorm',
  50355. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  50356. ASTC6x6Unorm: 'astc-6x6-unorm',
  50357. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  50358. ASTC8x5Unorm: 'astc-8x5-unorm',
  50359. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  50360. ASTC8x6Unorm: 'astc-8x6-unorm',
  50361. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  50362. ASTC8x8Unorm: 'astc-8x8-unorm',
  50363. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  50364. ASTC10x5Unorm: 'astc-10x5-unorm',
  50365. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  50366. ASTC10x6Unorm: 'astc-10x6-unorm',
  50367. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  50368. ASTC10x8Unorm: 'astc-10x8-unorm',
  50369. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  50370. ASTC10x10Unorm: 'astc-10x10-unorm',
  50371. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  50372. ASTC12x10Unorm: 'astc-12x10-unorm',
  50373. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  50374. ASTC12x12Unorm: 'astc-12x12-unorm',
  50375. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  50376. };
  50377. const GPUAddressMode = {
  50378. ClampToEdge: 'clamp-to-edge',
  50379. Repeat: 'repeat',
  50380. MirrorRepeat: 'mirror-repeat'
  50381. };
  50382. const GPUFilterMode = {
  50383. Linear: 'linear',
  50384. Nearest: 'nearest'
  50385. };
  50386. const GPUBlendFactor = {
  50387. Zero: 'zero',
  50388. One: 'one',
  50389. Src: 'src',
  50390. OneMinusSrc: 'one-minus-src',
  50391. SrcAlpha: 'src-alpha',
  50392. OneMinusSrcAlpha: 'one-minus-src-alpha',
  50393. Dst: 'dst',
  50394. OneMinusDst: 'one-minus-dst',
  50395. DstAlpha: 'dst-alpha',
  50396. OneMinusDstAlpha: 'one-minus-dst-alpha',
  50397. SrcAlphaSaturated: 'src-alpha-saturated',
  50398. Constant: 'constant',
  50399. OneMinusConstant: 'one-minus-constant'
  50400. };
  50401. const GPUBlendOperation = {
  50402. Add: 'add',
  50403. Subtract: 'subtract',
  50404. ReverseSubtract: 'reverse-subtract',
  50405. Min: 'min',
  50406. Max: 'max'
  50407. };
  50408. const GPUColorWriteFlags = {
  50409. None: 0,
  50410. All: 0xF
  50411. };
  50412. const GPUStencilOperation = {
  50413. Keep: 'keep',
  50414. Zero: 'zero',
  50415. Replace: 'replace',
  50416. Invert: 'invert',
  50417. IncrementClamp: 'increment-clamp',
  50418. DecrementClamp: 'decrement-clamp',
  50419. IncrementWrap: 'increment-wrap',
  50420. DecrementWrap: 'decrement-wrap'
  50421. };
  50422. const GPUBufferBindingType = {
  50423. Storage: 'storage',
  50424. ReadOnlyStorage: 'read-only-storage'
  50425. };
  50426. const GPUStorageTextureAccess = {
  50427. WriteOnly: 'write-only',
  50428. ReadOnly: 'read-only',
  50429. ReadWrite: 'read-write',
  50430. };
  50431. const GPUSamplerBindingType = {
  50432. NonFiltering: 'non-filtering',
  50433. Comparison: 'comparison'
  50434. };
  50435. const GPUTextureSampleType = {
  50436. Float: 'float',
  50437. UnfilterableFloat: 'unfilterable-float',
  50438. Depth: 'depth',
  50439. SInt: 'sint',
  50440. UInt: 'uint'
  50441. };
  50442. const GPUTextureDimension = {
  50443. TwoD: '2d',
  50444. ThreeD: '3d'
  50445. };
  50446. const GPUTextureViewDimension = {
  50447. TwoD: '2d',
  50448. TwoDArray: '2d-array',
  50449. Cube: 'cube',
  50450. ThreeD: '3d'
  50451. };
  50452. const GPUTextureAspect = {
  50453. All: 'all'};
  50454. const GPUInputStepMode = {
  50455. Vertex: 'vertex',
  50456. Instance: 'instance'
  50457. };
  50458. const GPUFeatureName = {
  50459. CoreFeaturesAndLimits: 'core-features-and-limits',
  50460. DepthClipControl: 'depth-clip-control',
  50461. Depth32FloatStencil8: 'depth32float-stencil8',
  50462. TextureCompressionBC: 'texture-compression-bc',
  50463. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  50464. TextureCompressionETC2: 'texture-compression-etc2',
  50465. TextureCompressionASTC: 'texture-compression-astc',
  50466. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  50467. TimestampQuery: 'timestamp-query',
  50468. IndirectFirstInstance: 'indirect-first-instance',
  50469. ShaderF16: 'shader-f16',
  50470. RG11B10UFloat: 'rg11b10ufloat-renderable',
  50471. BGRA8UNormStorage: 'bgra8unorm-storage',
  50472. Float32Filterable: 'float32-filterable',
  50473. Float32Blendable: 'float32-blendable',
  50474. ClipDistances: 'clip-distances',
  50475. DualSourceBlending: 'dual-source-blending',
  50476. Subgroups: 'subgroups',
  50477. TextureFormatsTier1: 'texture-formats-tier1',
  50478. TextureFormatsTier2: 'texture-formats-tier2'
  50479. };
  50480. const GPUFeatureMap = {
  50481. 'texture-compression-s3tc': 'texture-compression-bc',
  50482. 'texture-compression-etc1': 'texture-compression-etc2'
  50483. };
  50484. /**
  50485. * A special form of sampler binding type.
  50486. * It's texture value is managed by a node object.
  50487. *
  50488. * @private
  50489. * @augments Sampler
  50490. */
  50491. class NodeSampler extends Sampler {
  50492. /**
  50493. * Constructs a new node-based sampler.
  50494. *
  50495. * @param {string} name - The samplers's name.
  50496. * @param {TextureNode} textureNode - The texture node.
  50497. * @param {UniformGroupNode} groupNode - The uniform group node.
  50498. */
  50499. constructor( name, textureNode, groupNode ) {
  50500. super( name, textureNode ? textureNode.value : null );
  50501. /**
  50502. * The texture node.
  50503. *
  50504. * @type {TextureNode}
  50505. */
  50506. this.textureNode = textureNode;
  50507. /**
  50508. * The uniform group node.
  50509. *
  50510. * @type {UniformGroupNode}
  50511. */
  50512. this.groupNode = groupNode;
  50513. }
  50514. /**
  50515. * Updates the texture value of this sampler.
  50516. *
  50517. * @return {boolean} Whether the sampler needs an update or not.
  50518. */
  50519. update() {
  50520. const { textureNode } = this;
  50521. if ( this.texture !== textureNode.value ) {
  50522. this.texture = textureNode.value;
  50523. return true;
  50524. }
  50525. return super.update();
  50526. }
  50527. }
  50528. /**
  50529. * Represents a storage buffer binding type.
  50530. *
  50531. * @private
  50532. * @augments Buffer
  50533. */
  50534. class StorageBuffer extends Buffer {
  50535. /**
  50536. * Constructs a new uniform buffer.
  50537. *
  50538. * @param {string} name - The buffer's name.
  50539. * @param {BufferAttribute} attribute - The buffer attribute.
  50540. */
  50541. constructor( name, attribute ) {
  50542. super( name, attribute ? attribute.array : null );
  50543. /**
  50544. * This flag can be used for type testing.
  50545. *
  50546. * @private
  50547. * @type {BufferAttribute}
  50548. */
  50549. this._attribute = attribute;
  50550. /**
  50551. * This flag can be used for type testing.
  50552. *
  50553. * @type {boolean}
  50554. * @readonly
  50555. * @default true
  50556. */
  50557. this.isStorageBuffer = true;
  50558. }
  50559. /**
  50560. * The storage buffer attribute.
  50561. *
  50562. * @type {BufferAttribute}
  50563. */
  50564. get attribute() {
  50565. return this._attribute;
  50566. }
  50567. }
  50568. let _id = 0;
  50569. /**
  50570. * A special form of storage buffer binding type.
  50571. * It's buffer value is managed by a node object.
  50572. *
  50573. * @private
  50574. * @augments StorageBuffer
  50575. */
  50576. class NodeStorageBuffer extends StorageBuffer {
  50577. /**
  50578. * Constructs a new node-based storage buffer.
  50579. *
  50580. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  50581. * @param {UniformGroupNode} groupNode - The uniform group node.
  50582. */
  50583. constructor( nodeUniform, groupNode ) {
  50584. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  50585. /**
  50586. * The node uniform.
  50587. *
  50588. * @type {StorageBufferNode}
  50589. */
  50590. this.nodeUniform = nodeUniform;
  50591. /**
  50592. * The access type.
  50593. *
  50594. * @type {string}
  50595. */
  50596. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  50597. /**
  50598. * The uniform group node.
  50599. *
  50600. * @type {UniformGroupNode}
  50601. */
  50602. this.groupNode = groupNode;
  50603. }
  50604. /**
  50605. * The storage buffer attribute node.
  50606. *
  50607. * @type {StorageBufferAttribute}
  50608. */
  50609. get attribute() {
  50610. return this.nodeUniform.value;
  50611. }
  50612. /**
  50613. * The storage buffer.
  50614. *
  50615. * @type {Float32Array}
  50616. */
  50617. get buffer() {
  50618. return this.nodeUniform.value.array;
  50619. }
  50620. }
  50621. /**
  50622. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  50623. *
  50624. * @private
  50625. */
  50626. class WebGPUTexturePassUtils extends DataMap {
  50627. /**
  50628. * Constructs a new utility object.
  50629. *
  50630. * @param {GPUDevice} device - The WebGPU device.
  50631. */
  50632. constructor( device ) {
  50633. super();
  50634. /**
  50635. * The WebGPU device.
  50636. *
  50637. * @type {GPUDevice}
  50638. */
  50639. this.device = device;
  50640. const mipmapSource = `
  50641. struct VarysStruct {
  50642. @builtin( position ) Position: vec4f,
  50643. @location( 0 ) vTex : vec2f,
  50644. @location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,
  50645. };
  50646. @group( 0 ) @binding ( 2 )
  50647. var<uniform> flipY: u32;
  50648. @vertex
  50649. fn mainVS(
  50650. @builtin( vertex_index ) vertexIndex : u32,
  50651. @builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {
  50652. var Varys : VarysStruct;
  50653. var pos = array(
  50654. vec2f( -1, -1 ),
  50655. vec2f( -1, 3 ),
  50656. vec2f( 3, -1 ),
  50657. );
  50658. let p = pos[ vertexIndex ];
  50659. let mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );
  50660. Varys.vTex = p * mult + vec2f( 0.5 );
  50661. Varys.Position = vec4f( p, 0, 1 );
  50662. Varys.vBaseArrayLayer = instanceIndex;
  50663. return Varys;
  50664. }
  50665. @group( 0 ) @binding( 0 )
  50666. var imgSampler : sampler;
  50667. @group( 0 ) @binding( 1 )
  50668. var img2d : texture_2d<f32>;
  50669. @fragment
  50670. fn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  50671. return textureSample( img2d, imgSampler, Varys.vTex );
  50672. }
  50673. @group( 0 ) @binding( 1 )
  50674. var img2dArray : texture_2d_array<f32>;
  50675. @fragment
  50676. fn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  50677. return textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );
  50678. }
  50679. const faceMat = array(
  50680. mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x
  50681. mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x
  50682. mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y
  50683. mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y
  50684. mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z
  50685. mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z
  50686. );
  50687. @group( 0 ) @binding( 1 )
  50688. var imgCube : texture_cube<f32>;
  50689. @fragment
  50690. fn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
  50691. return textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );
  50692. }
  50693. `;
  50694. /**
  50695. * The mipmap GPU sampler.
  50696. *
  50697. * @type {GPUSampler}
  50698. */
  50699. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  50700. /**
  50701. * The flipY GPU sampler.
  50702. *
  50703. * @type {GPUSampler}
  50704. */
  50705. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  50706. /**
  50707. * flip uniform buffer
  50708. * @type {GPUBuffer}
  50709. */
  50710. this.flipUniformBuffer = device.createBuffer( {
  50711. size: 4,
  50712. usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
  50713. } );
  50714. device.queue.writeBuffer( this.flipUniformBuffer, 0, new Uint32Array( [ 1 ] ) );
  50715. /**
  50716. * no flip uniform buffer
  50717. * @type {GPUBuffer}
  50718. */
  50719. this.noFlipUniformBuffer = device.createBuffer( {
  50720. size: 4,
  50721. usage: GPUBufferUsage.UNIFORM
  50722. } );
  50723. /**
  50724. * A cache for GPU render pipelines used for copy/transfer passes.
  50725. * Every texture format and textureBindingViewDimension combo requires a unique pipeline.
  50726. *
  50727. * @type {Object<string,GPURenderPipeline>}
  50728. */
  50729. this.transferPipelines = {};
  50730. /**
  50731. * The mipmap shader module.
  50732. *
  50733. * @type {GPUShaderModule}
  50734. */
  50735. this.mipmapShaderModule = device.createShaderModule( {
  50736. label: 'mipmap',
  50737. code: mipmapSource
  50738. } );
  50739. }
  50740. /**
  50741. * Returns a render pipeline for the internal copy render pass. The pass
  50742. * requires a unique render pipeline for each texture format.
  50743. *
  50744. * @param {string} format - The GPU texture format
  50745. * @param {string?} textureBindingViewDimension - The GPU texture binding view dimension
  50746. * @return {GPURenderPipeline} The GPU render pipeline.
  50747. */
  50748. getTransferPipeline( format, textureBindingViewDimension ) {
  50749. textureBindingViewDimension = textureBindingViewDimension || '2d-array';
  50750. const key = `${ format }-${ textureBindingViewDimension }`;
  50751. let pipeline = this.transferPipelines[ key ];
  50752. if ( pipeline === undefined ) {
  50753. pipeline = this.device.createRenderPipeline( {
  50754. label: `mipmap-${ format }-${ textureBindingViewDimension }`,
  50755. vertex: {
  50756. module: this.mipmapShaderModule,
  50757. },
  50758. fragment: {
  50759. module: this.mipmapShaderModule,
  50760. entryPoint: `main_${ textureBindingViewDimension.replace( '-', '_' ) }`,
  50761. targets: [ { format } ]
  50762. },
  50763. layout: 'auto'
  50764. } );
  50765. this.transferPipelines[ key ] = pipeline;
  50766. }
  50767. return pipeline;
  50768. }
  50769. /**
  50770. * Flip the contents of the given GPU texture along its vertical axis.
  50771. *
  50772. * @param {GPUTexture} textureGPU - The GPU texture object.
  50773. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50774. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50775. */
  50776. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  50777. const format = textureGPUDescriptor.format;
  50778. const { width, height } = textureGPUDescriptor.size;
  50779. const tempTexture = this.device.createTexture( {
  50780. size: { width, height },
  50781. format,
  50782. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  50783. } );
  50784. const copyTransferPipeline = this.getTransferPipeline( format, textureGPU.textureBindingViewDimension );
  50785. const flipTransferPipeline = this.getTransferPipeline( format, tempTexture.textureBindingViewDimension );
  50786. const commandEncoder = this.device.createCommandEncoder( {} );
  50787. const pass = ( pipeline, sourceTexture, sourceArrayLayer, destinationTexture, destinationArrayLayer, flipY ) => {
  50788. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  50789. const bindGroup = this.device.createBindGroup( {
  50790. layout: bindGroupLayout,
  50791. entries: [ {
  50792. binding: 0,
  50793. resource: this.flipYSampler
  50794. }, {
  50795. binding: 1,
  50796. resource: sourceTexture.createView( {
  50797. dimension: sourceTexture.textureBindingViewDimension || '2d-array',
  50798. baseMipLevel: 0,
  50799. mipLevelCount: 1,
  50800. } ),
  50801. }, {
  50802. binding: 2,
  50803. resource: { buffer: flipY ? this.flipUniformBuffer : this.noFlipUniformBuffer }
  50804. } ]
  50805. } );
  50806. const passEncoder = commandEncoder.beginRenderPass( {
  50807. colorAttachments: [ {
  50808. view: destinationTexture.createView( {
  50809. dimension: '2d',
  50810. baseMipLevel: 0,
  50811. mipLevelCount: 1,
  50812. baseArrayLayer: destinationArrayLayer,
  50813. arrayLayerCount: 1,
  50814. } ),
  50815. loadOp: GPULoadOp.Clear,
  50816. storeOp: GPUStoreOp.Store,
  50817. } ]
  50818. } );
  50819. passEncoder.setPipeline( pipeline );
  50820. passEncoder.setBindGroup( 0, bindGroup );
  50821. passEncoder.draw( 3, 1, 0, sourceArrayLayer );
  50822. passEncoder.end();
  50823. };
  50824. pass( copyTransferPipeline, textureGPU, baseArrayLayer, tempTexture, 0, false );
  50825. pass( flipTransferPipeline, tempTexture, 0, textureGPU, baseArrayLayer, true );
  50826. this.device.queue.submit( [ commandEncoder.finish() ] );
  50827. tempTexture.destroy();
  50828. }
  50829. /**
  50830. * Generates mipmaps for the given GPU texture.
  50831. *
  50832. * @param {GPUTexture} textureGPU - The GPU texture object.
  50833. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  50834. */
  50835. generateMipmaps( textureGPU, encoder = null ) {
  50836. const textureData = this.get( textureGPU );
  50837. const passes = textureData.layers || this._mipmapCreateBundles( textureGPU );
  50838. const commandEncoder = encoder || this.device.createCommandEncoder( { label: 'mipmapEncoder' } );
  50839. this._mipmapRunBundles( commandEncoder, passes );
  50840. if ( encoder === null ) this.device.queue.submit( [ commandEncoder.finish() ] );
  50841. textureData.layers = passes;
  50842. }
  50843. /**
  50844. * Since multiple copy render passes are required to generate mipmaps, the passes
  50845. * are managed as render bundles to improve performance.
  50846. *
  50847. * @param {GPUTexture} textureGPU - The GPU texture object.
  50848. * @return {Array<Object>} An array of render bundles.
  50849. */
  50850. _mipmapCreateBundles( textureGPU ) {
  50851. const textureBindingViewDimension = textureGPU.textureBindingViewDimension || '2d-array';
  50852. const pipeline = this.getTransferPipeline( textureGPU.format, textureBindingViewDimension );
  50853. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  50854. const passes = [];
  50855. for ( let baseMipLevel = 1; baseMipLevel < textureGPU.mipLevelCount; baseMipLevel ++ ) {
  50856. for ( let baseArrayLayer = 0; baseArrayLayer < textureGPU.depthOrArrayLayers; baseArrayLayer ++ ) {
  50857. const bindGroup = this.device.createBindGroup( {
  50858. layout: bindGroupLayout,
  50859. entries: [ {
  50860. binding: 0,
  50861. resource: this.mipmapSampler
  50862. }, {
  50863. binding: 1,
  50864. resource: textureGPU.createView( {
  50865. dimension: textureBindingViewDimension,
  50866. baseMipLevel: baseMipLevel - 1,
  50867. mipLevelCount: 1,
  50868. } ),
  50869. }, {
  50870. binding: 2,
  50871. resource: { buffer: this.noFlipUniformBuffer }
  50872. } ]
  50873. } );
  50874. const passDescriptor = {
  50875. colorAttachments: [ {
  50876. view: textureGPU.createView( {
  50877. dimension: '2d',
  50878. baseMipLevel,
  50879. mipLevelCount: 1,
  50880. baseArrayLayer,
  50881. arrayLayerCount: 1,
  50882. } ),
  50883. loadOp: GPULoadOp.Clear,
  50884. storeOp: GPUStoreOp.Store,
  50885. } ]
  50886. };
  50887. const passEncoder = this.device.createRenderBundleEncoder( {
  50888. colorFormats: [ textureGPU.format ]
  50889. } );
  50890. passEncoder.setPipeline( pipeline );
  50891. passEncoder.setBindGroup( 0, bindGroup );
  50892. passEncoder.draw( 3, 1, 0, baseArrayLayer );
  50893. passes.push( {
  50894. renderBundles: [ passEncoder.finish() ],
  50895. passDescriptor
  50896. } );
  50897. }
  50898. }
  50899. return passes;
  50900. }
  50901. /**
  50902. * Executes the render bundles.
  50903. *
  50904. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  50905. * @param {Array<Object>} passes - An array of render bundles.
  50906. */
  50907. _mipmapRunBundles( commandEncoder, passes ) {
  50908. const levels = passes.length;
  50909. for ( let i = 0; i < levels; i ++ ) {
  50910. const pass = passes[ i ];
  50911. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  50912. passEncoder.executeBundles( pass.renderBundles );
  50913. passEncoder.end();
  50914. }
  50915. }
  50916. }
  50917. const _compareToWebGPU = {
  50918. [ NeverCompare ]: 'never',
  50919. [ LessCompare ]: 'less',
  50920. [ EqualCompare ]: 'equal',
  50921. [ LessEqualCompare ]: 'less-equal',
  50922. [ GreaterCompare ]: 'greater',
  50923. [ GreaterEqualCompare ]: 'greater-equal',
  50924. [ AlwaysCompare ]: 'always',
  50925. [ NotEqualCompare ]: 'not-equal'
  50926. };
  50927. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  50928. /**
  50929. * A WebGPU backend utility module for managing textures.
  50930. *
  50931. * @private
  50932. */
  50933. class WebGPUTextureUtils {
  50934. /**
  50935. * Constructs a new utility object.
  50936. *
  50937. * @param {WebGPUBackend} backend - The WebGPU backend.
  50938. */
  50939. constructor( backend ) {
  50940. /**
  50941. * A reference to the WebGPU backend.
  50942. *
  50943. * @type {WebGPUBackend}
  50944. */
  50945. this.backend = backend;
  50946. /**
  50947. * A reference to the pass utils.
  50948. *
  50949. * @type {?WebGPUTexturePassUtils}
  50950. * @default null
  50951. */
  50952. this._passUtils = null;
  50953. /**
  50954. * A dictionary for managing default textures. The key
  50955. * is the texture format, the value the texture object.
  50956. *
  50957. * @type {Object<string,Texture>}
  50958. */
  50959. this.defaultTexture = {};
  50960. /**
  50961. * A dictionary for managing default cube textures. The key
  50962. * is the texture format, the value the texture object.
  50963. *
  50964. * @type {Object<string,CubeTexture>}
  50965. */
  50966. this.defaultCubeTexture = {};
  50967. /**
  50968. * A default video frame.
  50969. *
  50970. * @type {?VideoFrame}
  50971. * @default null
  50972. */
  50973. this.defaultVideoFrame = null;
  50974. /**
  50975. * A cache of shared texture samplers.
  50976. *
  50977. * @type {Map<string, Object>}
  50978. */
  50979. this._samplerCache = new Map();
  50980. }
  50981. /**
  50982. * Creates a GPU sampler for the given texture.
  50983. *
  50984. * @param {Texture} texture - The texture to create the sampler for.
  50985. * @return {string} The current sampler key.
  50986. */
  50987. updateSampler( texture ) {
  50988. const backend = this.backend;
  50989. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  50990. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  50991. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  50992. let samplerData = this._samplerCache.get( samplerKey );
  50993. if ( samplerData === undefined ) {
  50994. const samplerDescriptorGPU = {
  50995. addressModeU: this._convertAddressMode( texture.wrapS ),
  50996. addressModeV: this._convertAddressMode( texture.wrapT ),
  50997. addressModeW: this._convertAddressMode( texture.wrapR ),
  50998. magFilter: this._convertFilterMode( texture.magFilter ),
  50999. minFilter: this._convertFilterMode( texture.minFilter ),
  51000. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  51001. maxAnisotropy: 1
  51002. };
  51003. // Depth textures without compare function must use non-filtering (nearest) sampling
  51004. if ( texture.isDepthTexture && texture.compareFunction === null ) {
  51005. samplerDescriptorGPU.magFilter = GPUFilterMode.Nearest;
  51006. samplerDescriptorGPU.minFilter = GPUFilterMode.Nearest;
  51007. samplerDescriptorGPU.mipmapFilter = GPUFilterMode.Nearest;
  51008. }
  51009. // anisotropy can only be used when all filter modes are set to linear.
  51010. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  51011. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  51012. }
  51013. if ( texture.isDepthTexture && texture.compareFunction !== null && backend.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  51014. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  51015. }
  51016. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  51017. samplerData = { sampler, usedTimes: 0 };
  51018. this._samplerCache.set( samplerKey, samplerData );
  51019. }
  51020. const textureData = backend.get( texture );
  51021. if ( textureData.sampler !== samplerData.sampler ) {
  51022. // check if previous sampler is unused so it can be deleted
  51023. if ( textureData.sampler !== undefined ) {
  51024. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  51025. oldSamplerData.usedTimes --;
  51026. if ( oldSamplerData.usedTimes === 0 ) {
  51027. this._samplerCache.delete( textureData.samplerKey );
  51028. }
  51029. }
  51030. // update to new sampler data
  51031. textureData.samplerKey = samplerKey;
  51032. textureData.sampler = samplerData.sampler;
  51033. samplerData.usedTimes ++;
  51034. }
  51035. return samplerKey;
  51036. }
  51037. /**
  51038. * Creates a default texture for the given texture that can be used
  51039. * as a placeholder until the actual texture is ready for usage.
  51040. *
  51041. * @param {Texture} texture - The texture to create a default texture for.
  51042. */
  51043. createDefaultTexture( texture ) {
  51044. let textureGPU;
  51045. const format = getFormat( texture );
  51046. if ( texture.isCubeTexture ) {
  51047. textureGPU = this._getDefaultCubeTextureGPU( format );
  51048. } else {
  51049. textureGPU = this._getDefaultTextureGPU( format );
  51050. }
  51051. this.backend.get( texture ).texture = textureGPU;
  51052. }
  51053. /**
  51054. * Defines a texture on the GPU for the given texture object.
  51055. *
  51056. * @param {Texture} texture - The texture.
  51057. * @param {Object} [options={}] - Optional configuration parameter.
  51058. */
  51059. createTexture( texture, options = {} ) {
  51060. const backend = this.backend;
  51061. const textureData = backend.get( texture );
  51062. if ( textureData.initialized ) {
  51063. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  51064. }
  51065. if ( texture.isExternalTexture ) {
  51066. textureData.texture = texture.sourceTexture;
  51067. textureData.initialized = true;
  51068. return;
  51069. }
  51070. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  51071. if ( options.levels === undefined ) options.levels = 1;
  51072. if ( options.depth === undefined ) options.depth = 1;
  51073. const { width, height, depth, levels } = options;
  51074. if ( texture.isFramebufferTexture ) {
  51075. if ( options.renderTarget ) {
  51076. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  51077. } else {
  51078. options.format = this.backend.utils.getPreferredCanvasFormat();
  51079. }
  51080. }
  51081. const dimension = this._getDimension( texture );
  51082. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  51083. textureData.format = format;
  51084. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  51085. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  51086. if ( texture.isStorageTexture === true ) {
  51087. usage |= GPUTextureUsage.STORAGE_BINDING;
  51088. }
  51089. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  51090. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  51091. }
  51092. const textureDescriptorGPU = {
  51093. label: texture.name,
  51094. size: {
  51095. width: width,
  51096. height: height,
  51097. depthOrArrayLayers: depth,
  51098. },
  51099. mipLevelCount: levels,
  51100. sampleCount: primarySamples,
  51101. dimension: dimension,
  51102. format: format,
  51103. usage: usage
  51104. };
  51105. // texture creation
  51106. if ( format === undefined ) {
  51107. warn( 'WebGPURenderer: Texture format not supported.' );
  51108. this.createDefaultTexture( texture );
  51109. return;
  51110. }
  51111. if ( texture.isCubeTexture ) {
  51112. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  51113. }
  51114. try {
  51115. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  51116. } catch ( e ) {
  51117. warn( 'WebGPURenderer: Failed to create texture with descriptor:', textureDescriptorGPU );
  51118. this.createDefaultTexture( texture );
  51119. return;
  51120. }
  51121. if ( isMSAA ) {
  51122. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  51123. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  51124. msaaTextureDescriptorGPU.sampleCount = samples;
  51125. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  51126. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  51127. }
  51128. textureData.initialized = true;
  51129. textureData.textureDescriptorGPU = textureDescriptorGPU;
  51130. }
  51131. /**
  51132. * Destroys the GPU data for the given texture object.
  51133. *
  51134. * @param {Texture} texture - The texture.
  51135. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  51136. */
  51137. destroyTexture( texture, isDefaultTexture = false ) {
  51138. const backend = this.backend;
  51139. const textureData = backend.get( texture );
  51140. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  51141. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  51142. backend.delete( texture );
  51143. }
  51144. /**
  51145. * Generates mipmaps for the given texture.
  51146. *
  51147. * @param {Texture} texture - The texture.
  51148. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  51149. */
  51150. generateMipmaps( texture, encoder = null ) {
  51151. const textureData = this.backend.get( texture );
  51152. this._generateMipmaps( textureData.texture, encoder );
  51153. }
  51154. /**
  51155. * Returns the color buffer representing the color
  51156. * attachment of the default framebuffer.
  51157. *
  51158. * @return {GPUTexture} The color buffer.
  51159. */
  51160. getColorBuffer() {
  51161. const backend = this.backend;
  51162. const canvasTarget = backend.renderer.getCanvasTarget();
  51163. const { width, height } = backend.getDrawingBufferSize();
  51164. const samples = backend.renderer.currentSamples;
  51165. const colorTexture = canvasTarget.colorTexture;
  51166. const colorTextureData = backend.get( colorTexture );
  51167. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  51168. return colorTextureData.texture;
  51169. }
  51170. // recreate
  51171. let colorBuffer = colorTextureData.texture;
  51172. if ( colorBuffer ) colorBuffer.destroy();
  51173. colorBuffer = backend.device.createTexture( {
  51174. label: 'colorBuffer',
  51175. size: {
  51176. width: width,
  51177. height: height,
  51178. depthOrArrayLayers: 1
  51179. },
  51180. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  51181. format: backend.utils.getPreferredCanvasFormat(),
  51182. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  51183. } );
  51184. //
  51185. colorTexture.source.width = width;
  51186. colorTexture.source.height = height;
  51187. colorTexture.samples = samples;
  51188. colorTextureData.texture = colorBuffer;
  51189. return colorBuffer;
  51190. }
  51191. /**
  51192. * Returns the depth buffer representing the depth
  51193. * attachment of the default framebuffer.
  51194. *
  51195. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  51196. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  51197. * @return {GPUTexture} The depth buffer.
  51198. */
  51199. getDepthBuffer( depth = true, stencil = false ) {
  51200. const backend = this.backend;
  51201. const canvasTarget = backend.renderer.getCanvasTarget();
  51202. const { width, height } = backend.getDrawingBufferSize();
  51203. const samples = backend.renderer.currentSamples;
  51204. const depthTexture = canvasTarget.depthTexture;
  51205. if ( depthTexture.width === width &&
  51206. depthTexture.height === height &&
  51207. depthTexture.samples === samples &&
  51208. depthTexture.depth === depth &&
  51209. depthTexture.stencil === stencil ) {
  51210. return backend.get( depthTexture ).texture;
  51211. }
  51212. //
  51213. const depthTextureGPU = backend.get( depthTexture ).texture;
  51214. let format, type;
  51215. if ( stencil ) {
  51216. format = DepthStencilFormat;
  51217. type = UnsignedInt248Type;
  51218. } else if ( depth ) {
  51219. format = DepthFormat;
  51220. type = UnsignedIntType;
  51221. }
  51222. if ( depthTextureGPU !== undefined ) {
  51223. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  51224. return depthTextureGPU;
  51225. }
  51226. this.destroyTexture( depthTexture );
  51227. }
  51228. // recreate
  51229. depthTexture.name = 'depthBuffer';
  51230. depthTexture.format = format;
  51231. depthTexture.type = type;
  51232. depthTexture.image.width = width;
  51233. depthTexture.image.height = height;
  51234. depthTexture.samples = samples;
  51235. this.createTexture( depthTexture, { width, height } );
  51236. return backend.get( depthTexture ).texture;
  51237. }
  51238. /**
  51239. * Uploads the updated texture data to the GPU.
  51240. *
  51241. * @param {Texture} texture - The texture.
  51242. * @param {Object} [options={}] - Optional configuration parameter.
  51243. */
  51244. updateTexture( texture, options ) {
  51245. const textureData = this.backend.get( texture );
  51246. const mipmaps = texture.mipmaps;
  51247. const { textureDescriptorGPU } = textureData;
  51248. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  51249. return;
  51250. // transfer texture data
  51251. if ( texture.isDataTexture ) {
  51252. if ( mipmaps.length > 0 ) {
  51253. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  51254. const mipmap = mipmaps[ i ];
  51255. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  51256. }
  51257. } else {
  51258. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  51259. }
  51260. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  51261. for ( let i = 0; i < options.image.depth; i ++ ) {
  51262. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  51263. }
  51264. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  51265. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  51266. } else if ( texture.isCubeTexture ) {
  51267. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  51268. } else {
  51269. if ( mipmaps.length > 0 ) {
  51270. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  51271. const mipmap = mipmaps[ i ];
  51272. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  51273. }
  51274. } else {
  51275. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  51276. }
  51277. }
  51278. //
  51279. textureData.version = texture.version;
  51280. }
  51281. /**
  51282. * Returns texture data as a typed array.
  51283. *
  51284. * @async
  51285. * @param {Texture} texture - The texture to copy.
  51286. * @param {number} x - The x coordinate of the copy origin.
  51287. * @param {number} y - The y coordinate of the copy origin.
  51288. * @param {number} width - The width of the copy.
  51289. * @param {number} height - The height of the copy.
  51290. * @param {number} faceIndex - The face index.
  51291. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  51292. */
  51293. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  51294. const device = this.backend.device;
  51295. const textureData = this.backend.get( texture );
  51296. const textureGPU = textureData.texture;
  51297. const format = textureData.textureDescriptorGPU.format;
  51298. const bytesPerTexel = this._getBytesPerTexel( format );
  51299. let bytesPerRow = width * bytesPerTexel;
  51300. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  51301. const readBuffer = device.createBuffer(
  51302. {
  51303. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  51304. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  51305. }
  51306. );
  51307. const encoder = device.createCommandEncoder();
  51308. encoder.copyTextureToBuffer(
  51309. {
  51310. texture: textureGPU,
  51311. origin: { x, y, z: faceIndex },
  51312. },
  51313. {
  51314. buffer: readBuffer,
  51315. bytesPerRow: bytesPerRow
  51316. },
  51317. {
  51318. width: width,
  51319. height: height
  51320. }
  51321. );
  51322. const typedArrayType = this._getTypedArrayType( format );
  51323. device.queue.submit( [ encoder.finish() ] );
  51324. await readBuffer.mapAsync( GPUMapMode.READ );
  51325. const buffer = readBuffer.getMappedRange();
  51326. return new typedArrayType( buffer );
  51327. }
  51328. /**
  51329. * Frees all internal resources.
  51330. */
  51331. dispose() {
  51332. this._samplerCache.clear();
  51333. }
  51334. /**
  51335. * Returns the default GPU texture for the given format.
  51336. *
  51337. * @private
  51338. * @param {string} format - The GPU format.
  51339. * @return {GPUTexture} The GPU texture.
  51340. */
  51341. _getDefaultTextureGPU( format ) {
  51342. let defaultTexture = this.defaultTexture[ format ];
  51343. if ( defaultTexture === undefined ) {
  51344. const texture = new Texture();
  51345. texture.minFilter = NearestFilter;
  51346. texture.magFilter = NearestFilter;
  51347. this.createTexture( texture, { width: 1, height: 1, format } );
  51348. this.defaultTexture[ format ] = defaultTexture = texture;
  51349. }
  51350. return this.backend.get( defaultTexture ).texture;
  51351. }
  51352. /**
  51353. * Returns the default GPU cube texture for the given format.
  51354. *
  51355. * @private
  51356. * @param {string} format - The GPU format.
  51357. * @return {GPUTexture} The GPU texture.
  51358. */
  51359. _getDefaultCubeTextureGPU( format ) {
  51360. let defaultCubeTexture = this.defaultCubeTexture[ format ];
  51361. if ( defaultCubeTexture === undefined ) {
  51362. const texture = new CubeTexture();
  51363. texture.minFilter = NearestFilter;
  51364. texture.magFilter = NearestFilter;
  51365. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  51366. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  51367. }
  51368. return this.backend.get( defaultCubeTexture ).texture;
  51369. }
  51370. /**
  51371. * Uploads cube texture image data to the GPU memory.
  51372. *
  51373. * @private
  51374. * @param {CubeTexture} texture - The cube texture.
  51375. * @param {GPUTexture} textureGPU - The GPU texture.
  51376. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51377. */
  51378. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  51379. const images = texture.images;
  51380. const mipmaps = texture.mipmaps;
  51381. for ( let i = 0; i < 6; i ++ ) {
  51382. const image = images[ i ];
  51383. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  51384. if ( image.isDataTexture ) {
  51385. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  51386. } else {
  51387. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  51388. }
  51389. for ( let j = 0; j < mipmaps.length; j ++ ) {
  51390. const mipmap = mipmaps[ j ];
  51391. const image = mipmap.images[ i ];
  51392. if ( image.isDataTexture ) {
  51393. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  51394. } else {
  51395. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  51396. }
  51397. }
  51398. }
  51399. }
  51400. /**
  51401. * Uploads texture image data to the GPU memory.
  51402. *
  51403. * @private
  51404. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  51405. * @param {GPUTexture} textureGPU - The GPU texture.
  51406. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51407. * @param {number} originDepth - The origin depth.
  51408. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  51409. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  51410. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  51411. */
  51412. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  51413. const device = this.backend.device;
  51414. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  51415. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  51416. try {
  51417. device.queue.copyExternalImageToTexture(
  51418. {
  51419. source: image,
  51420. flipY: flipY
  51421. }, {
  51422. texture: textureGPU,
  51423. mipLevel: mipLevel,
  51424. origin: { x: 0, y: 0, z: originDepth },
  51425. premultipliedAlpha: premultiplyAlpha
  51426. }, {
  51427. width: width,
  51428. height: height,
  51429. depthOrArrayLayers: 1
  51430. }
  51431. );
  51432. // try/catch has been added to fix bad video frame data on certain devices, see #32391
  51433. } catch ( _ ) {}
  51434. }
  51435. /**
  51436. * Returns the pass utils singleton.
  51437. *
  51438. * @private
  51439. * @return {WebGPUTexturePassUtils} The utils instance.
  51440. */
  51441. _getPassUtils() {
  51442. let passUtils = this._passUtils;
  51443. if ( passUtils === null ) {
  51444. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  51445. }
  51446. return passUtils;
  51447. }
  51448. /**
  51449. * Generates mipmaps for the given GPU texture.
  51450. *
  51451. * @private
  51452. * @param {GPUTexture} textureGPU - The GPU texture object.
  51453. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  51454. */
  51455. _generateMipmaps( textureGPU, encoder = null ) {
  51456. this._getPassUtils().generateMipmaps( textureGPU, encoder );
  51457. }
  51458. /**
  51459. * Flip the contents of the given GPU texture along its vertical axis.
  51460. *
  51461. * @private
  51462. * @param {GPUTexture} textureGPU - The GPU texture object.
  51463. * @param {Object} textureDescriptorGPU - The texture descriptor.
  51464. * @param {number} [originDepth=0] - The origin depth.
  51465. */
  51466. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  51467. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  51468. }
  51469. /**
  51470. * Uploads texture buffer data to the GPU memory.
  51471. *
  51472. * @private
  51473. * @param {Object} image - An object defining the image buffer data.
  51474. * @param {GPUTexture} textureGPU - The GPU texture.
  51475. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51476. * @param {number} originDepth - The origin depth.
  51477. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  51478. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  51479. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  51480. */
  51481. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  51482. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51483. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  51484. const device = this.backend.device;
  51485. const data = image.data;
  51486. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  51487. const bytesPerRow = image.width * bytesPerTexel;
  51488. device.queue.writeTexture(
  51489. {
  51490. texture: textureGPU,
  51491. mipLevel: mipLevel,
  51492. origin: { x: 0, y: 0, z: originDepth }
  51493. },
  51494. data,
  51495. {
  51496. offset: image.width * image.height * bytesPerTexel * depth,
  51497. bytesPerRow
  51498. },
  51499. {
  51500. width: image.width,
  51501. height: image.height,
  51502. depthOrArrayLayers: 1
  51503. } );
  51504. if ( flipY === true ) {
  51505. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  51506. }
  51507. }
  51508. /**
  51509. * Uploads compressed texture data to the GPU memory.
  51510. *
  51511. * @private
  51512. * @param {Array<Object>} mipmaps - An array with mipmap data.
  51513. * @param {GPUTexture} textureGPU - The GPU texture.
  51514. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51515. */
  51516. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  51517. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51518. const device = this.backend.device;
  51519. const blockData = this._getBlockData( textureDescriptorGPU.format );
  51520. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  51521. for ( let i = 0; i < mipmaps.length; i ++ ) {
  51522. const mipmap = mipmaps[ i ];
  51523. const width = mipmap.width;
  51524. const height = mipmap.height;
  51525. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  51526. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  51527. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  51528. for ( let j = 0; j < depth; j ++ ) {
  51529. device.queue.writeTexture(
  51530. {
  51531. texture: textureGPU,
  51532. mipLevel: i,
  51533. origin: { x: 0, y: 0, z: j }
  51534. },
  51535. mipmap.data,
  51536. {
  51537. offset: j * bytesPerImage,
  51538. bytesPerRow,
  51539. rowsPerImage: Math.ceil( height / blockData.height )
  51540. },
  51541. {
  51542. width: Math.ceil( width / blockData.width ) * blockData.width,
  51543. height: Math.ceil( height / blockData.height ) * blockData.height,
  51544. depthOrArrayLayers: 1
  51545. }
  51546. );
  51547. }
  51548. }
  51549. }
  51550. /**
  51551. * This method is only relevant for compressed texture formats. It returns a block
  51552. * data descriptor for the given GPU compressed texture format.
  51553. *
  51554. * @private
  51555. * @param {string} format - The GPU compressed texture format.
  51556. * @return {Object} The block data descriptor.
  51557. */
  51558. _getBlockData( format ) {
  51559. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  51560. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  51561. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  51562. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  51563. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  51564. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  51565. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  51566. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51567. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51568. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51569. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  51570. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  51571. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  51572. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  51573. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51574. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  51575. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  51576. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  51577. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  51578. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  51579. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  51580. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  51581. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  51582. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  51583. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  51584. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  51585. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  51586. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  51587. }
  51588. /**
  51589. * Converts the three.js uv wrapping constants to GPU address mode constants.
  51590. *
  51591. * @private
  51592. * @param {number} value - The three.js constant defining a uv wrapping mode.
  51593. * @return {string} The GPU address mode.
  51594. */
  51595. _convertAddressMode( value ) {
  51596. let addressMode = GPUAddressMode.ClampToEdge;
  51597. if ( value === RepeatWrapping ) {
  51598. addressMode = GPUAddressMode.Repeat;
  51599. } else if ( value === MirroredRepeatWrapping ) {
  51600. addressMode = GPUAddressMode.MirrorRepeat;
  51601. }
  51602. return addressMode;
  51603. }
  51604. /**
  51605. * Converts the three.js filter constants to GPU filter constants.
  51606. *
  51607. * @private
  51608. * @param {number} value - The three.js constant defining a filter mode.
  51609. * @return {string} The GPU filter mode.
  51610. */
  51611. _convertFilterMode( value ) {
  51612. let filterMode = GPUFilterMode.Linear;
  51613. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  51614. filterMode = GPUFilterMode.Nearest;
  51615. }
  51616. return filterMode;
  51617. }
  51618. /**
  51619. * Returns the bytes-per-texel value for the given GPU texture format.
  51620. *
  51621. * @private
  51622. * @param {string} format - The GPU texture format.
  51623. * @return {number} The bytes-per-texel.
  51624. */
  51625. _getBytesPerTexel( format ) {
  51626. // 8-bit formats
  51627. if ( format === GPUTextureFormat.R8Unorm ||
  51628. format === GPUTextureFormat.R8Snorm ||
  51629. format === GPUTextureFormat.R8Uint ||
  51630. format === GPUTextureFormat.R8Sint ) return 1;
  51631. // 16-bit formats
  51632. if ( format === GPUTextureFormat.R16Uint ||
  51633. format === GPUTextureFormat.R16Sint ||
  51634. format === GPUTextureFormat.R16Float ||
  51635. format === GPUTextureFormat.RG8Unorm ||
  51636. format === GPUTextureFormat.RG8Snorm ||
  51637. format === GPUTextureFormat.RG8Uint ||
  51638. format === GPUTextureFormat.RG8Sint ) return 2;
  51639. // 32-bit formats
  51640. if ( format === GPUTextureFormat.R32Uint ||
  51641. format === GPUTextureFormat.R32Sint ||
  51642. format === GPUTextureFormat.R32Float ||
  51643. format === GPUTextureFormat.RG16Uint ||
  51644. format === GPUTextureFormat.RG16Sint ||
  51645. format === GPUTextureFormat.RG16Float ||
  51646. format === GPUTextureFormat.RGBA8Unorm ||
  51647. format === GPUTextureFormat.RGBA8UnormSRGB ||
  51648. format === GPUTextureFormat.RGBA8Snorm ||
  51649. format === GPUTextureFormat.RGBA8Uint ||
  51650. format === GPUTextureFormat.RGBA8Sint ||
  51651. format === GPUTextureFormat.BGRA8Unorm ||
  51652. format === GPUTextureFormat.BGRA8UnormSRGB ||
  51653. // Packed 32-bit formats
  51654. format === GPUTextureFormat.RGB9E5UFloat ||
  51655. format === GPUTextureFormat.RGB10A2Unorm ||
  51656. format === GPUTextureFormat.RG11B10UFloat ||
  51657. format === GPUTextureFormat.Depth32Float ||
  51658. format === GPUTextureFormat.Depth24Plus ||
  51659. format === GPUTextureFormat.Depth24PlusStencil8 ||
  51660. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  51661. // 64-bit formats
  51662. if ( format === GPUTextureFormat.RG32Uint ||
  51663. format === GPUTextureFormat.RG32Sint ||
  51664. format === GPUTextureFormat.RG32Float ||
  51665. format === GPUTextureFormat.RGBA16Uint ||
  51666. format === GPUTextureFormat.RGBA16Sint ||
  51667. format === GPUTextureFormat.RGBA16Float ) return 8;
  51668. // 128-bit formats
  51669. if ( format === GPUTextureFormat.RGBA32Uint ||
  51670. format === GPUTextureFormat.RGBA32Sint ||
  51671. format === GPUTextureFormat.RGBA32Float ) return 16;
  51672. }
  51673. /**
  51674. * Returns the corresponding typed array type for the given GPU texture format.
  51675. *
  51676. * @private
  51677. * @param {string} format - The GPU texture format.
  51678. * @return {TypedArray.constructor} The typed array type.
  51679. */
  51680. _getTypedArrayType( format ) {
  51681. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  51682. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  51683. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  51684. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  51685. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  51686. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  51687. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  51688. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  51689. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  51690. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  51691. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  51692. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  51693. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  51694. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  51695. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  51696. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  51697. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  51698. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  51699. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  51700. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  51701. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  51702. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  51703. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  51704. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  51705. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  51706. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  51707. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  51708. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  51709. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  51710. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  51711. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  51712. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  51713. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  51714. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  51715. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  51716. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  51717. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  51718. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  51719. }
  51720. /**
  51721. * Returns the GPU dimensions for the given texture.
  51722. *
  51723. * @private
  51724. * @param {Texture} texture - The texture.
  51725. * @return {string} The GPU dimension.
  51726. */
  51727. _getDimension( texture ) {
  51728. let dimension;
  51729. if ( texture.is3DTexture || texture.isData3DTexture ) {
  51730. dimension = GPUTextureDimension.ThreeD;
  51731. } else {
  51732. dimension = GPUTextureDimension.TwoD;
  51733. }
  51734. return dimension;
  51735. }
  51736. }
  51737. /**
  51738. * Returns the GPU format for the given texture.
  51739. *
  51740. * @param {Texture} texture - The texture.
  51741. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  51742. * It is not necessary to apply the device for most formats.
  51743. * @return {string} The GPU format.
  51744. */
  51745. function getFormat( texture, device = null ) {
  51746. const format = texture.format;
  51747. const type = texture.type;
  51748. const colorSpace = texture.colorSpace;
  51749. const transfer = ColorManagement.getTransfer( colorSpace );
  51750. let formatGPU;
  51751. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  51752. switch ( format ) {
  51753. case RGB_S3TC_DXT1_Format:
  51754. case RGBA_S3TC_DXT1_Format:
  51755. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  51756. break;
  51757. case RGBA_S3TC_DXT3_Format:
  51758. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  51759. break;
  51760. case RGBA_S3TC_DXT5_Format:
  51761. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  51762. break;
  51763. case RED_RGTC1_Format:
  51764. formatGPU = GPUTextureFormat.BC4RUnorm;
  51765. break;
  51766. case SIGNED_RED_RGTC1_Format:
  51767. formatGPU = GPUTextureFormat.BC4RSnorm;
  51768. break;
  51769. case RED_GREEN_RGTC2_Format:
  51770. formatGPU = GPUTextureFormat.BC5RGUnorm;
  51771. break;
  51772. case SIGNED_RED_GREEN_RGTC2_Format:
  51773. formatGPU = GPUTextureFormat.BC5RGSnorm;
  51774. break;
  51775. case RGBA_BPTC_Format:
  51776. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  51777. break;
  51778. case RGB_ETC2_Format:
  51779. case RGB_ETC1_Format:
  51780. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  51781. break;
  51782. case RGBA_ETC2_EAC_Format:
  51783. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  51784. break;
  51785. case R11_EAC_Format:
  51786. formatGPU = GPUTextureFormat.EACR11Unorm;
  51787. break;
  51788. case SIGNED_R11_EAC_Format:
  51789. formatGPU = GPUTextureFormat.EACR11Snorm;
  51790. break;
  51791. case RG11_EAC_Format:
  51792. formatGPU = GPUTextureFormat.EACRG11Unorm;
  51793. break;
  51794. case SIGNED_RG11_EAC_Format:
  51795. formatGPU = GPUTextureFormat.EACRG11Snorm;
  51796. break;
  51797. case RGBA_ASTC_4x4_Format:
  51798. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  51799. break;
  51800. case RGBA_ASTC_5x4_Format:
  51801. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  51802. break;
  51803. case RGBA_ASTC_5x5_Format:
  51804. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  51805. break;
  51806. case RGBA_ASTC_6x5_Format:
  51807. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  51808. break;
  51809. case RGBA_ASTC_6x6_Format:
  51810. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  51811. break;
  51812. case RGBA_ASTC_8x5_Format:
  51813. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  51814. break;
  51815. case RGBA_ASTC_8x6_Format:
  51816. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  51817. break;
  51818. case RGBA_ASTC_8x8_Format:
  51819. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  51820. break;
  51821. case RGBA_ASTC_10x5_Format:
  51822. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  51823. break;
  51824. case RGBA_ASTC_10x6_Format:
  51825. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  51826. break;
  51827. case RGBA_ASTC_10x8_Format:
  51828. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  51829. break;
  51830. case RGBA_ASTC_10x10_Format:
  51831. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  51832. break;
  51833. case RGBA_ASTC_12x10_Format:
  51834. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  51835. break;
  51836. case RGBA_ASTC_12x12_Format:
  51837. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  51838. break;
  51839. case RGBAFormat:
  51840. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  51841. break;
  51842. default:
  51843. error( 'WebGPURenderer: Unsupported texture format.', format );
  51844. }
  51845. } else {
  51846. switch ( format ) {
  51847. case RGBAFormat:
  51848. switch ( type ) {
  51849. case ByteType:
  51850. formatGPU = GPUTextureFormat.RGBA8Snorm;
  51851. break;
  51852. case ShortType:
  51853. formatGPU = GPUTextureFormat.RGBA16Sint;
  51854. break;
  51855. case UnsignedShortType:
  51856. formatGPU = GPUTextureFormat.RGBA16Uint;
  51857. break;
  51858. case UnsignedIntType:
  51859. formatGPU = GPUTextureFormat.RGBA32Uint;
  51860. break;
  51861. case IntType:
  51862. formatGPU = GPUTextureFormat.RGBA32Sint;
  51863. break;
  51864. case UnsignedByteType:
  51865. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  51866. break;
  51867. case HalfFloatType:
  51868. formatGPU = GPUTextureFormat.RGBA16Float;
  51869. break;
  51870. case FloatType:
  51871. formatGPU = GPUTextureFormat.RGBA32Float;
  51872. break;
  51873. default:
  51874. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  51875. }
  51876. break;
  51877. case RGBFormat:
  51878. switch ( type ) {
  51879. case UnsignedInt5999Type:
  51880. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  51881. break;
  51882. case UnsignedInt101111Type:
  51883. formatGPU = GPUTextureFormat.RG11B10UFloat;
  51884. break;
  51885. default:
  51886. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  51887. }
  51888. break;
  51889. case RedFormat:
  51890. switch ( type ) {
  51891. case ByteType:
  51892. formatGPU = GPUTextureFormat.R8Snorm;
  51893. break;
  51894. case ShortType:
  51895. formatGPU = GPUTextureFormat.R16Sint;
  51896. break;
  51897. case UnsignedShortType:
  51898. formatGPU = GPUTextureFormat.R16Uint;
  51899. break;
  51900. case UnsignedIntType:
  51901. formatGPU = GPUTextureFormat.R32Uint;
  51902. break;
  51903. case IntType:
  51904. formatGPU = GPUTextureFormat.R32Sint;
  51905. break;
  51906. case UnsignedByteType:
  51907. formatGPU = GPUTextureFormat.R8Unorm;
  51908. break;
  51909. case HalfFloatType:
  51910. formatGPU = GPUTextureFormat.R16Float;
  51911. break;
  51912. case FloatType:
  51913. formatGPU = GPUTextureFormat.R32Float;
  51914. break;
  51915. default:
  51916. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  51917. }
  51918. break;
  51919. case RGFormat:
  51920. switch ( type ) {
  51921. case ByteType:
  51922. formatGPU = GPUTextureFormat.RG8Snorm;
  51923. break;
  51924. case ShortType:
  51925. formatGPU = GPUTextureFormat.RG16Sint;
  51926. break;
  51927. case UnsignedShortType:
  51928. formatGPU = GPUTextureFormat.RG16Uint;
  51929. break;
  51930. case UnsignedIntType:
  51931. formatGPU = GPUTextureFormat.RG32Uint;
  51932. break;
  51933. case IntType:
  51934. formatGPU = GPUTextureFormat.RG32Sint;
  51935. break;
  51936. case UnsignedByteType:
  51937. formatGPU = GPUTextureFormat.RG8Unorm;
  51938. break;
  51939. case HalfFloatType:
  51940. formatGPU = GPUTextureFormat.RG16Float;
  51941. break;
  51942. case FloatType:
  51943. formatGPU = GPUTextureFormat.RG32Float;
  51944. break;
  51945. default:
  51946. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  51947. }
  51948. break;
  51949. case DepthFormat:
  51950. switch ( type ) {
  51951. case UnsignedShortType:
  51952. formatGPU = GPUTextureFormat.Depth16Unorm;
  51953. break;
  51954. case UnsignedIntType:
  51955. formatGPU = GPUTextureFormat.Depth24Plus;
  51956. break;
  51957. case FloatType:
  51958. formatGPU = GPUTextureFormat.Depth32Float;
  51959. break;
  51960. default:
  51961. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  51962. }
  51963. break;
  51964. case DepthStencilFormat:
  51965. switch ( type ) {
  51966. case UnsignedInt248Type:
  51967. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  51968. break;
  51969. case FloatType:
  51970. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  51971. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  51972. }
  51973. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  51974. break;
  51975. default:
  51976. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  51977. }
  51978. break;
  51979. case RedIntegerFormat:
  51980. switch ( type ) {
  51981. case IntType:
  51982. formatGPU = GPUTextureFormat.R32Sint;
  51983. break;
  51984. case UnsignedIntType:
  51985. formatGPU = GPUTextureFormat.R32Uint;
  51986. break;
  51987. default:
  51988. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  51989. }
  51990. break;
  51991. case RGIntegerFormat:
  51992. switch ( type ) {
  51993. case IntType:
  51994. formatGPU = GPUTextureFormat.RG32Sint;
  51995. break;
  51996. case UnsignedIntType:
  51997. formatGPU = GPUTextureFormat.RG32Uint;
  51998. break;
  51999. default:
  52000. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  52001. }
  52002. break;
  52003. case RGBAIntegerFormat:
  52004. switch ( type ) {
  52005. case IntType:
  52006. formatGPU = GPUTextureFormat.RGBA32Sint;
  52007. break;
  52008. case UnsignedIntType:
  52009. formatGPU = GPUTextureFormat.RGBA32Uint;
  52010. break;
  52011. default:
  52012. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  52013. }
  52014. break;
  52015. default:
  52016. error( 'WebGPURenderer: Unsupported texture format.', format );
  52017. }
  52018. }
  52019. return formatGPU;
  52020. }
  52021. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  52022. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  52023. const wgslTypeLib$1 = {
  52024. 'f32': 'float',
  52025. 'i32': 'int',
  52026. 'u32': 'uint',
  52027. 'bool': 'bool',
  52028. 'vec2<f32>': 'vec2',
  52029. 'vec2<i32>': 'ivec2',
  52030. 'vec2<u32>': 'uvec2',
  52031. 'vec2<bool>': 'bvec2',
  52032. 'vec2f': 'vec2',
  52033. 'vec2i': 'ivec2',
  52034. 'vec2u': 'uvec2',
  52035. 'vec2b': 'bvec2',
  52036. 'vec3<f32>': 'vec3',
  52037. 'vec3<i32>': 'ivec3',
  52038. 'vec3<u32>': 'uvec3',
  52039. 'vec3<bool>': 'bvec3',
  52040. 'vec3f': 'vec3',
  52041. 'vec3i': 'ivec3',
  52042. 'vec3u': 'uvec3',
  52043. 'vec3b': 'bvec3',
  52044. 'vec4<f32>': 'vec4',
  52045. 'vec4<i32>': 'ivec4',
  52046. 'vec4<u32>': 'uvec4',
  52047. 'vec4<bool>': 'bvec4',
  52048. 'vec4f': 'vec4',
  52049. 'vec4i': 'ivec4',
  52050. 'vec4u': 'uvec4',
  52051. 'vec4b': 'bvec4',
  52052. 'mat2x2<f32>': 'mat2',
  52053. 'mat2x2f': 'mat2',
  52054. 'mat3x3<f32>': 'mat3',
  52055. 'mat3x3f': 'mat3',
  52056. 'mat4x4<f32>': 'mat4',
  52057. 'mat4x4f': 'mat4',
  52058. 'sampler': 'sampler',
  52059. 'texture_1d': 'texture',
  52060. 'texture_2d': 'texture',
  52061. 'texture_2d_array': 'texture',
  52062. 'texture_multisampled_2d': 'cubeTexture',
  52063. 'texture_depth_2d': 'depthTexture',
  52064. 'texture_depth_2d_array': 'depthTexture',
  52065. 'texture_depth_multisampled_2d': 'depthTexture',
  52066. 'texture_depth_cube': 'depthTexture',
  52067. 'texture_depth_cube_array': 'depthTexture',
  52068. 'texture_3d': 'texture3D',
  52069. 'texture_cube': 'cubeTexture',
  52070. 'texture_cube_array': 'cubeTexture',
  52071. 'texture_storage_1d': 'storageTexture',
  52072. 'texture_storage_2d': 'storageTexture',
  52073. 'texture_storage_2d_array': 'storageTexture',
  52074. 'texture_storage_3d': 'storageTexture'
  52075. };
  52076. const parse = ( source ) => {
  52077. source = source.trim();
  52078. const declaration = source.match( declarationRegexp );
  52079. if ( declaration !== null && declaration.length === 4 ) {
  52080. const inputsCode = declaration[ 2 ];
  52081. const propsMatches = [];
  52082. let match = null;
  52083. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  52084. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  52085. }
  52086. // Process matches to correctly pair names and types
  52087. const inputs = [];
  52088. for ( let i = 0; i < propsMatches.length; i ++ ) {
  52089. const { name, type } = propsMatches[ i ];
  52090. let resolvedType = type;
  52091. if ( resolvedType.startsWith( 'ptr' ) ) {
  52092. resolvedType = 'pointer';
  52093. } else {
  52094. if ( resolvedType.startsWith( 'texture' ) ) {
  52095. resolvedType = type.split( '<' )[ 0 ];
  52096. }
  52097. resolvedType = wgslTypeLib$1[ resolvedType ];
  52098. }
  52099. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  52100. }
  52101. const blockCode = source.substring( declaration[ 0 ].length );
  52102. const outputType = declaration[ 3 ] || 'void';
  52103. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  52104. const type = wgslTypeLib$1[ outputType ] || outputType;
  52105. return {
  52106. type,
  52107. inputs,
  52108. name,
  52109. inputsCode,
  52110. blockCode,
  52111. outputType
  52112. };
  52113. } else {
  52114. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  52115. }
  52116. };
  52117. /**
  52118. * This class represents a WSL node function.
  52119. *
  52120. * @augments NodeFunction
  52121. */
  52122. class WGSLNodeFunction extends NodeFunction {
  52123. /**
  52124. * Constructs a new WGSL node function.
  52125. *
  52126. * @param {string} source - The WGSL source.
  52127. */
  52128. constructor( source ) {
  52129. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  52130. super( type, inputs, name );
  52131. this.inputsCode = inputsCode;
  52132. this.blockCode = blockCode;
  52133. this.outputType = outputType;
  52134. }
  52135. /**
  52136. * This method returns the WGSL code of the node function.
  52137. *
  52138. * @param {string} [name=this.name] - The function's name.
  52139. * @return {string} The shader code.
  52140. */
  52141. getCode( name = this.name ) {
  52142. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  52143. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  52144. }
  52145. }
  52146. /**
  52147. * A WGSL node parser.
  52148. *
  52149. * @augments NodeParser
  52150. */
  52151. class WGSLNodeParser extends NodeParser {
  52152. /**
  52153. * The method parses the given WGSL code an returns a node function.
  52154. *
  52155. * @param {string} source - The WGSL code.
  52156. * @return {WGSLNodeFunction} A node function.
  52157. */
  52158. parseFunction( source ) {
  52159. return new WGSLNodeFunction( source );
  52160. }
  52161. }
  52162. const accessNames = {
  52163. [ NodeAccess.READ_ONLY ]: 'read',
  52164. [ NodeAccess.WRITE_ONLY ]: 'write',
  52165. [ NodeAccess.READ_WRITE ]: 'read_write'
  52166. };
  52167. const wrapNames = {
  52168. [ RepeatWrapping ]: 'repeat',
  52169. [ ClampToEdgeWrapping ]: 'clamp',
  52170. [ MirroredRepeatWrapping ]: 'mirror'
  52171. };
  52172. const gpuShaderStageLib = {
  52173. 'vertex': GPUShaderStage.VERTEX,
  52174. 'fragment': GPUShaderStage.FRAGMENT,
  52175. 'compute': GPUShaderStage.COMPUTE
  52176. };
  52177. const supports = {
  52178. instance: true,
  52179. swizzleAssign: false,
  52180. storageBuffer: true
  52181. };
  52182. const wgslFnOpLib = {
  52183. '^^': 'tsl_xor'
  52184. };
  52185. const wgslTypeLib = {
  52186. float: 'f32',
  52187. int: 'i32',
  52188. uint: 'u32',
  52189. bool: 'bool',
  52190. color: 'vec3<f32>',
  52191. vec2: 'vec2<f32>',
  52192. ivec2: 'vec2<i32>',
  52193. uvec2: 'vec2<u32>',
  52194. bvec2: 'vec2<bool>',
  52195. vec3: 'vec3<f32>',
  52196. ivec3: 'vec3<i32>',
  52197. uvec3: 'vec3<u32>',
  52198. bvec3: 'vec3<bool>',
  52199. vec4: 'vec4<f32>',
  52200. ivec4: 'vec4<i32>',
  52201. uvec4: 'vec4<u32>',
  52202. bvec4: 'vec4<bool>',
  52203. mat2: 'mat2x2<f32>',
  52204. mat3: 'mat3x3<f32>',
  52205. mat4: 'mat4x4<f32>'
  52206. };
  52207. const wgslCodeCache = {};
  52208. const wgslPolyfill = {
  52209. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  52210. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  52211. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  52212. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  52213. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  52214. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  52215. 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 ); }' ),
  52216. 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 ); }' ),
  52217. 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 ); }' ),
  52218. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  52219. 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 ); }' ),
  52220. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  52221. biquadraticTexture: new CodeNode( /* wgsl */`
  52222. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  52223. let res = vec2f( iRes );
  52224. let uvScaled = coord * res;
  52225. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  52226. // https://www.shadertoy.com/view/WtyXRy
  52227. let uv = uvWrapping - 0.5;
  52228. let iuv = floor( uv );
  52229. let f = fract( uv );
  52230. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  52231. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  52232. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  52233. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  52234. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  52235. }
  52236. ` ),
  52237. biquadraticTextureArray: new CodeNode( /* wgsl */`
  52238. fn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {
  52239. let res = vec2f( iRes );
  52240. let uvScaled = coord * res;
  52241. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  52242. // https://www.shadertoy.com/view/WtyXRy
  52243. let uv = uvWrapping - 0.5;
  52244. let iuv = floor( uv );
  52245. let f = fract( uv );
  52246. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );
  52247. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );
  52248. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );
  52249. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );
  52250. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  52251. }
  52252. ` )
  52253. };
  52254. const wgslMethods = {
  52255. dFdx: 'dpdx',
  52256. dFdy: '- dpdy',
  52257. mod_float: 'tsl_mod_float',
  52258. mod_vec2: 'tsl_mod_vec2',
  52259. mod_vec3: 'tsl_mod_vec3',
  52260. mod_vec4: 'tsl_mod_vec4',
  52261. equals_bool: 'tsl_equals_bool',
  52262. equals_bvec2: 'tsl_equals_bvec2',
  52263. equals_bvec3: 'tsl_equals_bvec3',
  52264. equals_bvec4: 'tsl_equals_bvec4',
  52265. inversesqrt: 'inverseSqrt',
  52266. bitcast: 'bitcast<f32>',
  52267. floatpack_snorm_2x16: 'pack2x16snorm',
  52268. floatpack_unorm_2x16: 'pack2x16unorm',
  52269. floatpack_float16_2x16: 'pack2x16float',
  52270. floatunpack_snorm_2x16: 'unpack2x16snorm',
  52271. floatunpack_unorm_2x16: 'unpack2x16unorm',
  52272. floatunpack_float16_2x16: 'unpack2x16float'
  52273. };
  52274. //
  52275. let diagnostics = '';
  52276. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  52277. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  52278. }
  52279. /**
  52280. * A node builder targeting WGSL.
  52281. *
  52282. * This module generates WGSL shader code from node materials and also
  52283. * generates the respective bindings and vertex buffer definitions. These
  52284. * data are later used by the renderer to create render and compute pipelines
  52285. * for render objects.
  52286. *
  52287. * @augments NodeBuilder
  52288. */
  52289. class WGSLNodeBuilder extends NodeBuilder {
  52290. /**
  52291. * Constructs a new WGSL node builder renderer.
  52292. *
  52293. * @param {Object3D} object - The 3D object.
  52294. * @param {Renderer} renderer - The renderer.
  52295. */
  52296. constructor( object, renderer ) {
  52297. super( object, renderer, new WGSLNodeParser() );
  52298. /**
  52299. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  52300. * another dictionary which manages UBOs per group ('render','frame','object').
  52301. *
  52302. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  52303. */
  52304. this.uniformGroups = {};
  52305. /**
  52306. * A dictionary that holds the assigned binding indices for each uniform group.
  52307. * This ensures the same binding index is used across all shader stages.
  52308. *
  52309. * @type {Object<string,{index: number, id: number}>}
  52310. */
  52311. this.uniformGroupsBindings = {};
  52312. /**
  52313. * A dictionary that holds for each shader stage a Map of builtins.
  52314. *
  52315. * @type {Object<string,Map<string,Object>>}
  52316. */
  52317. this.builtins = {};
  52318. /**
  52319. * A dictionary that holds for each shader stage a Set of directives.
  52320. *
  52321. * @type {Object<string,Set<string>>}
  52322. */
  52323. this.directives = {};
  52324. /**
  52325. * A map for managing scope arrays. Only relevant for when using
  52326. * {@link WorkgroupInfoNode} in context of compute shaders.
  52327. *
  52328. * @type {Map<string,Object>}
  52329. */
  52330. this.scopedArrays = new Map();
  52331. }
  52332. /**
  52333. * Generates the WGSL snippet for sampled textures.
  52334. *
  52335. * @private
  52336. * @param {Texture} texture - The texture.
  52337. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52338. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52339. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52340. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52341. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52342. * @return {string} The WGSL snippet.
  52343. */
  52344. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52345. if ( shaderStage === 'fragment' ) {
  52346. if ( depthSnippet ) {
  52347. if ( offsetSnippet ) {
  52348. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  52349. }
  52350. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  52351. } else {
  52352. if ( offsetSnippet ) {
  52353. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  52354. }
  52355. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  52356. }
  52357. } else {
  52358. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  52359. }
  52360. }
  52361. /**
  52362. * Generates the WGSL snippet when sampling textures with explicit mip level.
  52363. *
  52364. * @private
  52365. * @param {Texture} texture - The texture.
  52366. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52367. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52368. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52369. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52370. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52371. * @return {string} The WGSL snippet.
  52372. */
  52373. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52374. if ( this.isUnfilterable( texture ) === false ) {
  52375. if ( depthSnippet ) {
  52376. if ( offsetSnippet ) {
  52377. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52378. }
  52379. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  52380. } else {
  52381. if ( offsetSnippet ) {
  52382. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52383. }
  52384. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  52385. }
  52386. } else if ( this.isFilteredTexture( texture ) ) {
  52387. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet, depthSnippet );
  52388. } else {
  52389. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  52390. }
  52391. }
  52392. /**
  52393. * Generates a wrap function used in context of textures.
  52394. *
  52395. * @param {Texture} texture - The texture to generate the function for.
  52396. * @return {string} The name of the generated function.
  52397. */
  52398. generateWrapFunction( texture ) {
  52399. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.is3DTexture || texture.isData3DTexture ? '3d' : '2d' }T`;
  52400. let nodeCode = wgslCodeCache[ functionName ];
  52401. if ( nodeCode === undefined ) {
  52402. const includes = [];
  52403. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  52404. const coordType = texture.is3DTexture || texture.isData3DTexture ? 'vec3f' : 'vec2f';
  52405. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  52406. const addWrapSnippet = ( wrap, axis ) => {
  52407. if ( wrap === RepeatWrapping ) {
  52408. includes.push( wgslPolyfill.repeatWrapping_float );
  52409. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  52410. } else if ( wrap === ClampToEdgeWrapping ) {
  52411. includes.push( wgslPolyfill.clampWrapping_float );
  52412. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  52413. } else if ( wrap === MirroredRepeatWrapping ) {
  52414. includes.push( wgslPolyfill.mirrorWrapping_float );
  52415. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  52416. } else {
  52417. code += `\t\tcoord.${ axis }`;
  52418. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  52419. }
  52420. };
  52421. addWrapSnippet( texture.wrapS, 'x' );
  52422. code += ',\n';
  52423. addWrapSnippet( texture.wrapT, 'y' );
  52424. if ( texture.is3DTexture || texture.isData3DTexture ) {
  52425. code += ',\n';
  52426. addWrapSnippet( texture.wrapR, 'z' );
  52427. }
  52428. code += '\n\t);\n\n}\n';
  52429. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  52430. }
  52431. nodeCode.build( this );
  52432. return functionName;
  52433. }
  52434. /**
  52435. * Generates the array declaration string.
  52436. *
  52437. * @param {string} type - The type.
  52438. * @param {?number} [count] - The count.
  52439. * @return {string} The generated value as a shader string.
  52440. */
  52441. generateArrayDeclaration( type, count ) {
  52442. return `array< ${ this.getType( type ) }, ${ count } >`;
  52443. }
  52444. /**
  52445. * Generates a WGSL variable that holds the texture dimension of the given texture.
  52446. * It also returns information about the number of layers (elements) of an arrayed
  52447. * texture as well as the cube face count of cube textures.
  52448. *
  52449. * @param {Texture} texture - The texture to generate the function for.
  52450. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  52451. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52452. * @return {string} The name of the dimension variable.
  52453. */
  52454. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  52455. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  52456. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  52457. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  52458. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  52459. let textureDimensionsParams;
  52460. let dimensionType;
  52461. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  52462. const isMultisampled = primarySamples > 1;
  52463. if ( texture.is3DTexture || texture.isData3DTexture ) {
  52464. dimensionType = 'vec3<u32>';
  52465. } else {
  52466. // Regular 2D textures, depth textures, etc.
  52467. dimensionType = 'vec2<u32>';
  52468. }
  52469. // Build parameters string based on texture type and multisampling
  52470. if ( isMultisampled || texture.isStorageTexture ) {
  52471. textureDimensionsParams = textureProperty;
  52472. } else {
  52473. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  52474. }
  52475. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  52476. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  52477. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.is3DTexture || texture.isData3DTexture ) {
  52478. textureData.arrayLayerCount = new VarNode(
  52479. new ExpressionNode(
  52480. `textureNumLayers(${textureProperty})`,
  52481. 'u32'
  52482. )
  52483. );
  52484. }
  52485. // For cube textures, we know it's always 6 faces
  52486. if ( texture.isTextureCube ) {
  52487. textureData.cubeFaceCount = new VarNode(
  52488. new ExpressionNode( '6u', 'u32' )
  52489. );
  52490. }
  52491. }
  52492. return textureDimensionNode.build( this );
  52493. }
  52494. /**
  52495. * Generates the WGSL snippet for a manual filtered texture.
  52496. *
  52497. * @param {Texture} texture - The texture.
  52498. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52499. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52500. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52501. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52502. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52503. * @return {string} The WGSL snippet.
  52504. */
  52505. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u', depthSnippet ) {
  52506. const wrapFunction = this.generateWrapFunction( texture );
  52507. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52508. if ( offsetSnippet ) {
  52509. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  52510. }
  52511. if ( depthSnippet ) {
  52512. this._include( 'biquadraticTextureArray' );
  52513. return `tsl_biquadraticTexture_array( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ depthSnippet } ), u32( ${ levelSnippet } ) )`;
  52514. }
  52515. this._include( 'biquadraticTexture' );
  52516. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  52517. }
  52518. /**
  52519. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  52520. * Since it's a lookup, no sampling or filtering is applied.
  52521. *
  52522. * @param {Texture} texture - The texture.
  52523. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52524. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52525. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52526. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52527. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52528. * @return {string} The WGSL snippet.
  52529. */
  52530. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  52531. // Cube textures cannot use textureLoad in WGSL, must use textureSampleLevel
  52532. if ( texture.isCubeTexture === true ) {
  52533. if ( offsetSnippet ) {
  52534. uvSnippet = `${ uvSnippet } + vec3<f32>(${ offsetSnippet })`;
  52535. }
  52536. // Depth textures require integer level, regular textures use float
  52537. const levelType = texture.isDepthTexture ? 'u32' : 'f32';
  52538. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelType }( ${ levelSnippet } ) )`;
  52539. }
  52540. const wrapFunction = this.generateWrapFunction( texture );
  52541. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52542. const vecType = texture.is3DTexture || texture.isData3DTexture ? 'vec3' : 'vec2';
  52543. const textureDimensionMargin = ( vecType === 'vec3' ) ? 'vec3<u32>( 1, 1, 1 )' : 'vec2<u32>( 1, 1 )';
  52544. if ( offsetSnippet ) {
  52545. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  52546. }
  52547. const clampMin = `${ vecType }<f32>( 0 )`;
  52548. const clampMax = `${ vecType }<f32>( ${ textureDimension } - ${ textureDimensionMargin } )`;
  52549. uvSnippet = `${ vecType }<u32>( clamp( floor( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) ), ${ clampMin }, ${ clampMax } ) )`;
  52550. return this.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, null );
  52551. }
  52552. /**
  52553. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  52554. *
  52555. * @param {Texture} texture - The texture.
  52556. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52557. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52558. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52559. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52560. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52561. * @return {string} The WGSL snippet.
  52562. */
  52563. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52564. const isStorageTexture = texture.isStorageTexture === true;
  52565. if ( levelSnippet === null && ! isStorageTexture ) levelSnippet = '0u';
  52566. if ( offsetSnippet ) {
  52567. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  52568. }
  52569. let snippet;
  52570. if ( depthSnippet ) {
  52571. // Storage textures don't take a level parameter in WGSL
  52572. if ( isStorageTexture ) {
  52573. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet } )`;
  52574. } else {
  52575. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  52576. }
  52577. } else {
  52578. // Storage textures don't take a level parameter in WGSL
  52579. if ( isStorageTexture ) {
  52580. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  52581. } else {
  52582. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  52583. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  52584. snippet += '.x';
  52585. }
  52586. }
  52587. }
  52588. return snippet;
  52589. }
  52590. /**
  52591. * Generates the WGSL snippet that writes a single texel to a texture.
  52592. *
  52593. * @param {Texture} texture - The texture.
  52594. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52595. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52596. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52597. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  52598. * @return {string} The WGSL snippet.
  52599. */
  52600. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  52601. let snippet;
  52602. if ( depthSnippet ) {
  52603. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  52604. } else {
  52605. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  52606. }
  52607. return snippet;
  52608. }
  52609. /**
  52610. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  52611. *
  52612. * @param {Texture} texture - The texture.
  52613. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  52614. */
  52615. isSampleCompare( texture ) {
  52616. return texture.isDepthTexture === true && texture.compareFunction !== null && this.renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE );
  52617. }
  52618. /**
  52619. * Returns `true` if the given texture is unfilterable.
  52620. *
  52621. * @param {Texture} texture - The texture.
  52622. * @return {boolean} Whether the given texture is unfilterable or not.
  52623. */
  52624. isUnfilterable( texture ) {
  52625. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  52626. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  52627. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  52628. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  52629. }
  52630. /**
  52631. * Generates the WGSL snippet for sampling/loading the given texture.
  52632. *
  52633. * @param {Texture} texture - The texture.
  52634. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52635. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52636. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52637. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52638. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52639. * @return {string} The WGSL snippet.
  52640. */
  52641. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52642. let snippet = null;
  52643. if ( this.isUnfilterable( texture ) ) {
  52644. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  52645. } else {
  52646. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  52647. }
  52648. return snippet;
  52649. }
  52650. /**
  52651. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  52652. *
  52653. * @param {Texture} texture - The texture.
  52654. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52655. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52656. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  52657. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52658. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52659. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52660. * @return {string} The WGSL snippet.
  52661. */
  52662. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52663. if ( shaderStage === 'fragment' ) {
  52664. if ( depthSnippet ) {
  52665. if ( offsetSnippet ) {
  52666. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  52667. }
  52668. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  52669. } else {
  52670. if ( offsetSnippet ) {
  52671. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  52672. }
  52673. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  52674. }
  52675. } else {
  52676. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  52677. }
  52678. }
  52679. /**
  52680. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  52681. * against a reference value.
  52682. *
  52683. * @param {Texture} texture - The texture.
  52684. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52685. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52686. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  52687. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52688. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52689. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52690. * @return {string} The WGSL snippet.
  52691. */
  52692. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52693. if ( shaderStage === 'fragment' ) {
  52694. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  52695. if ( offsetSnippet ) {
  52696. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52697. }
  52698. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  52699. }
  52700. if ( offsetSnippet ) {
  52701. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52702. }
  52703. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  52704. } else {
  52705. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  52706. }
  52707. }
  52708. /**
  52709. * Generates the WGSL snippet when sampling textures with explicit mip level.
  52710. *
  52711. * @param {Texture} texture - The texture.
  52712. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52713. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52714. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52715. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52716. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52717. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52718. * @return {string} The WGSL snippet.
  52719. */
  52720. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52721. if ( this.isUnfilterable( texture ) === false ) {
  52722. if ( depthSnippet ) {
  52723. if ( offsetSnippet ) {
  52724. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52725. }
  52726. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  52727. } else {
  52728. if ( offsetSnippet ) {
  52729. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52730. }
  52731. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  52732. }
  52733. } else if ( this.isFilteredTexture( texture ) ) {
  52734. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet, depthSnippet );
  52735. } else {
  52736. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  52737. }
  52738. }
  52739. /**
  52740. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  52741. *
  52742. * @param {Texture} texture - The texture.
  52743. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52744. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52745. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  52746. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52747. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52748. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52749. * @return {string} The WGSL snippet.
  52750. */
  52751. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52752. if ( shaderStage === 'fragment' ) {
  52753. if ( depthSnippet ) {
  52754. if ( offsetSnippet ) {
  52755. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  52756. }
  52757. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ biasSnippet } )`;
  52758. } else {
  52759. if ( offsetSnippet ) {
  52760. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  52761. }
  52762. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  52763. }
  52764. } else {
  52765. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  52766. }
  52767. }
  52768. /**
  52769. * Returns a WGSL snippet that represents the property name of the given node.
  52770. *
  52771. * @param {Node} node - The node.
  52772. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52773. * @return {string} The property name.
  52774. */
  52775. getPropertyName( node, shaderStage = this.shaderStage ) {
  52776. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  52777. if ( shaderStage === 'vertex' ) {
  52778. return `varyings.${ node.name }`;
  52779. }
  52780. } else if ( node.isNodeUniform === true ) {
  52781. const name = node.name;
  52782. const type = node.type;
  52783. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  52784. return name;
  52785. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  52786. if ( this.isCustomStruct( node ) ) {
  52787. return name;
  52788. }
  52789. return name + '.value';
  52790. } else {
  52791. return node.groupNode.name + '.' + name;
  52792. }
  52793. }
  52794. return super.getPropertyName( node );
  52795. }
  52796. /**
  52797. * Returns the output struct name.
  52798. *
  52799. * @return {string} The name of the output struct.
  52800. */
  52801. getOutputStructName() {
  52802. return 'output';
  52803. }
  52804. /**
  52805. * Returns the native shader operator name for a given generic name.
  52806. *
  52807. * @param {string} op - The operator name to resolve.
  52808. * @return {?string} The resolved operator name.
  52809. */
  52810. getFunctionOperator( op ) {
  52811. const fnOp = wgslFnOpLib[ op ];
  52812. if ( fnOp !== undefined ) {
  52813. this._include( fnOp );
  52814. return fnOp;
  52815. }
  52816. return null;
  52817. }
  52818. /**
  52819. * Returns the node access for the given node and shader stage.
  52820. *
  52821. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  52822. * @param {string} shaderStage - The shader stage.
  52823. * @return {string} The node access.
  52824. */
  52825. getNodeAccess( node, shaderStage ) {
  52826. if ( shaderStage !== 'compute' ) {
  52827. if ( node.isAtomic === true ) {
  52828. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  52829. return NodeAccess.READ_WRITE;
  52830. }
  52831. return NodeAccess.READ_ONLY;
  52832. }
  52833. return node.access;
  52834. }
  52835. /**
  52836. * Returns A WGSL snippet representing the storage access.
  52837. *
  52838. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  52839. * @param {string} shaderStage - The shader stage.
  52840. * @return {string} The WGSL snippet representing the storage access.
  52841. */
  52842. getStorageAccess( node, shaderStage ) {
  52843. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  52844. }
  52845. /**
  52846. * This method is one of the more important ones since it's responsible
  52847. * for generating a matching binding instance for the given uniform node.
  52848. *
  52849. * These bindings are later used in the renderer to create bind groups
  52850. * and layouts.
  52851. *
  52852. * @param {UniformNode} node - The uniform node.
  52853. * @param {string} type - The node data type.
  52854. * @param {string} shaderStage - The shader stage.
  52855. * @param {?string} [name=null] - An optional uniform name.
  52856. * @return {NodeUniform} The node uniform object.
  52857. */
  52858. getUniformFromNode( node, type, shaderStage, name = null ) {
  52859. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  52860. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  52861. if ( nodeData.uniformGPU === undefined ) {
  52862. let uniformGPU;
  52863. const group = node.groupNode;
  52864. const groupName = group.name;
  52865. const bindings = this.getBindGroupArray( groupName, shaderStage );
  52866. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  52867. let texture = null;
  52868. const access = this.getNodeAccess( node, shaderStage );
  52869. if ( type === 'texture' || type === 'storageTexture' ) {
  52870. if ( node.value.is3DTexture === true ) {
  52871. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  52872. } else {
  52873. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  52874. }
  52875. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  52876. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  52877. } else if ( type === 'texture3D' ) {
  52878. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  52879. }
  52880. texture.store = node.isStorageTextureNode === true;
  52881. texture.mipLevel = texture.store ? node.mipLevel : 0;
  52882. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52883. // Cube textures always need samplers (they use textureSampleLevel, not textureLoad)
  52884. const needsSampler = node.value.isCubeTexture === true || ( this.isUnfilterable( node.value ) === false && texture.store === false );
  52885. if ( needsSampler ) {
  52886. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  52887. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52888. bindings.push( sampler, texture );
  52889. uniformGPU = [ sampler, texture ];
  52890. } else {
  52891. bindings.push( texture );
  52892. uniformGPU = [ texture ];
  52893. }
  52894. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  52895. const sharedData = this.getSharedDataFromNode( node );
  52896. let buffer = sharedData.buffer;
  52897. if ( buffer === undefined ) {
  52898. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  52899. buffer = new bufferClass( node, group );
  52900. sharedData.buffer = buffer;
  52901. }
  52902. buffer.setVisibility( buffer.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  52903. bindings.push( buffer );
  52904. uniformGPU = buffer;
  52905. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  52906. } else {
  52907. let uniformsGroup = this.uniformGroups[ groupName ];
  52908. if ( uniformsGroup === undefined ) {
  52909. uniformsGroup = new NodeUniformsGroup( groupName, group );
  52910. this.uniformGroups[ groupName ] = uniformsGroup;
  52911. }
  52912. // Update visibility to include this shader stage (bitwise OR)
  52913. uniformsGroup.setVisibility( uniformsGroup.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  52914. // Add to bindings for this stage if not already present
  52915. if ( bindings.indexOf( uniformsGroup ) === -1 ) {
  52916. bindings.push( uniformsGroup );
  52917. }
  52918. uniformGPU = this.getNodeUniform( uniformNode, type );
  52919. // Only add uniform if not already present in the group (check by name to avoid duplicates across stages)
  52920. const uniformName = uniformGPU.name;
  52921. const alreadyExists = uniformsGroup.uniforms.some( u => u.name === uniformName );
  52922. if ( ! alreadyExists ) {
  52923. uniformsGroup.addUniform( uniformGPU );
  52924. }
  52925. }
  52926. nodeData.uniformGPU = uniformGPU;
  52927. }
  52928. return uniformNode;
  52929. }
  52930. /**
  52931. * This method should be used whenever builtins are required in nodes.
  52932. * The internal builtins data structure will make sure builtins are
  52933. * defined in the WGSL source.
  52934. *
  52935. * @param {string} name - The builtin name.
  52936. * @param {string} property - The property name.
  52937. * @param {string} type - The node data type.
  52938. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52939. * @return {string} The property name.
  52940. */
  52941. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  52942. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  52943. if ( map.has( name ) === false ) {
  52944. map.set( name, {
  52945. name,
  52946. property,
  52947. type
  52948. } );
  52949. }
  52950. return property;
  52951. }
  52952. /**
  52953. * Returns `true` if the given builtin is defined in the given shader stage.
  52954. *
  52955. * @param {string} name - The builtin name.
  52956. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52957. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  52958. */
  52959. hasBuiltin( name, shaderStage = this.shaderStage ) {
  52960. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  52961. }
  52962. /**
  52963. * Returns the vertex index builtin.
  52964. *
  52965. * @return {string} The vertex index.
  52966. */
  52967. getVertexIndex() {
  52968. if ( this.shaderStage === 'vertex' ) {
  52969. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  52970. }
  52971. return 'vertexIndex';
  52972. }
  52973. /**
  52974. * Builds the given shader node.
  52975. *
  52976. * @param {ShaderNodeInternal} shaderNode - The shader node.
  52977. * @return {string} The WGSL function code.
  52978. */
  52979. buildFunctionCode( shaderNode ) {
  52980. const layout = shaderNode.layout;
  52981. const flowData = this.flowShaderNode( shaderNode );
  52982. const parameters = [];
  52983. for ( const input of layout.inputs ) {
  52984. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  52985. }
  52986. //
  52987. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  52988. ${ flowData.vars }
  52989. ${ flowData.code }
  52990. `;
  52991. if ( flowData.result ) {
  52992. code += `\treturn ${ flowData.result };\n`;
  52993. }
  52994. code += '\n}\n';
  52995. //
  52996. return code;
  52997. }
  52998. /**
  52999. * Contextually returns either the vertex stage instance index builtin
  53000. * or the linearized index of an compute invocation within a grid of workgroups.
  53001. *
  53002. * @return {string} The instance index.
  53003. */
  53004. getInstanceIndex() {
  53005. if ( this.shaderStage === 'vertex' ) {
  53006. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  53007. }
  53008. return 'instanceIndex';
  53009. }
  53010. /**
  53011. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  53012. *
  53013. * @return {string} The invocation local index.
  53014. */
  53015. getInvocationLocalIndex() {
  53016. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  53017. }
  53018. /**
  53019. * Returns a builtin representing the size of a subgroup within the current shader.
  53020. *
  53021. * @return {string} The subgroup size.
  53022. */
  53023. getSubgroupSize() {
  53024. this.enableSubGroups();
  53025. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  53026. }
  53027. /**
  53028. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  53029. *
  53030. * @return {string} The invocation subgroup index.
  53031. */
  53032. getInvocationSubgroupIndex() {
  53033. this.enableSubGroups();
  53034. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  53035. }
  53036. /**
  53037. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  53038. *
  53039. * @return {string} The subgroup index.
  53040. */
  53041. getSubgroupIndex() {
  53042. this.enableSubGroups();
  53043. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  53044. }
  53045. /**
  53046. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  53047. *
  53048. * @return {null} Null.
  53049. */
  53050. getDrawIndex() {
  53051. return null;
  53052. }
  53053. /**
  53054. * Returns the front facing builtin.
  53055. *
  53056. * @return {string} The front facing builtin.
  53057. */
  53058. getFrontFacing() {
  53059. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  53060. }
  53061. /**
  53062. * Returns the frag coord builtin.
  53063. *
  53064. * @return {string} The frag coord builtin.
  53065. */
  53066. getFragCoord() {
  53067. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  53068. }
  53069. /**
  53070. * Returns the frag depth builtin.
  53071. *
  53072. * @return {string} The frag depth builtin.
  53073. */
  53074. getFragDepth() {
  53075. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  53076. }
  53077. /**
  53078. * Returns the clip distances builtin.
  53079. *
  53080. * @return {string} The clip distances builtin.
  53081. */
  53082. getClipDistance() {
  53083. return 'varyings.hw_clip_distances';
  53084. }
  53085. /**
  53086. * Whether to flip texture data along its vertical axis or not.
  53087. *
  53088. * @return {boolean} Returns always `false` in context of WGSL.
  53089. */
  53090. isFlipY() {
  53091. return false;
  53092. }
  53093. /**
  53094. * Enables the given directive for the given shader stage.
  53095. *
  53096. * @param {string} name - The directive name.
  53097. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  53098. */
  53099. enableDirective( name, shaderStage = this.shaderStage ) {
  53100. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  53101. stage.add( name );
  53102. }
  53103. /**
  53104. * Returns the directives of the given shader stage as a WGSL string.
  53105. *
  53106. * @param {string} shaderStage - The shader stage.
  53107. * @return {string} A WGSL snippet that enables the directives of the given stage.
  53108. */
  53109. getDirectives( shaderStage ) {
  53110. const snippets = [];
  53111. const directives = this.directives[ shaderStage ];
  53112. if ( directives !== undefined ) {
  53113. for ( const directive of directives ) {
  53114. snippets.push( `enable ${directive};` );
  53115. }
  53116. }
  53117. return snippets.join( '\n' );
  53118. }
  53119. /**
  53120. * Enables the 'subgroups' directive.
  53121. */
  53122. enableSubGroups() {
  53123. this.enableDirective( 'subgroups' );
  53124. }
  53125. /**
  53126. * Enables the 'subgroups-f16' directive.
  53127. */
  53128. enableSubgroupsF16() {
  53129. this.enableDirective( 'subgroups-f16' );
  53130. }
  53131. /**
  53132. * Enables the 'clip_distances' directive.
  53133. */
  53134. enableClipDistances() {
  53135. this.enableDirective( 'clip_distances' );
  53136. }
  53137. /**
  53138. * Enables the 'f16' directive.
  53139. */
  53140. enableShaderF16() {
  53141. this.enableDirective( 'f16' );
  53142. }
  53143. /**
  53144. * Enables the 'dual_source_blending' directive.
  53145. */
  53146. enableDualSourceBlending() {
  53147. this.enableDirective( 'dual_source_blending' );
  53148. }
  53149. /**
  53150. * Enables hardware clipping.
  53151. *
  53152. * @param {string} planeCount - The clipping plane count.
  53153. */
  53154. enableHardwareClipping( planeCount ) {
  53155. this.enableClipDistances();
  53156. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  53157. }
  53158. /**
  53159. * Returns the builtins of the given shader stage as a WGSL string.
  53160. *
  53161. * @param {string} shaderStage - The shader stage.
  53162. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  53163. */
  53164. getBuiltins( shaderStage ) {
  53165. const snippets = [];
  53166. const builtins = this.builtins[ shaderStage ];
  53167. if ( builtins !== undefined ) {
  53168. for ( const { name, property, type } of builtins.values() ) {
  53169. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  53170. }
  53171. }
  53172. return snippets.join( ',\n\t' );
  53173. }
  53174. /**
  53175. * This method should be used when a new scoped buffer is used in context of
  53176. * compute shaders. It adds the array to the internal data structure which is
  53177. * later used to generate the respective WGSL.
  53178. *
  53179. * @param {string} name - The array name.
  53180. * @param {string} scope - The scope.
  53181. * @param {string} bufferType - The buffer type.
  53182. * @param {string} bufferCount - The buffer count.
  53183. * @return {string} The array name.
  53184. */
  53185. getScopedArray( name, scope, bufferType, bufferCount ) {
  53186. if ( this.scopedArrays.has( name ) === false ) {
  53187. this.scopedArrays.set( name, {
  53188. name,
  53189. scope,
  53190. bufferType,
  53191. bufferCount
  53192. } );
  53193. }
  53194. return name;
  53195. }
  53196. /**
  53197. * Returns the scoped arrays of the given shader stage as a WGSL string.
  53198. *
  53199. * @param {string} shaderStage - The shader stage.
  53200. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  53201. * Returns `undefined` when used in the vertex or fragment stage.
  53202. */
  53203. getScopedArrays( shaderStage ) {
  53204. if ( shaderStage !== 'compute' ) {
  53205. return;
  53206. }
  53207. const snippets = [];
  53208. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  53209. const type = this.getType( bufferType );
  53210. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  53211. }
  53212. return snippets.join( '\n' );
  53213. }
  53214. /**
  53215. * Returns the shader attributes of the given shader stage as a WGSL string.
  53216. *
  53217. * @param {string} shaderStage - The shader stage.
  53218. * @return {string} The WGSL snippet that defines the shader attributes.
  53219. */
  53220. getAttributes( shaderStage ) {
  53221. const snippets = [];
  53222. if ( shaderStage === 'compute' ) {
  53223. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  53224. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  53225. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  53226. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  53227. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  53228. this.enableDirective( 'subgroups', shaderStage );
  53229. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  53230. }
  53231. }
  53232. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  53233. const builtins = this.getBuiltins( 'attribute' );
  53234. if ( builtins ) snippets.push( builtins );
  53235. const attributes = this.getAttributesArray();
  53236. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  53237. const attribute = attributes[ index ];
  53238. const name = attribute.name;
  53239. const type = this.getType( attribute.type );
  53240. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  53241. }
  53242. }
  53243. return snippets.join( ',\n\t' );
  53244. }
  53245. /**
  53246. * Returns the members of the given struct type node as a WGSL string.
  53247. *
  53248. * @param {StructTypeNode} struct - The struct type node.
  53249. * @return {string} The WGSL snippet that defines the struct members.
  53250. */
  53251. getStructMembers( struct ) {
  53252. const snippets = [];
  53253. for ( const member of struct.members ) {
  53254. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  53255. let type = this.getType( member.type );
  53256. if ( member.atomic ) {
  53257. type = 'atomic< ' + type + ' >';
  53258. }
  53259. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  53260. }
  53261. if ( struct.output ) {
  53262. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  53263. }
  53264. return snippets.join( ',\n' );
  53265. }
  53266. /**
  53267. * Returns the structs of the given shader stage as a WGSL string.
  53268. *
  53269. * @param {string} shaderStage - The shader stage.
  53270. * @return {string} The WGSL snippet that defines the structs.
  53271. */
  53272. getStructs( shaderStage ) {
  53273. let result = '';
  53274. const structs = this.structs[ shaderStage ];
  53275. if ( structs.length > 0 ) {
  53276. const snippets = [];
  53277. for ( const struct of structs ) {
  53278. let snippet = `struct ${ struct.name } {\n`;
  53279. snippet += this.getStructMembers( struct );
  53280. snippet += '\n};';
  53281. snippets.push( snippet );
  53282. }
  53283. result = '\n' + snippets.join( '\n\n' ) + '\n';
  53284. }
  53285. return result;
  53286. }
  53287. /**
  53288. * Returns a WGSL string representing a variable.
  53289. *
  53290. * @param {string} type - The variable's type.
  53291. * @param {string} name - The variable's name.
  53292. * @param {?number} [count=null] - The array length.
  53293. * @return {string} The WGSL snippet that defines a variable.
  53294. */
  53295. getVar( type, name, count = null ) {
  53296. let snippet = `var ${ name } : `;
  53297. if ( count !== null ) {
  53298. snippet += this.generateArrayDeclaration( type, count );
  53299. } else {
  53300. snippet += this.getType( type );
  53301. }
  53302. return snippet;
  53303. }
  53304. /**
  53305. * Returns the variables of the given shader stage as a WGSL string.
  53306. *
  53307. * @param {string} shaderStage - The shader stage.
  53308. * @return {string} The WGSL snippet that defines the variables.
  53309. */
  53310. getVars( shaderStage ) {
  53311. const snippets = [];
  53312. const vars = this.vars[ shaderStage ];
  53313. if ( vars !== undefined ) {
  53314. for ( const variable of vars ) {
  53315. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  53316. }
  53317. }
  53318. return `\n${ snippets.join( '\n' ) }\n`;
  53319. }
  53320. /**
  53321. * Returns the varyings of the given shader stage as a WGSL string.
  53322. *
  53323. * @param {string} shaderStage - The shader stage.
  53324. * @return {string} The WGSL snippet that defines the varyings.
  53325. */
  53326. getVaryings( shaderStage ) {
  53327. const snippets = [];
  53328. if ( shaderStage === 'vertex' ) {
  53329. this.getBuiltin( 'position', 'builtinClipSpace', 'vec4<f32>', 'vertex' );
  53330. }
  53331. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  53332. const varyings = this.varyings;
  53333. const vars = this.vars[ shaderStage ];
  53334. for ( let index = 0; index < varyings.length; index ++ ) {
  53335. const varying = varyings[ index ];
  53336. if ( varying.needsInterpolation ) {
  53337. let attributesSnippet = `@location( ${index} )`;
  53338. if ( varying.interpolationType ) {
  53339. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  53340. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  53341. // Otherwise, optimize interpolation when sensible
  53342. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  53343. attributesSnippet += ' @interpolate(flat, either)';
  53344. }
  53345. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  53346. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  53347. vars.push( varying );
  53348. }
  53349. }
  53350. }
  53351. const builtins = this.getBuiltins( shaderStage );
  53352. if ( builtins ) snippets.push( builtins );
  53353. const code = snippets.join( ',\n\t' );
  53354. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  53355. }
  53356. isCustomStruct( nodeUniform ) {
  53357. const attribute = nodeUniform.value;
  53358. const bufferNode = nodeUniform.node;
  53359. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  53360. const isStructArray =
  53361. ( bufferNode.value && bufferNode.value.array ) &&
  53362. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  53363. return isAttributeStructType && ! isStructArray;
  53364. }
  53365. /**
  53366. * Returns the uniforms of the given shader stage as a WGSL string.
  53367. *
  53368. * @param {string} shaderStage - The shader stage.
  53369. * @return {string} The WGSL snippet that defines the uniforms.
  53370. */
  53371. getUniforms( shaderStage ) {
  53372. const uniforms = this.uniforms[ shaderStage ];
  53373. const bindingSnippets = [];
  53374. const bufferSnippets = [];
  53375. const structSnippets = [];
  53376. const uniformGroups = {};
  53377. for ( const uniform of uniforms ) {
  53378. const groupName = uniform.groupNode.name;
  53379. const uniformIndexes = this.bindingsIndexes[ groupName ];
  53380. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'cubeDepthTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  53381. const texture = uniform.node.value;
  53382. // Cube textures always need samplers (they use textureSampleLevel, not textureLoad)
  53383. const needsSampler = texture.isCubeTexture === true || ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true );
  53384. if ( needsSampler ) {
  53385. if ( this.isSampleCompare( texture ) ) {
  53386. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  53387. } else {
  53388. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  53389. }
  53390. }
  53391. let textureType;
  53392. let multisampled = '';
  53393. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  53394. if ( primarySamples > 1 ) {
  53395. multisampled = '_multisampled';
  53396. }
  53397. if ( texture.isCubeTexture === true && texture.isDepthTexture === true ) {
  53398. textureType = 'texture_depth_cube';
  53399. } else if ( texture.isCubeTexture === true ) {
  53400. textureType = 'texture_cube<f32>';
  53401. } else if ( texture.isDepthTexture === true ) {
  53402. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  53403. textureType = `texture${ multisampled }_2d<f32>`;
  53404. } else {
  53405. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  53406. }
  53407. } else if ( uniform.node.isStorageTextureNode === true ) {
  53408. const format = getFormat( texture );
  53409. const access = this.getStorageAccess( uniform.node, shaderStage );
  53410. const is3D = uniform.node.value.is3DTexture;
  53411. const isArrayTexture = uniform.node.value.isArrayTexture;
  53412. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  53413. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  53414. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  53415. textureType = 'texture_2d_array<f32>';
  53416. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  53417. textureType = 'texture_3d<f32>';
  53418. } else {
  53419. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  53420. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  53421. }
  53422. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  53423. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  53424. const bufferNode = uniform.node;
  53425. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  53426. const bufferCount = bufferNode.bufferCount;
  53427. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  53428. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  53429. if ( this.isCustomStruct( uniform ) ) {
  53430. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  53431. } else {
  53432. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  53433. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  53434. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  53435. }
  53436. } else {
  53437. const groupName = uniform.groupNode.name;
  53438. // Check if this group has already been processed in this shader stage
  53439. if ( uniformGroups[ groupName ] === undefined ) {
  53440. // Get the shared uniform group that contains uniforms from all stages
  53441. const sharedUniformGroup = this.uniformGroups[ groupName ];
  53442. if ( sharedUniformGroup !== undefined ) {
  53443. // Generate snippets for ALL uniforms in this shared group
  53444. const snippets = [];
  53445. for ( const sharedUniform of sharedUniformGroup.uniforms ) {
  53446. const type = sharedUniform.getType();
  53447. const vectorType = this.getType( this.getVectorType( type ) );
  53448. snippets.push( `\t${ sharedUniform.name } : ${ vectorType }` );
  53449. }
  53450. // Check if this group already has an assigned binding index (from another shader stage)
  53451. let groupBinding = this.uniformGroupsBindings[ groupName ];
  53452. if ( groupBinding === undefined ) {
  53453. // First time processing this group - assign a new binding index
  53454. groupBinding = {
  53455. index: uniformIndexes.binding ++,
  53456. id: uniformIndexes.group
  53457. };
  53458. this.uniformGroupsBindings[ groupName ] = groupBinding;
  53459. }
  53460. uniformGroups[ groupName ] = {
  53461. index: groupBinding.index,
  53462. id: groupBinding.id,
  53463. snippets: snippets
  53464. };
  53465. }
  53466. }
  53467. }
  53468. }
  53469. for ( const name in uniformGroups ) {
  53470. const group = uniformGroups[ name ];
  53471. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  53472. }
  53473. const code = [ ...bindingSnippets, ...bufferSnippets, ...structSnippets ].join( '\n' );
  53474. return code;
  53475. }
  53476. /**
  53477. * Controls the code build of the shader stages.
  53478. */
  53479. buildCode() {
  53480. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  53481. this.sortBindingGroups();
  53482. for ( const shaderStage in shadersData ) {
  53483. this.shaderStage = shaderStage;
  53484. const stageData = shadersData[ shaderStage ];
  53485. stageData.uniforms = this.getUniforms( shaderStage );
  53486. stageData.attributes = this.getAttributes( shaderStage );
  53487. stageData.varyings = this.getVaryings( shaderStage );
  53488. stageData.structs = this.getStructs( shaderStage );
  53489. stageData.vars = this.getVars( shaderStage );
  53490. stageData.codes = this.getCodes( shaderStage );
  53491. stageData.directives = this.getDirectives( shaderStage );
  53492. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  53493. //
  53494. let flow = '// code\n\n';
  53495. flow += this.flowCode[ shaderStage ];
  53496. const flowNodes = this.flowNodes[ shaderStage ];
  53497. const mainNode = flowNodes[ flowNodes.length - 1 ];
  53498. const outputNode = mainNode.outputNode;
  53499. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  53500. for ( const node of flowNodes ) {
  53501. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  53502. const slotName = node.name;
  53503. if ( slotName ) {
  53504. if ( flow.length > 0 ) flow += '\n';
  53505. flow += `\t// flow -> ${ slotName }\n`;
  53506. }
  53507. flow += `${ flowSlotData.code }\n\t`;
  53508. if ( node === mainNode && shaderStage !== 'compute' ) {
  53509. flow += '// result\n\n\t';
  53510. if ( shaderStage === 'vertex' ) {
  53511. flow += `varyings.builtinClipSpace = ${ flowSlotData.result };`;
  53512. } else if ( shaderStage === 'fragment' ) {
  53513. if ( isOutputStruct ) {
  53514. stageData.returnType = outputNode.getNodeType( this );
  53515. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  53516. flow += `return ${ flowSlotData.result };`;
  53517. } else {
  53518. let structSnippet = '\t@location(0) color: vec4<f32>';
  53519. const builtins = this.getBuiltins( 'output' );
  53520. if ( builtins ) structSnippet += ',\n\t' + builtins;
  53521. stageData.returnType = 'OutputStruct';
  53522. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  53523. stageData.structs += '\nvar<private> output : OutputStruct;';
  53524. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  53525. }
  53526. }
  53527. }
  53528. }
  53529. stageData.flow = flow;
  53530. }
  53531. this.shaderStage = null;
  53532. if ( this.material !== null ) {
  53533. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  53534. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  53535. } else {
  53536. // Early strictly validated in computeNode
  53537. const workgroupSize = this.object.workgroupSize;
  53538. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  53539. }
  53540. }
  53541. /**
  53542. * Returns the native shader method name for a given generic name.
  53543. *
  53544. * @param {string} method - The method name to resolve.
  53545. * @param {?string} [output=null] - An optional output.
  53546. * @return {string} The resolved WGSL method name.
  53547. */
  53548. getMethod( method, output = null ) {
  53549. let wgslMethod;
  53550. if ( output !== null ) {
  53551. wgslMethod = this._getWGSLMethod( method + '_' + output );
  53552. }
  53553. if ( wgslMethod === undefined ) {
  53554. wgslMethod = this._getWGSLMethod( method );
  53555. }
  53556. return wgslMethod || method;
  53557. }
  53558. /**
  53559. * Returns the bitcast method name for a given input and outputType.
  53560. *
  53561. * @param {string} type - The output type to bitcast to.
  53562. * @return {string} The resolved WGSL bitcast invocation.
  53563. */
  53564. getBitcastMethod( type ) {
  53565. const dataType = this.getType( type );
  53566. return `bitcast<${ dataType }>`;
  53567. }
  53568. /**
  53569. * Returns the float packing method name for a given numeric encoding.
  53570. *
  53571. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  53572. * @returns {string} The resolve WGSL float packing method name.
  53573. */
  53574. getFloatPackingMethod( encoding ) {
  53575. return this.getMethod( `floatpack_${ encoding }_2x16` );
  53576. }
  53577. /**
  53578. * Returns the float unpacking method name for a given numeric encoding.
  53579. *
  53580. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  53581. * @returns {string} The resolve WGSL float unpacking method name.
  53582. */
  53583. getFloatUnpackingMethod( encoding ) {
  53584. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  53585. }
  53586. /**
  53587. * Returns the native snippet for a ternary operation.
  53588. *
  53589. * @param {string} condSnippet - The condition determining which expression gets resolved.
  53590. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  53591. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  53592. * @return {string} The resolved method name.
  53593. */
  53594. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  53595. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  53596. }
  53597. /**
  53598. * Returns the WGSL type of the given node data type.
  53599. *
  53600. * @param {string} type - The node data type.
  53601. * @return {string} The WGSL type.
  53602. */
  53603. getType( type ) {
  53604. return wgslTypeLib[ type ] || type;
  53605. }
  53606. /**
  53607. * Whether the requested feature is available or not.
  53608. *
  53609. * @param {string} name - The requested feature.
  53610. * @return {boolean} Whether the requested feature is supported or not.
  53611. */
  53612. isAvailable( name ) {
  53613. let result = supports[ name ];
  53614. if ( result === undefined ) {
  53615. if ( name === 'float32Filterable' ) {
  53616. result = this.renderer.hasFeature( 'float32-filterable' );
  53617. } else if ( name === 'clipDistance' ) {
  53618. result = this.renderer.hasFeature( 'clip-distances' );
  53619. }
  53620. supports[ name ] = result;
  53621. }
  53622. return result;
  53623. }
  53624. /**
  53625. * Returns the maximum uniform buffer size limit.
  53626. *
  53627. * @return {number} The maximum uniform buffer size in bytes.
  53628. */
  53629. getUniformBufferLimit() {
  53630. return this.renderer.backend.device.limits.maxUniformBufferBindingSize;
  53631. }
  53632. /**
  53633. * Returns the native shader method name for a given generic name.
  53634. *
  53635. * @private
  53636. * @param {string} method - The method name to resolve.
  53637. * @return {string} The resolved WGSL method name.
  53638. */
  53639. _getWGSLMethod( method ) {
  53640. if ( wgslPolyfill[ method ] !== undefined ) {
  53641. this._include( method );
  53642. }
  53643. return wgslMethods[ method ];
  53644. }
  53645. /**
  53646. * Includes the given method name into the current
  53647. * function node.
  53648. *
  53649. * @private
  53650. * @param {string} name - The method name to include.
  53651. * @return {CodeNode} The respective code node.
  53652. */
  53653. _include( name ) {
  53654. const codeNode = wgslPolyfill[ name ];
  53655. codeNode.build( this );
  53656. this.addInclude( codeNode );
  53657. return codeNode;
  53658. }
  53659. /**
  53660. * Returns a WGSL vertex shader based on the given shader data.
  53661. *
  53662. * @private
  53663. * @param {Object} shaderData - The shader data.
  53664. * @return {string} The vertex shader.
  53665. */
  53666. _getWGSLVertexCode( shaderData ) {
  53667. return `${ this.getSignature() }
  53668. // directives
  53669. ${shaderData.directives}
  53670. // structs
  53671. ${shaderData.structs}
  53672. // uniforms
  53673. ${shaderData.uniforms}
  53674. // varyings
  53675. ${shaderData.varyings}
  53676. var<private> varyings : VaryingsStruct;
  53677. // codes
  53678. ${shaderData.codes}
  53679. @vertex
  53680. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  53681. // vars
  53682. ${shaderData.vars}
  53683. // flow
  53684. ${shaderData.flow}
  53685. return varyings;
  53686. }
  53687. `;
  53688. }
  53689. /**
  53690. * Returns a WGSL fragment shader based on the given shader data.
  53691. *
  53692. * @private
  53693. * @param {Object} shaderData - The shader data.
  53694. * @return {string} The vertex shader.
  53695. */
  53696. _getWGSLFragmentCode( shaderData ) {
  53697. return `${ this.getSignature() }
  53698. // global
  53699. ${ diagnostics }
  53700. // structs
  53701. ${shaderData.structs}
  53702. // uniforms
  53703. ${shaderData.uniforms}
  53704. // codes
  53705. ${shaderData.codes}
  53706. @fragment
  53707. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  53708. // vars
  53709. ${shaderData.vars}
  53710. // flow
  53711. ${shaderData.flow}
  53712. }
  53713. `;
  53714. }
  53715. /**
  53716. * Returns a WGSL compute shader based on the given shader data.
  53717. *
  53718. * @private
  53719. * @param {Object} shaderData - The shader data.
  53720. * @param {string} workgroupSize - The workgroup size.
  53721. * @return {string} The vertex shader.
  53722. */
  53723. _getWGSLComputeCode( shaderData, workgroupSize ) {
  53724. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  53725. return `${ this.getSignature() }
  53726. // directives
  53727. ${ shaderData.directives }
  53728. // system
  53729. var<private> instanceIndex : u32;
  53730. // locals
  53731. ${ shaderData.scopedArrays }
  53732. // structs
  53733. ${ shaderData.structs }
  53734. // uniforms
  53735. ${ shaderData.uniforms }
  53736. // codes
  53737. ${ shaderData.codes }
  53738. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  53739. fn main( ${ shaderData.attributes } ) {
  53740. // system
  53741. instanceIndex = globalId.x
  53742. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  53743. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  53744. // vars
  53745. ${ shaderData.vars }
  53746. // flow
  53747. ${ shaderData.flow }
  53748. }
  53749. `;
  53750. }
  53751. /**
  53752. * Returns a WGSL struct based on the given name and variables.
  53753. *
  53754. * @private
  53755. * @param {string} name - The struct name.
  53756. * @param {string} vars - The struct variables.
  53757. * @return {string} The WGSL snippet representing a struct.
  53758. */
  53759. _getWGSLStruct( name, vars ) {
  53760. return `
  53761. struct ${name} {
  53762. ${vars}
  53763. };`;
  53764. }
  53765. /**
  53766. * Returns a WGSL struct binding.
  53767. *
  53768. * @private
  53769. * @param {string} name - The struct name.
  53770. * @param {string} vars - The struct variables.
  53771. * @param {string} access - The access.
  53772. * @param {number} [binding=0] - The binding index.
  53773. * @param {number} [group=0] - The group index.
  53774. * @return {string} The WGSL snippet representing a struct binding.
  53775. */
  53776. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  53777. const structName = name + 'Struct';
  53778. const structSnippet = this._getWGSLStruct( structName, vars );
  53779. return `${structSnippet}
  53780. @binding( ${ binding } ) @group( ${ group } )
  53781. var<${access}> ${ name } : ${ structName };`;
  53782. }
  53783. }
  53784. /**
  53785. * A WebGPU backend utility module with common helpers.
  53786. *
  53787. * @private
  53788. */
  53789. class WebGPUUtils {
  53790. /**
  53791. * Constructs a new utility object.
  53792. *
  53793. * @param {WebGPUBackend} backend - The WebGPU backend.
  53794. */
  53795. constructor( backend ) {
  53796. /**
  53797. * A reference to the WebGPU backend.
  53798. *
  53799. * @type {WebGPUBackend}
  53800. */
  53801. this.backend = backend;
  53802. }
  53803. /**
  53804. * Returns the depth/stencil GPU format for the given render context.
  53805. *
  53806. * @param {RenderContext} renderContext - The render context.
  53807. * @return {string} The depth/stencil GPU texture format.
  53808. */
  53809. getCurrentDepthStencilFormat( renderContext ) {
  53810. let format;
  53811. if ( renderContext.depth ) {
  53812. if ( renderContext.depthTexture !== null ) {
  53813. format = this.getTextureFormatGPU( renderContext.depthTexture );
  53814. } else if ( renderContext.stencil ) {
  53815. format = GPUTextureFormat.Depth24PlusStencil8;
  53816. } else {
  53817. format = GPUTextureFormat.Depth24Plus;
  53818. }
  53819. }
  53820. return format;
  53821. }
  53822. /**
  53823. * Returns the GPU format for the given texture.
  53824. *
  53825. * @param {Texture} texture - The texture.
  53826. * @return {string} The GPU texture format.
  53827. */
  53828. getTextureFormatGPU( texture ) {
  53829. return this.backend.get( texture ).format;
  53830. }
  53831. /**
  53832. * Returns an object that defines the multi-sampling state of the given texture.
  53833. *
  53834. * @param {Texture} texture - The texture.
  53835. * @return {Object} The multi-sampling state.
  53836. */
  53837. getTextureSampleData( texture ) {
  53838. let samples;
  53839. if ( texture.isFramebufferTexture ) {
  53840. samples = 1;
  53841. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  53842. const renderer = this.backend.renderer;
  53843. const renderTarget = renderer.getRenderTarget();
  53844. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  53845. } else if ( texture.renderTarget ) {
  53846. samples = texture.renderTarget.samples;
  53847. }
  53848. samples = samples || 1;
  53849. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  53850. const primarySamples = isMSAA ? 1 : samples;
  53851. return { samples, primarySamples, isMSAA };
  53852. }
  53853. /**
  53854. * Returns the default color attachment's GPU format of the current render context.
  53855. *
  53856. * @param {RenderContext} renderContext - The render context.
  53857. * @return {string} The GPU texture format of the default color attachment.
  53858. */
  53859. getCurrentColorFormat( renderContext ) {
  53860. let format;
  53861. if ( renderContext.textures !== null ) {
  53862. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  53863. } else {
  53864. format = this.getPreferredCanvasFormat(); // default context format
  53865. }
  53866. return format;
  53867. }
  53868. /**
  53869. * Returns the GPU formats of all color attachments of the current render context.
  53870. *
  53871. * @param {RenderContext} renderContext - The render context.
  53872. * @return {Array<string>} The GPU texture formats of all color attachments.
  53873. */
  53874. getCurrentColorFormats( renderContext ) {
  53875. if ( renderContext.textures !== null ) {
  53876. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  53877. } else {
  53878. return [ this.getPreferredCanvasFormat() ]; // default context format
  53879. }
  53880. }
  53881. /**
  53882. * Returns the output color space of the current render context.
  53883. *
  53884. * @param {RenderContext} renderContext - The render context.
  53885. * @return {string} The output color space.
  53886. */
  53887. getCurrentColorSpace( renderContext ) {
  53888. if ( renderContext.textures !== null ) {
  53889. return renderContext.textures[ 0 ].colorSpace;
  53890. }
  53891. return this.backend.renderer.outputColorSpace;
  53892. }
  53893. /**
  53894. * Returns GPU primitive topology for the given object and material.
  53895. *
  53896. * @param {Object3D} object - The 3D object.
  53897. * @param {Material} material - The material.
  53898. * @return {string} The GPU primitive topology.
  53899. */
  53900. getPrimitiveTopology( object, material ) {
  53901. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  53902. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  53903. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  53904. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  53905. }
  53906. /**
  53907. * Returns a modified sample count from the given sample count value.
  53908. *
  53909. * That is required since WebGPU only supports either 1 or 4.
  53910. *
  53911. * @param {number} sampleCount - The input sample count.
  53912. * @return {number} The (potentially updated) output sample count.
  53913. */
  53914. getSampleCount( sampleCount ) {
  53915. return sampleCount >= 4 ? 4 : 1;
  53916. }
  53917. /**
  53918. * Returns the sample count of the given render context.
  53919. *
  53920. * @param {RenderContext} renderContext - The render context.
  53921. * @return {number} The sample count.
  53922. */
  53923. getSampleCountRenderContext( renderContext ) {
  53924. if ( renderContext.textures !== null ) {
  53925. return this.getSampleCount( renderContext.sampleCount );
  53926. }
  53927. return this.getSampleCount( this.backend.renderer.currentSamples );
  53928. }
  53929. /**
  53930. * Returns the preferred canvas format.
  53931. *
  53932. * There is a separate method for this so it's possible to
  53933. * honor edge cases for specific devices.
  53934. *
  53935. * @return {string} The GPU texture format of the canvas.
  53936. */
  53937. getPreferredCanvasFormat() {
  53938. const parameters = this.backend.parameters;
  53939. const bufferType = parameters.outputType;
  53940. if ( bufferType === undefined ) {
  53941. return navigator.gpu.getPreferredCanvasFormat();
  53942. } else if ( bufferType === UnsignedByteType ) {
  53943. return GPUTextureFormat.BGRA8Unorm;
  53944. } else if ( bufferType === HalfFloatType ) {
  53945. return GPUTextureFormat.RGBA16Float;
  53946. } else {
  53947. throw new Error( 'Unsupported output buffer type.' );
  53948. }
  53949. }
  53950. }
  53951. const typedArraysToVertexFormatPrefix = new Map( [
  53952. [ Int8Array, [ 'sint8', 'snorm8' ]],
  53953. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  53954. [ Int16Array, [ 'sint16', 'snorm16' ]],
  53955. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  53956. [ Int32Array, [ 'sint32', 'snorm32' ]],
  53957. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  53958. [ Float32Array, [ 'float32', ]],
  53959. ] );
  53960. if ( typeof Float16Array !== 'undefined' ) {
  53961. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  53962. }
  53963. const typedAttributeToVertexFormatPrefix = new Map( [
  53964. [ Float16BufferAttribute, [ 'float16', ]],
  53965. ] );
  53966. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  53967. [ Int32Array, 'sint32' ],
  53968. [ Int16Array, 'sint32' ], // patch for INT16
  53969. [ Uint32Array, 'uint32' ],
  53970. [ Uint16Array, 'uint32' ], // patch for UINT16
  53971. [ Float32Array, 'float32' ]
  53972. ] );
  53973. /**
  53974. * A WebGPU backend utility module for managing shader attributes.
  53975. *
  53976. * @private
  53977. */
  53978. class WebGPUAttributeUtils {
  53979. /**
  53980. * Constructs a new utility object.
  53981. *
  53982. * @param {WebGPUBackend} backend - The WebGPU backend.
  53983. */
  53984. constructor( backend ) {
  53985. /**
  53986. * A reference to the WebGPU backend.
  53987. *
  53988. * @type {WebGPUBackend}
  53989. */
  53990. this.backend = backend;
  53991. }
  53992. /**
  53993. * Creates the GPU buffer for the given buffer attribute.
  53994. *
  53995. * @param {BufferAttribute} attribute - The buffer attribute.
  53996. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  53997. */
  53998. createAttribute( attribute, usage ) {
  53999. const bufferAttribute = this._getBufferAttribute( attribute );
  54000. const backend = this.backend;
  54001. const bufferData = backend.get( bufferAttribute );
  54002. let buffer = bufferData.buffer;
  54003. if ( buffer === undefined ) {
  54004. const device = backend.device;
  54005. let array = bufferAttribute.array;
  54006. // patch for INT16 and UINT16
  54007. if ( attribute.normalized === false ) {
  54008. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  54009. array = new Int32Array( array );
  54010. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  54011. array = new Uint32Array( array );
  54012. if ( usage & GPUBufferUsage.INDEX ) {
  54013. for ( let i = 0; i < array.length; i ++ ) {
  54014. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  54015. }
  54016. }
  54017. }
  54018. }
  54019. bufferAttribute.array = array;
  54020. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  54021. array = new array.constructor( bufferAttribute.count * 4 );
  54022. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  54023. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  54024. }
  54025. // Update BufferAttribute
  54026. bufferAttribute.itemSize = 4;
  54027. bufferAttribute.array = array;
  54028. bufferData._force3to4BytesAlignment = true;
  54029. }
  54030. // ensure 4 byte alignment
  54031. const byteLength = array.byteLength;
  54032. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  54033. buffer = device.createBuffer( {
  54034. label: bufferAttribute.name,
  54035. size: size,
  54036. usage: usage,
  54037. mappedAtCreation: true
  54038. } );
  54039. new array.constructor( buffer.getMappedRange() ).set( array );
  54040. buffer.unmap();
  54041. bufferData.buffer = buffer;
  54042. }
  54043. }
  54044. /**
  54045. * Updates the GPU buffer of the given buffer attribute.
  54046. *
  54047. * @param {BufferAttribute} attribute - The buffer attribute.
  54048. */
  54049. updateAttribute( attribute ) {
  54050. const bufferAttribute = this._getBufferAttribute( attribute );
  54051. const backend = this.backend;
  54052. const device = backend.device;
  54053. const bufferData = backend.get( bufferAttribute );
  54054. const buffer = backend.get( bufferAttribute ).buffer;
  54055. let array = bufferAttribute.array;
  54056. // if storage buffer ensure 4 byte alignment
  54057. if ( bufferData._force3to4BytesAlignment === true ) {
  54058. array = new array.constructor( bufferAttribute.count * 4 );
  54059. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  54060. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  54061. }
  54062. bufferAttribute.array = array;
  54063. }
  54064. const updateRanges = bufferAttribute.updateRanges;
  54065. if ( updateRanges.length === 0 ) {
  54066. // Not using update ranges
  54067. device.queue.writeBuffer(
  54068. buffer,
  54069. 0,
  54070. array,
  54071. 0
  54072. );
  54073. } else {
  54074. const isTyped = isTypedArray( array );
  54075. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  54076. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  54077. const range = updateRanges[ i ];
  54078. let dataOffset, size;
  54079. if ( bufferData._force3to4BytesAlignment === true ) {
  54080. const vertexStart = Math.floor( range.start / 3 );
  54081. const vertexCount = Math.ceil( range.count / 3 );
  54082. dataOffset = vertexStart * 4 * byteOffsetFactor;
  54083. size = vertexCount * 4 * byteOffsetFactor;
  54084. } else {
  54085. dataOffset = range.start * byteOffsetFactor;
  54086. size = range.count * byteOffsetFactor;
  54087. }
  54088. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  54089. device.queue.writeBuffer(
  54090. buffer,
  54091. bufferOffset,
  54092. array,
  54093. dataOffset,
  54094. size
  54095. );
  54096. }
  54097. bufferAttribute.clearUpdateRanges();
  54098. }
  54099. }
  54100. /**
  54101. * This method creates the vertex buffer layout data which are
  54102. * require when creating a render pipeline for the given render object.
  54103. *
  54104. * @param {RenderObject} renderObject - The render object.
  54105. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  54106. */
  54107. createShaderVertexBuffers( renderObject ) {
  54108. const attributes = renderObject.getAttributes();
  54109. const vertexBuffers = new Map();
  54110. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  54111. const geometryAttribute = attributes[ slot ];
  54112. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  54113. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  54114. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  54115. if ( vertexBufferLayout === undefined ) {
  54116. let arrayStride, stepMode;
  54117. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  54118. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  54119. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  54120. } else {
  54121. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  54122. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  54123. }
  54124. // patch for INT16 and UINT16
  54125. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  54126. arrayStride = 4;
  54127. }
  54128. vertexBufferLayout = {
  54129. arrayStride,
  54130. attributes: [],
  54131. stepMode
  54132. };
  54133. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  54134. }
  54135. const format = this._getVertexFormat( geometryAttribute );
  54136. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  54137. vertexBufferLayout.attributes.push( {
  54138. shaderLocation: slot,
  54139. offset,
  54140. format
  54141. } );
  54142. }
  54143. return Array.from( vertexBuffers.values() );
  54144. }
  54145. /**
  54146. * Destroys the GPU buffer of the given buffer attribute.
  54147. *
  54148. * @param {BufferAttribute} attribute - The buffer attribute.
  54149. */
  54150. destroyAttribute( attribute ) {
  54151. const backend = this.backend;
  54152. const data = backend.get( this._getBufferAttribute( attribute ) );
  54153. data.buffer.destroy();
  54154. backend.delete( attribute );
  54155. }
  54156. /**
  54157. * This method performs a readback operation by moving buffer data from
  54158. * a storage buffer attribute from the GPU to the CPU.
  54159. *
  54160. * @async
  54161. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  54162. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  54163. */
  54164. async getArrayBufferAsync( attribute ) {
  54165. const backend = this.backend;
  54166. const device = backend.device;
  54167. const data = backend.get( this._getBufferAttribute( attribute ) );
  54168. const bufferGPU = data.buffer;
  54169. const size = bufferGPU.size;
  54170. const readBufferGPU = device.createBuffer( {
  54171. label: `${ attribute.name }_readback`,
  54172. size,
  54173. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  54174. } );
  54175. const cmdEncoder = device.createCommandEncoder( {
  54176. label: `readback_encoder_${ attribute.name }`
  54177. } );
  54178. cmdEncoder.copyBufferToBuffer(
  54179. bufferGPU,
  54180. 0,
  54181. readBufferGPU,
  54182. 0,
  54183. size
  54184. );
  54185. const gpuCommands = cmdEncoder.finish();
  54186. device.queue.submit( [ gpuCommands ] );
  54187. await readBufferGPU.mapAsync( GPUMapMode.READ );
  54188. const arrayBuffer = readBufferGPU.getMappedRange();
  54189. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  54190. readBufferGPU.unmap();
  54191. return dstBuffer.buffer;
  54192. }
  54193. /**
  54194. * Returns the vertex format of the given buffer attribute.
  54195. *
  54196. * @private
  54197. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  54198. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  54199. */
  54200. _getVertexFormat( geometryAttribute ) {
  54201. const { itemSize, normalized } = geometryAttribute;
  54202. const ArrayType = geometryAttribute.array.constructor;
  54203. const AttributeType = geometryAttribute.constructor;
  54204. let format;
  54205. if ( itemSize === 1 ) {
  54206. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  54207. } else {
  54208. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  54209. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  54210. if ( prefix ) {
  54211. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  54212. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  54213. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  54214. if ( paddedItemSize % 1 ) {
  54215. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  54216. }
  54217. format = `${prefix}x${paddedItemSize}`;
  54218. }
  54219. }
  54220. if ( ! format ) {
  54221. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  54222. }
  54223. return format;
  54224. }
  54225. /**
  54226. * Utility method for handling interleaved buffer attributes correctly.
  54227. * To process them, their `InterleavedBuffer` is returned.
  54228. *
  54229. * @private
  54230. * @param {BufferAttribute} attribute - The attribute.
  54231. * @return {BufferAttribute|InterleavedBuffer}
  54232. */
  54233. _getBufferAttribute( attribute ) {
  54234. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  54235. return attribute;
  54236. }
  54237. }
  54238. /**
  54239. * Class representing a WebGPU bind group layout.
  54240. *
  54241. * @private
  54242. */
  54243. class BindGroupLayout {
  54244. /**
  54245. * Constructs a new layout.
  54246. *
  54247. * @param {GPUBindGroupLayout} layoutGPU - A GPU Bind Group Layout.
  54248. */
  54249. constructor( layoutGPU ) {
  54250. /**
  54251. * The current GPUBindGroupLayout.
  54252. *
  54253. * @type {GPUBindGroupLayout}
  54254. */
  54255. this.layoutGPU = layoutGPU;
  54256. /**
  54257. * The number of bind groups that use this layout.
  54258. *
  54259. * @type {number}
  54260. */
  54261. this.usedTimes = 0;
  54262. }
  54263. }
  54264. /**
  54265. * A WebGPU backend utility module for managing bindings.
  54266. *
  54267. * When reading the documentation it's helpful to keep in mind that
  54268. * all class definitions starting with 'GPU*' are modules from the
  54269. * WebGPU API. So for example `BindGroup` is a class from the engine
  54270. * whereas `GPUBindGroup` is a class from WebGPU.
  54271. *
  54272. * @private
  54273. */
  54274. class WebGPUBindingUtils {
  54275. /**
  54276. * Constructs a new utility object.
  54277. *
  54278. * @param {WebGPUBackend} backend - The WebGPU backend.
  54279. */
  54280. constructor( backend ) {
  54281. /**
  54282. * A reference to the WebGPU backend.
  54283. *
  54284. * @type {WebGPUBackend}
  54285. */
  54286. this.backend = backend;
  54287. /**
  54288. * A cache that maps combinations of layout entries to existing bind group layouts.
  54289. *
  54290. * @private
  54291. * @type {Map<string, BindGroupLayout>}
  54292. */
  54293. this._bindGroupLayoutCache = new Map();
  54294. }
  54295. /**
  54296. * Creates a GPU bind group layout for the given bind group.
  54297. *
  54298. * @param {BindGroup} bindGroup - The bind group.
  54299. * @return {GPUBindGroupLayout} The GPU bind group layout.
  54300. */
  54301. createBindingsLayout( bindGroup ) {
  54302. const backend = this.backend;
  54303. const device = backend.device;
  54304. const bindingsData = backend.get( bindGroup );
  54305. const entries = this._createLayoutEntries( bindGroup );
  54306. const bindGroupLayoutHash = hashString( JSON.stringify( entries ) );
  54307. let layoutChanged = false;
  54308. // check if the bind group already has a layout and if it's still valid
  54309. if ( bindingsData.layout ) {
  54310. // if the layout hash changed (e.g. visibility was updated), invalidate the old layout
  54311. if ( bindingsData.layoutHash !== bindGroupLayoutHash ) {
  54312. bindingsData.layout.usedTimes --;
  54313. if ( bindingsData.layout.usedTimes === 0 ) {
  54314. this._bindGroupLayoutCache.delete( bindingsData.layoutHash );
  54315. }
  54316. bindingsData.layout = undefined;
  54317. bindingsData.layoutHash = undefined;
  54318. layoutChanged = true;
  54319. } else {
  54320. return bindingsData.layout.layoutGPU;
  54321. }
  54322. }
  54323. // create or reuse a bind group layout from the cache
  54324. let bindGroupLayout = this._bindGroupLayoutCache.get( bindGroupLayoutHash );
  54325. if ( bindGroupLayout === undefined ) {
  54326. bindGroupLayout = new BindGroupLayout( device.createBindGroupLayout( { entries } ) );
  54327. this._bindGroupLayoutCache.set( bindGroupLayoutHash, bindGroupLayout );
  54328. }
  54329. bindGroupLayout.usedTimes ++;
  54330. bindingsData.layout = bindGroupLayout;
  54331. bindingsData.layoutHash = bindGroupLayoutHash;
  54332. // if layout changed, recreate the GPU bind group with the new layout
  54333. if ( layoutChanged ) {
  54334. bindingsData.group = this.createBindGroup( bindGroup, bindGroupLayout.layoutGPU );
  54335. }
  54336. return bindGroupLayout.layoutGPU;
  54337. }
  54338. /**
  54339. * Creates bindings from the given bind group definition.
  54340. *
  54341. * @param {BindGroup} bindGroup - The bind group.
  54342. * @param {Array<BindGroup>} bindings - Array of bind groups.
  54343. * @param {number} cacheIndex - The cache index.
  54344. * @param {number} version - The version.
  54345. */
  54346. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  54347. const { backend } = this;
  54348. const bindingsData = backend.get( bindGroup );
  54349. // setup (static) binding layout and (dynamic) binding group
  54350. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  54351. let bindGroupGPU;
  54352. if ( cacheIndex > 0 ) {
  54353. if ( bindingsData.groups === undefined ) {
  54354. bindingsData.groups = [];
  54355. bindingsData.versions = [];
  54356. }
  54357. if ( bindingsData.versions[ cacheIndex ] === version ) {
  54358. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  54359. }
  54360. }
  54361. if ( bindGroupGPU === undefined ) {
  54362. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  54363. if ( cacheIndex > 0 ) {
  54364. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  54365. bindingsData.versions[ cacheIndex ] = version;
  54366. }
  54367. }
  54368. bindingsData.group = bindGroupGPU;
  54369. }
  54370. /**
  54371. * Updates a buffer binding.
  54372. *
  54373. * @param {Buffer} binding - The buffer binding to update.
  54374. */
  54375. updateBinding( binding ) {
  54376. const backend = this.backend;
  54377. const device = backend.device;
  54378. const array = binding.buffer; // cpu
  54379. const buffer = backend.get( binding ).buffer; // gpu
  54380. const updateRanges = binding.updateRanges;
  54381. if ( updateRanges.length === 0 ) {
  54382. device.queue.writeBuffer(
  54383. buffer,
  54384. 0,
  54385. array,
  54386. 0
  54387. );
  54388. } else {
  54389. const isTyped = isTypedArray( array );
  54390. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  54391. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  54392. const range = updateRanges[ i ];
  54393. const dataOffset = range.start * byteOffsetFactor;
  54394. const size = range.count * byteOffsetFactor;
  54395. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  54396. device.queue.writeBuffer(
  54397. buffer,
  54398. bufferOffset,
  54399. array,
  54400. dataOffset,
  54401. size
  54402. );
  54403. }
  54404. }
  54405. }
  54406. /**
  54407. * Creates a GPU bind group for the camera index.
  54408. *
  54409. * @param {Uint32Array} data - The index data.
  54410. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  54411. * @return {GPUBindGroup} The GPU bind group.
  54412. */
  54413. createBindGroupIndex( data, layoutGPU ) {
  54414. const backend = this.backend;
  54415. const device = backend.device;
  54416. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  54417. const index = data[ 0 ];
  54418. const buffer = device.createBuffer( {
  54419. label: 'bindingCameraIndex_' + index,
  54420. size: 16, // uint(4) * 4
  54421. usage: usage
  54422. } );
  54423. device.queue.writeBuffer( buffer, 0, data, 0 );
  54424. const entries = [ { binding: 0, resource: { buffer } } ];
  54425. return device.createBindGroup( {
  54426. label: 'bindGroupCameraIndex_' + index,
  54427. layout: layoutGPU,
  54428. entries
  54429. } );
  54430. }
  54431. /**
  54432. * Creates a GPU bind group for the given bind group and GPU layout.
  54433. *
  54434. * @param {BindGroup} bindGroup - The bind group.
  54435. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  54436. * @return {GPUBindGroup} The GPU bind group.
  54437. */
  54438. createBindGroup( bindGroup, layoutGPU ) {
  54439. const backend = this.backend;
  54440. const device = backend.device;
  54441. let bindingPoint = 0;
  54442. const entriesGPU = [];
  54443. for ( const binding of bindGroup.bindings ) {
  54444. if ( binding.isUniformBuffer ) {
  54445. const bindingData = backend.get( binding );
  54446. if ( bindingData.buffer === undefined ) {
  54447. const byteLength = binding.byteLength;
  54448. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  54449. const visibilities = [];
  54450. if ( binding.visibility & GPUShaderStage.VERTEX ) {
  54451. visibilities.push( 'vertex' );
  54452. }
  54453. if ( binding.visibility & GPUShaderStage.FRAGMENT ) {
  54454. visibilities.push( 'fragment' );
  54455. }
  54456. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  54457. visibilities.push( 'compute' );
  54458. }
  54459. const bufferVisibility = `(${visibilities.join( ',' )})`;
  54460. const bufferGPU = device.createBuffer( {
  54461. label: `bindingBuffer${binding.id}_${binding.name}_${bufferVisibility}`,
  54462. size: byteLength,
  54463. usage: usage
  54464. } );
  54465. bindingData.buffer = bufferGPU;
  54466. }
  54467. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  54468. } else if ( binding.isStorageBuffer ) {
  54469. const buffer = backend.get( binding.attribute ).buffer;
  54470. entriesGPU.push( { binding: bindingPoint, resource: { buffer: buffer } } );
  54471. } else if ( binding.isSampledTexture ) {
  54472. const textureData = backend.get( binding.texture );
  54473. let resourceGPU;
  54474. if ( textureData.externalTexture !== undefined ) {
  54475. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  54476. } else {
  54477. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  54478. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  54479. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  54480. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  54481. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  54482. }
  54483. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  54484. resourceGPU = textureData[ propertyName ];
  54485. if ( resourceGPU === undefined ) {
  54486. const aspectGPU = GPUTextureAspect.All;
  54487. let dimensionViewGPU;
  54488. if ( binding.isSampledCubeTexture ) {
  54489. dimensionViewGPU = GPUTextureViewDimension.Cube;
  54490. } else if ( binding.isSampledTexture3D ) {
  54491. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  54492. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  54493. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  54494. } else {
  54495. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  54496. }
  54497. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount, baseMipLevel } );
  54498. }
  54499. }
  54500. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  54501. } else if ( binding.isSampler ) {
  54502. const textureGPU = backend.get( binding.texture );
  54503. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  54504. }
  54505. bindingPoint ++;
  54506. }
  54507. return device.createBindGroup( {
  54508. label: 'bindGroup_' + bindGroup.name,
  54509. layout: layoutGPU,
  54510. entries: entriesGPU
  54511. } );
  54512. }
  54513. /**
  54514. * Creates a GPU bind group layout entries for the given bind group.
  54515. *
  54516. * @private
  54517. * @param {BindGroup} bindGroup - The bind group.
  54518. * @return {Array<GPUBindGroupLayoutEntry>} The GPU bind group layout entries.
  54519. */
  54520. _createLayoutEntries( bindGroup ) {
  54521. const entries = [];
  54522. let index = 0;
  54523. for ( const binding of bindGroup.bindings ) {
  54524. const backend = this.backend;
  54525. const bindingGPU = {
  54526. binding: index,
  54527. visibility: binding.visibility
  54528. };
  54529. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  54530. const buffer = {}; // GPUBufferBindingLayout
  54531. if ( binding.isStorageBuffer ) {
  54532. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  54533. // compute
  54534. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  54535. buffer.type = GPUBufferBindingType.Storage;
  54536. } else {
  54537. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  54538. }
  54539. } else {
  54540. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  54541. }
  54542. }
  54543. bindingGPU.buffer = buffer;
  54544. } else if ( binding.isSampledTexture && binding.store ) {
  54545. const storageTexture = {}; // GPUStorageTextureBindingLayout
  54546. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  54547. const access = binding.access;
  54548. if ( access === NodeAccess.READ_WRITE ) {
  54549. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  54550. } else if ( access === NodeAccess.WRITE_ONLY ) {
  54551. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  54552. } else {
  54553. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  54554. }
  54555. if ( binding.texture.isArrayTexture ) {
  54556. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  54557. } else if ( binding.texture.is3DTexture ) {
  54558. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  54559. }
  54560. bindingGPU.storageTexture = storageTexture;
  54561. } else if ( binding.isSampledTexture ) {
  54562. const texture = {}; // GPUTextureBindingLayout
  54563. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  54564. if ( primarySamples > 1 ) {
  54565. texture.multisampled = true;
  54566. if ( ! binding.texture.isDepthTexture ) {
  54567. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54568. }
  54569. }
  54570. if ( binding.texture.isDepthTexture ) {
  54571. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  54572. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54573. } else {
  54574. texture.sampleType = GPUTextureSampleType.Depth;
  54575. }
  54576. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  54577. const type = binding.texture.type;
  54578. if ( type === IntType ) {
  54579. texture.sampleType = GPUTextureSampleType.SInt;
  54580. } else if ( type === UnsignedIntType ) {
  54581. texture.sampleType = GPUTextureSampleType.UInt;
  54582. } else if ( type === FloatType ) {
  54583. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  54584. texture.sampleType = GPUTextureSampleType.Float;
  54585. } else {
  54586. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54587. }
  54588. }
  54589. }
  54590. if ( binding.isSampledCubeTexture ) {
  54591. texture.viewDimension = GPUTextureViewDimension.Cube;
  54592. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  54593. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  54594. } else if ( binding.isSampledTexture3D ) {
  54595. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  54596. }
  54597. bindingGPU.texture = texture;
  54598. } else if ( binding.isSampler ) {
  54599. const sampler = {}; // GPUSamplerBindingLayout
  54600. if ( binding.texture.isDepthTexture ) {
  54601. if ( binding.texture.compareFunction !== null && backend.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  54602. sampler.type = GPUSamplerBindingType.Comparison;
  54603. } else {
  54604. // Depth textures without compare must use non-filtering sampler
  54605. sampler.type = GPUSamplerBindingType.NonFiltering;
  54606. }
  54607. }
  54608. bindingGPU.sampler = sampler;
  54609. } else {
  54610. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  54611. }
  54612. entries.push( bindingGPU );
  54613. index ++;
  54614. }
  54615. return entries;
  54616. }
  54617. /**
  54618. * Delete the data associated with a bind group.
  54619. *
  54620. * @param {BindGroup} bindGroup - The bind group.
  54621. */
  54622. deleteBindGroupData( bindGroup ) {
  54623. const { backend } = this;
  54624. const bindingsData = backend.get( bindGroup );
  54625. if ( bindingsData.layout ) {
  54626. bindingsData.layout.usedTimes --;
  54627. if ( bindingsData.layout.usedTimes === 0 ) {
  54628. this._bindGroupLayoutCache.delete( bindingsData.layoutHash );
  54629. }
  54630. bindingsData.layout = undefined;
  54631. bindingsData.layoutHash = undefined;
  54632. }
  54633. }
  54634. /**
  54635. * Frees internal resources.
  54636. */
  54637. dispose() {
  54638. this._bindGroupLayoutCache.clear();
  54639. }
  54640. }
  54641. /**
  54642. * A WebGPU backend utility module for managing pipelines.
  54643. *
  54644. * @private
  54645. */
  54646. class WebGPUPipelineUtils {
  54647. /**
  54648. * Constructs a new utility object.
  54649. *
  54650. * @param {WebGPUBackend} backend - The WebGPU backend.
  54651. */
  54652. constructor( backend ) {
  54653. /**
  54654. * A reference to the WebGPU backend.
  54655. *
  54656. * @type {WebGPUBackend}
  54657. */
  54658. this.backend = backend;
  54659. /**
  54660. * A Weak Map that tracks the active pipeline for render or compute passes.
  54661. *
  54662. * @private
  54663. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  54664. */
  54665. this._activePipelines = new WeakMap();
  54666. }
  54667. /**
  54668. * Sets the given pipeline for the given pass. The method makes sure to only set the
  54669. * pipeline when necessary.
  54670. *
  54671. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  54672. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  54673. */
  54674. setPipeline( pass, pipeline ) {
  54675. const currentPipeline = this._activePipelines.get( pass );
  54676. if ( currentPipeline !== pipeline ) {
  54677. pass.setPipeline( pipeline );
  54678. this._activePipelines.set( pass, pipeline );
  54679. }
  54680. }
  54681. /**
  54682. * Returns the sample count derived from the given render context.
  54683. *
  54684. * @private
  54685. * @param {RenderContext} renderContext - The render context.
  54686. * @return {number} The sample count.
  54687. */
  54688. _getSampleCount( renderContext ) {
  54689. return this.backend.utils.getSampleCountRenderContext( renderContext );
  54690. }
  54691. /**
  54692. * Creates a render pipeline for the given render object.
  54693. *
  54694. * @param {RenderObject} renderObject - The render object.
  54695. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  54696. */
  54697. createRenderPipeline( renderObject, promises ) {
  54698. const { object, material, geometry, pipeline } = renderObject;
  54699. const { vertexProgram, fragmentProgram } = pipeline;
  54700. const backend = this.backend;
  54701. const device = backend.device;
  54702. const utils = backend.utils;
  54703. const pipelineData = backend.get( pipeline );
  54704. // bind group layouts
  54705. const bindGroupLayouts = [];
  54706. for ( const bindGroup of renderObject.getBindings() ) {
  54707. // ensure layout is up to date (visibility may have changed due to shared bind groups)
  54708. const layoutGPU = backend.bindingUtils.createBindingsLayout( bindGroup );
  54709. bindGroupLayouts.push( layoutGPU );
  54710. }
  54711. // vertex buffers
  54712. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  54713. // material blending
  54714. let materialBlending;
  54715. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  54716. materialBlending = this._getBlending( material );
  54717. }
  54718. // stencil
  54719. let stencilFront = {};
  54720. if ( material.stencilWrite === true ) {
  54721. stencilFront = {
  54722. compare: this._getStencilCompare( material ),
  54723. failOp: this._getStencilOperation( material.stencilFail ),
  54724. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  54725. passOp: this._getStencilOperation( material.stencilZPass )
  54726. };
  54727. }
  54728. const colorWriteMask = this._getColorWriteMask( material );
  54729. const targets = [];
  54730. if ( renderObject.context.textures !== null ) {
  54731. const textures = renderObject.context.textures;
  54732. const mrt = renderObject.context.mrt;
  54733. for ( let i = 0; i < textures.length; i ++ ) {
  54734. const texture = textures[ i ];
  54735. const colorFormat = utils.getTextureFormatGPU( texture );
  54736. // mrt blending
  54737. let blending;
  54738. if ( mrt !== null ) {
  54739. if ( this.backend.compatibilityMode !== true ) {
  54740. const blendMode = mrt.getBlendMode( texture.name );
  54741. if ( blendMode.blending === MaterialBlending ) {
  54742. blending = materialBlending;
  54743. } else if ( blendMode.blending !== NoBlending ) {
  54744. blending = this._getBlending( blendMode );
  54745. }
  54746. } else {
  54747. 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.' );
  54748. blending = materialBlending;
  54749. }
  54750. } else {
  54751. blending = materialBlending;
  54752. }
  54753. targets.push( {
  54754. format: colorFormat,
  54755. blend: blending,
  54756. writeMask: colorWriteMask
  54757. } );
  54758. }
  54759. } else {
  54760. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  54761. targets.push( {
  54762. format: colorFormat,
  54763. blend: materialBlending,
  54764. writeMask: colorWriteMask
  54765. } );
  54766. }
  54767. const vertexModule = backend.get( vertexProgram ).module;
  54768. const fragmentModule = backend.get( fragmentProgram ).module;
  54769. const primitiveState = this._getPrimitiveState( object, geometry, material );
  54770. const depthCompare = this._getDepthCompare( material );
  54771. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  54772. const sampleCount = this._getSampleCount( renderObject.context );
  54773. const pipelineDescriptor = {
  54774. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  54775. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  54776. fragment: Object.assign( {}, fragmentModule, { targets } ),
  54777. primitive: primitiveState,
  54778. multisample: {
  54779. count: sampleCount,
  54780. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  54781. },
  54782. layout: device.createPipelineLayout( {
  54783. bindGroupLayouts
  54784. } )
  54785. };
  54786. const depthStencil = {};
  54787. const renderDepth = renderObject.context.depth;
  54788. const renderStencil = renderObject.context.stencil;
  54789. if ( renderDepth === true || renderStencil === true ) {
  54790. if ( renderDepth === true ) {
  54791. depthStencil.format = depthStencilFormat;
  54792. depthStencil.depthWriteEnabled = material.depthWrite;
  54793. depthStencil.depthCompare = depthCompare;
  54794. }
  54795. if ( renderStencil === true ) {
  54796. depthStencil.stencilFront = stencilFront;
  54797. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  54798. depthStencil.stencilReadMask = material.stencilFuncMask;
  54799. depthStencil.stencilWriteMask = material.stencilWriteMask;
  54800. }
  54801. if ( material.polygonOffset === true ) {
  54802. depthStencil.depthBias = material.polygonOffsetUnits;
  54803. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  54804. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  54805. }
  54806. pipelineDescriptor.depthStencil = depthStencil;
  54807. }
  54808. // create pipeline
  54809. device.pushErrorScope( 'validation' );
  54810. if ( promises === null ) {
  54811. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  54812. device.popErrorScope().then( ( err ) => {
  54813. if ( err !== null ) {
  54814. pipelineData.error = true;
  54815. error( err.message );
  54816. }
  54817. } );
  54818. } else {
  54819. const p = new Promise( async ( resolve /*, reject*/ ) => {
  54820. try {
  54821. pipelineData.pipeline = await device.createRenderPipelineAsync( pipelineDescriptor );
  54822. } catch ( err ) { }
  54823. const errorScope = await device.popErrorScope();
  54824. if ( errorScope !== null ) {
  54825. pipelineData.error = true;
  54826. error( errorScope.message );
  54827. }
  54828. resolve();
  54829. } );
  54830. promises.push( p );
  54831. }
  54832. }
  54833. /**
  54834. * Creates GPU render bundle encoder for the given render context.
  54835. *
  54836. * @param {RenderContext} renderContext - The render context.
  54837. * @param {?string} [label='renderBundleEncoder'] - The label.
  54838. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  54839. */
  54840. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  54841. const backend = this.backend;
  54842. const { utils, device } = backend;
  54843. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  54844. const colorFormats = utils.getCurrentColorFormats( renderContext );
  54845. const sampleCount = this._getSampleCount( renderContext );
  54846. const descriptor = {
  54847. label,
  54848. colorFormats,
  54849. depthStencilFormat,
  54850. sampleCount
  54851. };
  54852. return device.createRenderBundleEncoder( descriptor );
  54853. }
  54854. /**
  54855. * Creates a compute pipeline for the given compute node.
  54856. *
  54857. * @param {ComputePipeline} pipeline - The compute pipeline.
  54858. * @param {Array<BindGroup>} bindings - The bindings.
  54859. */
  54860. createComputePipeline( pipeline, bindings ) {
  54861. const backend = this.backend;
  54862. const device = backend.device;
  54863. const computeProgram = backend.get( pipeline.computeProgram ).module;
  54864. const pipelineGPU = backend.get( pipeline );
  54865. // bind group layouts
  54866. const bindGroupLayouts = [];
  54867. for ( const bindingsGroup of bindings ) {
  54868. // ensure layout is up to date (visibility may have changed due to shared bind groups)
  54869. const layoutGPU = backend.bindingUtils.createBindingsLayout( bindingsGroup );
  54870. bindGroupLayouts.push( layoutGPU );
  54871. }
  54872. pipelineGPU.pipeline = device.createComputePipeline( {
  54873. compute: computeProgram,
  54874. layout: device.createPipelineLayout( {
  54875. bindGroupLayouts
  54876. } )
  54877. } );
  54878. }
  54879. /**
  54880. * Returns the blending state as a descriptor object required
  54881. * for the pipeline creation.
  54882. *
  54883. * @private
  54884. * @param {Material|BlendMode} object - The object containing blending information.
  54885. * @return {Object} The blending state.
  54886. */
  54887. _getBlending( object ) {
  54888. let color, alpha;
  54889. const blending = object.blending;
  54890. const blendSrc = object.blendSrc;
  54891. const blendDst = object.blendDst;
  54892. const blendEquation = object.blendEquation;
  54893. if ( blending === CustomBlending ) {
  54894. const blendSrcAlpha = object.blendSrcAlpha !== null ? object.blendSrcAlpha : blendSrc;
  54895. const blendDstAlpha = object.blendDstAlpha !== null ? object.blendDstAlpha : blendDst;
  54896. const blendEquationAlpha = object.blendEquationAlpha !== null ? object.blendEquationAlpha : blendEquation;
  54897. color = {
  54898. srcFactor: this._getBlendFactor( blendSrc ),
  54899. dstFactor: this._getBlendFactor( blendDst ),
  54900. operation: this._getBlendOperation( blendEquation )
  54901. };
  54902. alpha = {
  54903. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  54904. dstFactor: this._getBlendFactor( blendDstAlpha ),
  54905. operation: this._getBlendOperation( blendEquationAlpha )
  54906. };
  54907. } else {
  54908. const premultipliedAlpha = object.premultipliedAlpha;
  54909. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  54910. color = {
  54911. srcFactor: srcRGB,
  54912. dstFactor: dstRGB,
  54913. operation: GPUBlendOperation.Add
  54914. };
  54915. alpha = {
  54916. srcFactor: srcAlpha,
  54917. dstFactor: dstAlpha,
  54918. operation: GPUBlendOperation.Add
  54919. };
  54920. };
  54921. if ( premultipliedAlpha ) {
  54922. switch ( blending ) {
  54923. case NormalBlending:
  54924. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  54925. break;
  54926. case AdditiveBlending:
  54927. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  54928. break;
  54929. case SubtractiveBlending:
  54930. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  54931. break;
  54932. case MultiplyBlending:
  54933. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  54934. break;
  54935. }
  54936. } else {
  54937. switch ( blending ) {
  54938. case NormalBlending:
  54939. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  54940. break;
  54941. case AdditiveBlending:
  54942. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  54943. break;
  54944. case SubtractiveBlending:
  54945. error( `WebGPURenderer: "SubtractiveBlending" requires "${ object.isMaterial ? 'material' : 'blendMode' }.premultipliedAlpha = true".` );
  54946. break;
  54947. case MultiplyBlending:
  54948. error( `WebGPURenderer: "MultiplyBlending" requires "${ object.isMaterial ? 'material' : 'blendMode' }.premultipliedAlpha = true".` );
  54949. break;
  54950. }
  54951. }
  54952. }
  54953. if ( color !== undefined && alpha !== undefined ) {
  54954. return { color, alpha };
  54955. } else {
  54956. error( 'WebGPURenderer: Invalid blending: ', blending );
  54957. }
  54958. }
  54959. /**
  54960. * Returns the GPU blend factor which is required for the pipeline creation.
  54961. *
  54962. * @private
  54963. * @param {number} blend - The blend factor as a three.js constant.
  54964. * @return {string} The GPU blend factor.
  54965. */
  54966. _getBlendFactor( blend ) {
  54967. let blendFactor;
  54968. switch ( blend ) {
  54969. case ZeroFactor:
  54970. blendFactor = GPUBlendFactor.Zero;
  54971. break;
  54972. case OneFactor:
  54973. blendFactor = GPUBlendFactor.One;
  54974. break;
  54975. case SrcColorFactor:
  54976. blendFactor = GPUBlendFactor.Src;
  54977. break;
  54978. case OneMinusSrcColorFactor:
  54979. blendFactor = GPUBlendFactor.OneMinusSrc;
  54980. break;
  54981. case SrcAlphaFactor:
  54982. blendFactor = GPUBlendFactor.SrcAlpha;
  54983. break;
  54984. case OneMinusSrcAlphaFactor:
  54985. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  54986. break;
  54987. case DstColorFactor:
  54988. blendFactor = GPUBlendFactor.Dst;
  54989. break;
  54990. case OneMinusDstColorFactor:
  54991. blendFactor = GPUBlendFactor.OneMinusDst;
  54992. break;
  54993. case DstAlphaFactor:
  54994. blendFactor = GPUBlendFactor.DstAlpha;
  54995. break;
  54996. case OneMinusDstAlphaFactor:
  54997. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  54998. break;
  54999. case SrcAlphaSaturateFactor:
  55000. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  55001. break;
  55002. case BlendColorFactor:
  55003. blendFactor = GPUBlendFactor.Constant;
  55004. break;
  55005. case OneMinusBlendColorFactor:
  55006. blendFactor = GPUBlendFactor.OneMinusConstant;
  55007. break;
  55008. default:
  55009. error( 'WebGPURenderer: Blend factor not supported.', blend );
  55010. }
  55011. return blendFactor;
  55012. }
  55013. /**
  55014. * Returns the GPU stencil compare function which is required for the pipeline creation.
  55015. *
  55016. * @private
  55017. * @param {Material} material - The material.
  55018. * @return {string} The GPU stencil compare function.
  55019. */
  55020. _getStencilCompare( material ) {
  55021. let stencilCompare;
  55022. const stencilFunc = material.stencilFunc;
  55023. switch ( stencilFunc ) {
  55024. case NeverStencilFunc:
  55025. stencilCompare = GPUCompareFunction.Never;
  55026. break;
  55027. case AlwaysStencilFunc:
  55028. stencilCompare = GPUCompareFunction.Always;
  55029. break;
  55030. case LessStencilFunc:
  55031. stencilCompare = GPUCompareFunction.Less;
  55032. break;
  55033. case LessEqualStencilFunc:
  55034. stencilCompare = GPUCompareFunction.LessEqual;
  55035. break;
  55036. case EqualStencilFunc:
  55037. stencilCompare = GPUCompareFunction.Equal;
  55038. break;
  55039. case GreaterEqualStencilFunc:
  55040. stencilCompare = GPUCompareFunction.GreaterEqual;
  55041. break;
  55042. case GreaterStencilFunc:
  55043. stencilCompare = GPUCompareFunction.Greater;
  55044. break;
  55045. case NotEqualStencilFunc:
  55046. stencilCompare = GPUCompareFunction.NotEqual;
  55047. break;
  55048. default:
  55049. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  55050. }
  55051. return stencilCompare;
  55052. }
  55053. /**
  55054. * Returns the GPU stencil operation which is required for the pipeline creation.
  55055. *
  55056. * @private
  55057. * @param {number} op - A three.js constant defining the stencil operation.
  55058. * @return {string} The GPU stencil operation.
  55059. */
  55060. _getStencilOperation( op ) {
  55061. let stencilOperation;
  55062. switch ( op ) {
  55063. case KeepStencilOp:
  55064. stencilOperation = GPUStencilOperation.Keep;
  55065. break;
  55066. case ZeroStencilOp:
  55067. stencilOperation = GPUStencilOperation.Zero;
  55068. break;
  55069. case ReplaceStencilOp:
  55070. stencilOperation = GPUStencilOperation.Replace;
  55071. break;
  55072. case InvertStencilOp:
  55073. stencilOperation = GPUStencilOperation.Invert;
  55074. break;
  55075. case IncrementStencilOp:
  55076. stencilOperation = GPUStencilOperation.IncrementClamp;
  55077. break;
  55078. case DecrementStencilOp:
  55079. stencilOperation = GPUStencilOperation.DecrementClamp;
  55080. break;
  55081. case IncrementWrapStencilOp:
  55082. stencilOperation = GPUStencilOperation.IncrementWrap;
  55083. break;
  55084. case DecrementWrapStencilOp:
  55085. stencilOperation = GPUStencilOperation.DecrementWrap;
  55086. break;
  55087. default:
  55088. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  55089. }
  55090. return stencilOperation;
  55091. }
  55092. /**
  55093. * Returns the GPU blend operation which is required for the pipeline creation.
  55094. *
  55095. * @private
  55096. * @param {number} blendEquation - A three.js constant defining the blend equation.
  55097. * @return {string} The GPU blend operation.
  55098. */
  55099. _getBlendOperation( blendEquation ) {
  55100. let blendOperation;
  55101. switch ( blendEquation ) {
  55102. case AddEquation:
  55103. blendOperation = GPUBlendOperation.Add;
  55104. break;
  55105. case SubtractEquation:
  55106. blendOperation = GPUBlendOperation.Subtract;
  55107. break;
  55108. case ReverseSubtractEquation:
  55109. blendOperation = GPUBlendOperation.ReverseSubtract;
  55110. break;
  55111. case MinEquation:
  55112. blendOperation = GPUBlendOperation.Min;
  55113. break;
  55114. case MaxEquation:
  55115. blendOperation = GPUBlendOperation.Max;
  55116. break;
  55117. default:
  55118. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  55119. }
  55120. return blendOperation;
  55121. }
  55122. /**
  55123. * Returns the primitive state as a descriptor object required
  55124. * for the pipeline creation.
  55125. *
  55126. * @private
  55127. * @param {Object3D} object - The 3D object.
  55128. * @param {BufferGeometry} geometry - The geometry.
  55129. * @param {Material} material - The material.
  55130. * @return {Object} The primitive state.
  55131. */
  55132. _getPrimitiveState( object, geometry, material ) {
  55133. const descriptor = {};
  55134. const utils = this.backend.utils;
  55135. //
  55136. descriptor.topology = utils.getPrimitiveTopology( object, material );
  55137. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  55138. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  55139. }
  55140. //
  55141. let flipSided = ( material.side === BackSide );
  55142. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  55143. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  55144. //
  55145. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  55146. return descriptor;
  55147. }
  55148. /**
  55149. * Returns the GPU color write mask which is required for the pipeline creation.
  55150. *
  55151. * @private
  55152. * @param {Material} material - The material.
  55153. * @return {number} The GPU color write mask.
  55154. */
  55155. _getColorWriteMask( material ) {
  55156. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  55157. }
  55158. /**
  55159. * Returns the GPU depth compare function which is required for the pipeline creation.
  55160. *
  55161. * @private
  55162. * @param {Material} material - The material.
  55163. * @return {string} The GPU depth compare function.
  55164. */
  55165. _getDepthCompare( material ) {
  55166. let depthCompare;
  55167. if ( material.depthTest === false ) {
  55168. depthCompare = ( this.backend.parameters.reversedDepthBuffer ) ? GPUCompareFunction.Never : GPUCompareFunction.Always;
  55169. } else {
  55170. const depthFunc = ( this.backend.parameters.reversedDepthBuffer ) ? ReversedDepthFuncs[ material.depthFunc ] : material.depthFunc;
  55171. switch ( depthFunc ) {
  55172. case NeverDepth:
  55173. depthCompare = GPUCompareFunction.Never;
  55174. break;
  55175. case AlwaysDepth:
  55176. depthCompare = GPUCompareFunction.Always;
  55177. break;
  55178. case LessDepth:
  55179. depthCompare = GPUCompareFunction.Less;
  55180. break;
  55181. case LessEqualDepth:
  55182. depthCompare = GPUCompareFunction.LessEqual;
  55183. break;
  55184. case EqualDepth:
  55185. depthCompare = GPUCompareFunction.Equal;
  55186. break;
  55187. case GreaterEqualDepth:
  55188. depthCompare = GPUCompareFunction.GreaterEqual;
  55189. break;
  55190. case GreaterDepth:
  55191. depthCompare = GPUCompareFunction.Greater;
  55192. break;
  55193. case NotEqualDepth:
  55194. depthCompare = GPUCompareFunction.NotEqual;
  55195. break;
  55196. default:
  55197. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  55198. }
  55199. }
  55200. return depthCompare;
  55201. }
  55202. }
  55203. /**
  55204. * Manages a pool of WebGPU timestamp queries for performance measurement.
  55205. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  55206. *
  55207. * @augments TimestampQueryPool
  55208. */
  55209. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  55210. /**
  55211. * Creates a new WebGPU timestamp query pool.
  55212. *
  55213. * @param {GPUDevice} device - The WebGPU device to create queries on.
  55214. * @param {string} type - The type identifier for this query pool.
  55215. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  55216. */
  55217. constructor( device, type, maxQueries = 2048 ) {
  55218. super( maxQueries );
  55219. this.device = device;
  55220. this.type = type;
  55221. this.querySet = this.device.createQuerySet( {
  55222. type: 'timestamp',
  55223. count: this.maxQueries,
  55224. label: `queryset_global_timestamp_${type}`
  55225. } );
  55226. const bufferSize = this.maxQueries * 8;
  55227. this.resolveBuffer = this.device.createBuffer( {
  55228. label: `buffer_timestamp_resolve_${type}`,
  55229. size: bufferSize,
  55230. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  55231. } );
  55232. this.resultBuffer = this.device.createBuffer( {
  55233. label: `buffer_timestamp_result_${type}`,
  55234. size: bufferSize,
  55235. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  55236. } );
  55237. }
  55238. /**
  55239. * Allocates a pair of queries for a given render context.
  55240. *
  55241. * @param {string} uid - A unique identifier for the render context.
  55242. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  55243. */
  55244. allocateQueriesForContext( uid ) {
  55245. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  55246. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  55247. 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() } ).` );
  55248. return null;
  55249. }
  55250. const baseOffset = this.currentQueryIndex;
  55251. this.currentQueryIndex += 2;
  55252. this.queryOffsets.set( uid, baseOffset );
  55253. return baseOffset;
  55254. }
  55255. /**
  55256. * Asynchronously resolves all pending queries and returns the total duration.
  55257. * If there's already a pending resolve operation, returns that promise instead.
  55258. *
  55259. * @async
  55260. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  55261. */
  55262. async resolveQueriesAsync() {
  55263. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  55264. return this.lastValue;
  55265. }
  55266. if ( this.pendingResolve ) {
  55267. return this.pendingResolve;
  55268. }
  55269. this.pendingResolve = this._resolveQueries();
  55270. try {
  55271. const result = await this.pendingResolve;
  55272. return result;
  55273. } finally {
  55274. this.pendingResolve = null;
  55275. }
  55276. }
  55277. /**
  55278. * Internal method to resolve queries and calculate total duration.
  55279. *
  55280. * @async
  55281. * @private
  55282. * @returns {Promise<number>} The total duration in milliseconds.
  55283. */
  55284. async _resolveQueries() {
  55285. if ( this.isDisposed ) {
  55286. return this.lastValue;
  55287. }
  55288. try {
  55289. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  55290. return this.lastValue;
  55291. }
  55292. const currentOffsets = new Map( this.queryOffsets );
  55293. const queryCount = this.currentQueryIndex;
  55294. const bytesUsed = queryCount * 8;
  55295. // Reset state before GPU work
  55296. this.currentQueryIndex = 0;
  55297. this.queryOffsets.clear();
  55298. const commandEncoder = this.device.createCommandEncoder();
  55299. commandEncoder.resolveQuerySet(
  55300. this.querySet,
  55301. 0,
  55302. queryCount,
  55303. this.resolveBuffer,
  55304. 0
  55305. );
  55306. commandEncoder.copyBufferToBuffer(
  55307. this.resolveBuffer,
  55308. 0,
  55309. this.resultBuffer,
  55310. 0,
  55311. bytesUsed
  55312. );
  55313. const commandBuffer = commandEncoder.finish();
  55314. this.device.queue.submit( [ commandBuffer ] );
  55315. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  55316. return this.lastValue;
  55317. }
  55318. // Create and track the mapping operation
  55319. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  55320. if ( this.isDisposed ) {
  55321. if ( this.resultBuffer.mapState === 'mapped' ) {
  55322. this.resultBuffer.unmap();
  55323. }
  55324. return this.lastValue;
  55325. }
  55326. //
  55327. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  55328. const framesDuration = {};
  55329. const frames = [];
  55330. for ( const [ uid, baseOffset ] of currentOffsets ) {
  55331. const match = uid.match( /^(.*):f(\d+)$/ );
  55332. const frame = parseInt( match[ 2 ] );
  55333. if ( frames.includes( frame ) === false ) {
  55334. frames.push( frame );
  55335. }
  55336. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  55337. const startTime = times[ baseOffset ];
  55338. const endTime = times[ baseOffset + 1 ];
  55339. const duration = Number( endTime - startTime ) / 1e6;
  55340. this.timestamps.set( uid, duration );
  55341. framesDuration[ frame ] += duration;
  55342. }
  55343. // Return the total duration of the last frame
  55344. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  55345. this.resultBuffer.unmap();
  55346. this.lastValue = totalDuration;
  55347. this.frames = frames;
  55348. return totalDuration;
  55349. } catch ( e ) {
  55350. error( 'Error resolving queries:', e );
  55351. if ( this.resultBuffer.mapState === 'mapped' ) {
  55352. this.resultBuffer.unmap();
  55353. }
  55354. return this.lastValue;
  55355. }
  55356. }
  55357. /**
  55358. * Dispose of the query pool.
  55359. *
  55360. * @async
  55361. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  55362. */
  55363. async dispose() {
  55364. if ( this.isDisposed ) {
  55365. return;
  55366. }
  55367. this.isDisposed = true;
  55368. // Wait for pending resolve operation
  55369. if ( this.pendingResolve ) {
  55370. try {
  55371. await this.pendingResolve;
  55372. } catch ( e ) {
  55373. error( 'Error waiting for pending resolve:', e );
  55374. }
  55375. }
  55376. // Ensure buffer is unmapped before destroying
  55377. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  55378. try {
  55379. this.resultBuffer.unmap();
  55380. } catch ( e ) {
  55381. error( 'Error unmapping buffer:', e );
  55382. }
  55383. }
  55384. // Destroy resources
  55385. if ( this.querySet ) {
  55386. this.querySet.destroy();
  55387. this.querySet = null;
  55388. }
  55389. if ( this.resolveBuffer ) {
  55390. this.resolveBuffer.destroy();
  55391. this.resolveBuffer = null;
  55392. }
  55393. if ( this.resultBuffer ) {
  55394. this.resultBuffer.destroy();
  55395. this.resultBuffer = null;
  55396. }
  55397. this.queryOffsets.clear();
  55398. this.pendingResolve = null;
  55399. }
  55400. }
  55401. /*// debugger tools
  55402. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  55403. //*/
  55404. /**
  55405. * A backend implementation targeting WebGPU.
  55406. *
  55407. * @private
  55408. * @augments Backend
  55409. */
  55410. class WebGPUBackend extends Backend {
  55411. /**
  55412. * WebGPUBackend options.
  55413. *
  55414. * @typedef {Object} WebGPUBackend~Options
  55415. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  55416. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  55417. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  55418. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  55419. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  55420. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  55421. * @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.
  55422. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  55423. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  55424. * @property {string} [powerPreference=undefined] - The power preference.
  55425. * @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.
  55426. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  55427. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  55428. */
  55429. /**
  55430. * Constructs a new WebGPU backend.
  55431. *
  55432. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  55433. */
  55434. constructor( parameters = {} ) {
  55435. super( parameters );
  55436. /**
  55437. * This flag can be used for type testing.
  55438. *
  55439. * @type {boolean}
  55440. * @readonly
  55441. * @default true
  55442. */
  55443. this.isWebGPUBackend = true;
  55444. // some parameters require default values other than "undefined"
  55445. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  55446. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  55447. /**
  55448. * Indicates whether the backend is in WebGPU compatibility mode or not.
  55449. * The backend must be initialized before the property can be evaluated.
  55450. *
  55451. * @type {?boolean}
  55452. * @readonly
  55453. * @default null
  55454. */
  55455. this.compatibilityMode = null;
  55456. /**
  55457. * A reference to the device.
  55458. *
  55459. * @type {?GPUDevice}
  55460. * @default null
  55461. */
  55462. this.device = null;
  55463. /**
  55464. * A reference to the default render pass descriptor.
  55465. *
  55466. * @type {?Object}
  55467. * @default null
  55468. */
  55469. this.defaultRenderPassdescriptor = null;
  55470. /**
  55471. * A reference to a backend module holding common utility functions.
  55472. *
  55473. * @type {WebGPUUtils}
  55474. */
  55475. this.utils = new WebGPUUtils( this );
  55476. /**
  55477. * A reference to a backend module holding shader attribute-related
  55478. * utility functions.
  55479. *
  55480. * @type {WebGPUAttributeUtils}
  55481. */
  55482. this.attributeUtils = new WebGPUAttributeUtils( this );
  55483. /**
  55484. * A reference to a backend module holding shader binding-related
  55485. * utility functions.
  55486. *
  55487. * @type {WebGPUBindingUtils}
  55488. */
  55489. this.bindingUtils = new WebGPUBindingUtils( this );
  55490. /**
  55491. * A reference to a backend module holding shader pipeline-related
  55492. * utility functions.
  55493. *
  55494. * @type {WebGPUPipelineUtils}
  55495. */
  55496. this.pipelineUtils = new WebGPUPipelineUtils( this );
  55497. /**
  55498. * A reference to a backend module holding shader texture-related
  55499. * utility functions.
  55500. *
  55501. * @type {WebGPUTextureUtils}
  55502. */
  55503. this.textureUtils = new WebGPUTextureUtils( this );
  55504. /**
  55505. * A map that manages the resolve buffers for occlusion queries.
  55506. *
  55507. * @type {Map<number,GPUBuffer>}
  55508. */
  55509. this.occludedResolveCache = new Map();
  55510. // compatibility checks
  55511. const compatibilityTextureCompare = typeof navigator === 'undefined' ? true : /Android/.test( navigator.userAgent ) === false;
  55512. /**
  55513. * A map of compatibility checks.
  55514. *
  55515. * @type {Object}
  55516. */
  55517. this._compatibility = {
  55518. [ Compatibility.TEXTURE_COMPARE ]: compatibilityTextureCompare
  55519. };
  55520. }
  55521. /**
  55522. * Initializes the backend so it is ready for usage.
  55523. *
  55524. * @async
  55525. * @param {Renderer} renderer - The renderer.
  55526. * @return {Promise} A Promise that resolves when the backend has been initialized.
  55527. */
  55528. async init( renderer ) {
  55529. await super.init( renderer );
  55530. //
  55531. const parameters = this.parameters;
  55532. // create the device if it is not passed with parameters
  55533. let device;
  55534. if ( parameters.device === undefined ) {
  55535. const adapterOptions = {
  55536. powerPreference: parameters.powerPreference,
  55537. featureLevel: 'compatibility'
  55538. };
  55539. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  55540. if ( adapter === null ) {
  55541. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  55542. }
  55543. // feature support
  55544. const features = Object.values( GPUFeatureName );
  55545. const supportedFeatures = [];
  55546. for ( const name of features ) {
  55547. if ( adapter.features.has( name ) ) {
  55548. supportedFeatures.push( name );
  55549. }
  55550. }
  55551. const deviceDescriptor = {
  55552. requiredFeatures: supportedFeatures,
  55553. requiredLimits: parameters.requiredLimits
  55554. };
  55555. device = await adapter.requestDevice( deviceDescriptor );
  55556. } else {
  55557. device = parameters.device;
  55558. }
  55559. this.compatibilityMode = ! device.features.has( 'core-features-and-limits' );
  55560. if ( this.compatibilityMode ) {
  55561. renderer._samples = 0;
  55562. }
  55563. device.lost.then( ( info ) => {
  55564. if ( info.reason === 'destroyed' ) return;
  55565. const deviceLossInfo = {
  55566. api: 'WebGPU',
  55567. message: info.message || 'Unknown reason',
  55568. reason: info.reason || null,
  55569. originalEvent: info
  55570. };
  55571. renderer.onDeviceLost( deviceLossInfo );
  55572. } );
  55573. this.device = device;
  55574. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  55575. this.updateSize();
  55576. }
  55577. /**
  55578. * A reference to the context.
  55579. *
  55580. * @type {?GPUCanvasContext}
  55581. * @default null
  55582. */
  55583. get context() {
  55584. const canvasTarget = this.renderer.getCanvasTarget();
  55585. const canvasData = this.get( canvasTarget );
  55586. let context = canvasData.context;
  55587. if ( context === undefined ) {
  55588. const parameters = this.parameters;
  55589. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  55590. context = parameters.context;
  55591. } else {
  55592. context = canvasTarget.domElement.getContext( 'webgpu' );
  55593. }
  55594. // OffscreenCanvas does not have setAttribute, see #22811
  55595. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  55596. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  55597. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  55598. context.configure( {
  55599. device: this.device,
  55600. format: this.utils.getPreferredCanvasFormat(),
  55601. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  55602. alphaMode: alphaMode,
  55603. toneMapping: {
  55604. mode: toneMappingMode
  55605. }
  55606. } );
  55607. canvasData.context = context;
  55608. }
  55609. return context;
  55610. }
  55611. /**
  55612. * The coordinate system of the backend.
  55613. *
  55614. * @type {number}
  55615. * @readonly
  55616. */
  55617. get coordinateSystem() {
  55618. return WebGPUCoordinateSystem;
  55619. }
  55620. /**
  55621. * This method performs a readback operation by moving buffer data from
  55622. * a storage buffer attribute from the GPU to the CPU.
  55623. *
  55624. * @async
  55625. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  55626. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  55627. */
  55628. async getArrayBufferAsync( attribute ) {
  55629. return await this.attributeUtils.getArrayBufferAsync( attribute );
  55630. }
  55631. /**
  55632. * Returns the backend's rendering context.
  55633. *
  55634. * @return {GPUCanvasContext} The rendering context.
  55635. */
  55636. getContext() {
  55637. return this.context;
  55638. }
  55639. /**
  55640. * Returns the default render pass descriptor.
  55641. *
  55642. * In WebGPU, the default framebuffer must be configured
  55643. * like custom framebuffers so the backend needs a render
  55644. * pass descriptor even when rendering directly to screen.
  55645. *
  55646. * @private
  55647. * @return {Object} The render pass descriptor.
  55648. */
  55649. _getDefaultRenderPassDescriptor() {
  55650. const renderer = this.renderer;
  55651. const canvasTarget = renderer.getCanvasTarget();
  55652. const canvasData = this.get( canvasTarget );
  55653. const samples = renderer.currentSamples;
  55654. let descriptor = canvasData.descriptor;
  55655. if ( descriptor === undefined || canvasData.samples !== samples ) {
  55656. descriptor = {
  55657. colorAttachments: [ {
  55658. view: null
  55659. } ]
  55660. };
  55661. if ( renderer.depth === true || renderer.stencil === true ) {
  55662. descriptor.depthStencilAttachment = {
  55663. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  55664. };
  55665. }
  55666. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55667. if ( samples > 0 ) {
  55668. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  55669. } else {
  55670. colorAttachment.resolveTarget = undefined;
  55671. }
  55672. canvasData.descriptor = descriptor;
  55673. canvasData.samples = samples;
  55674. }
  55675. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55676. if ( samples > 0 ) {
  55677. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  55678. } else {
  55679. colorAttachment.view = this.context.getCurrentTexture().createView();
  55680. }
  55681. return descriptor;
  55682. }
  55683. /**
  55684. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  55685. *
  55686. * @param {RenderContext} renderContext - The render context.
  55687. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  55688. *
  55689. * @private
  55690. */
  55691. _isRenderCameraDepthArray( renderContext ) {
  55692. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  55693. }
  55694. /**
  55695. * Returns the render pass descriptor for the given render context.
  55696. *
  55697. * @private
  55698. * @param {RenderContext} renderContext - The render context.
  55699. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  55700. * @return {Object} The render pass descriptor.
  55701. */
  55702. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  55703. const renderTarget = renderContext.renderTarget;
  55704. const renderTargetData = this.get( renderTarget );
  55705. let descriptors = renderTargetData.descriptors;
  55706. if ( descriptors === undefined ||
  55707. renderTargetData.width !== renderTarget.width ||
  55708. renderTargetData.height !== renderTarget.height ||
  55709. renderTargetData.samples !== renderTarget.samples
  55710. ) {
  55711. descriptors = {};
  55712. renderTargetData.descriptors = descriptors;
  55713. }
  55714. const cacheKey = renderContext.getCacheKey();
  55715. let descriptorBase = descriptors[ cacheKey ];
  55716. if ( descriptorBase === undefined ) {
  55717. const textures = renderContext.textures;
  55718. const textureViews = [];
  55719. let sliceIndex;
  55720. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  55721. for ( let i = 0; i < textures.length; i ++ ) {
  55722. const textureData = this.get( textures[ i ] );
  55723. const viewDescriptor = {
  55724. label: `colorAttachment_${ i }`,
  55725. baseMipLevel: renderContext.activeMipmapLevel,
  55726. mipLevelCount: 1,
  55727. baseArrayLayer: renderContext.activeCubeFace,
  55728. arrayLayerCount: 1,
  55729. dimension: GPUTextureViewDimension.TwoD
  55730. };
  55731. if ( renderTarget.isRenderTarget3D ) {
  55732. sliceIndex = renderContext.activeCubeFace;
  55733. viewDescriptor.baseArrayLayer = 0;
  55734. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  55735. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55736. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  55737. if ( isRenderCameraDepthArray === true ) {
  55738. const cameras = renderContext.camera.cameras;
  55739. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  55740. const layerViewDescriptor = {
  55741. ...viewDescriptor,
  55742. baseArrayLayer: layer,
  55743. arrayLayerCount: 1,
  55744. dimension: GPUTextureViewDimension.TwoD
  55745. };
  55746. const textureView = textureData.texture.createView( layerViewDescriptor );
  55747. textureViews.push( {
  55748. view: textureView,
  55749. resolveTarget: undefined,
  55750. depthSlice: undefined
  55751. } );
  55752. }
  55753. } else {
  55754. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  55755. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55756. }
  55757. }
  55758. if ( isRenderCameraDepthArray !== true ) {
  55759. const textureView = textureData.texture.createView( viewDescriptor );
  55760. let view, resolveTarget;
  55761. if ( textureData.msaaTexture !== undefined ) {
  55762. view = textureData.msaaTexture.createView();
  55763. resolveTarget = textureView;
  55764. } else {
  55765. view = textureView;
  55766. resolveTarget = undefined;
  55767. }
  55768. textureViews.push( {
  55769. view,
  55770. resolveTarget,
  55771. depthSlice: sliceIndex
  55772. } );
  55773. }
  55774. }
  55775. descriptorBase = { textureViews };
  55776. if ( renderContext.depth ) {
  55777. const depthTextureData = this.get( renderContext.depthTexture );
  55778. const options = {};
  55779. if ( renderContext.depthTexture.isArrayTexture || renderContext.depthTexture.isCubeTexture ) {
  55780. options.dimension = GPUTextureViewDimension.TwoD;
  55781. options.arrayLayerCount = 1;
  55782. options.baseArrayLayer = renderContext.activeCubeFace;
  55783. }
  55784. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  55785. }
  55786. descriptors[ cacheKey ] = descriptorBase;
  55787. renderTargetData.width = renderTarget.width;
  55788. renderTargetData.height = renderTarget.height;
  55789. renderTargetData.samples = renderTarget.samples;
  55790. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  55791. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  55792. }
  55793. const descriptor = {
  55794. colorAttachments: []
  55795. };
  55796. // Apply dynamic properties to cached views
  55797. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  55798. const viewInfo = descriptorBase.textureViews[ i ];
  55799. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  55800. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  55801. clearValue = colorAttachmentsConfig.clearValue;
  55802. }
  55803. descriptor.colorAttachments.push( {
  55804. view: viewInfo.view,
  55805. depthSlice: viewInfo.depthSlice,
  55806. resolveTarget: viewInfo.resolveTarget,
  55807. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  55808. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  55809. clearValue: clearValue
  55810. } );
  55811. }
  55812. if ( descriptorBase.depthStencilView ) {
  55813. descriptor.depthStencilAttachment = {
  55814. view: descriptorBase.depthStencilView
  55815. };
  55816. }
  55817. return descriptor;
  55818. }
  55819. /**
  55820. * This method is executed at the beginning of a render call and prepares
  55821. * the WebGPU state for upcoming render calls
  55822. *
  55823. * @param {RenderContext} renderContext - The render context.
  55824. */
  55825. beginRender( renderContext ) {
  55826. const renderContextData = this.get( renderContext );
  55827. //
  55828. const device = this.device;
  55829. const occlusionQueryCount = renderContext.occlusionQueryCount;
  55830. let occlusionQuerySet;
  55831. if ( occlusionQueryCount > 0 ) {
  55832. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  55833. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  55834. // Get a reference to the array of objects with queries. The renderContextData property
  55835. // can be changed by another render pass before the buffer.mapAsyc() completes.
  55836. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  55837. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  55838. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  55839. //
  55840. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  55841. renderContextData.occlusionQuerySet = occlusionQuerySet;
  55842. renderContextData.occlusionQueryIndex = 0;
  55843. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  55844. renderContextData.lastOcclusionObject = null;
  55845. }
  55846. let descriptor;
  55847. if ( renderContext.textures === null ) {
  55848. descriptor = this._getDefaultRenderPassDescriptor();
  55849. } else {
  55850. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  55851. }
  55852. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  55853. descriptor.occlusionQuerySet = occlusionQuerySet;
  55854. const depthStencilAttachment = descriptor.depthStencilAttachment;
  55855. if ( renderContext.textures !== null ) {
  55856. const colorAttachments = descriptor.colorAttachments;
  55857. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  55858. const colorAttachment = colorAttachments[ i ];
  55859. if ( renderContext.clearColor ) {
  55860. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  55861. colorAttachment.loadOp = GPULoadOp.Clear;
  55862. } else {
  55863. colorAttachment.loadOp = GPULoadOp.Load;
  55864. }
  55865. colorAttachment.storeOp = GPUStoreOp.Store;
  55866. }
  55867. } else {
  55868. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55869. if ( renderContext.clearColor ) {
  55870. colorAttachment.clearValue = renderContext.clearColorValue;
  55871. colorAttachment.loadOp = GPULoadOp.Clear;
  55872. } else {
  55873. colorAttachment.loadOp = GPULoadOp.Load;
  55874. }
  55875. colorAttachment.storeOp = GPUStoreOp.Store;
  55876. }
  55877. //
  55878. if ( renderContext.depth ) {
  55879. if ( renderContext.clearDepth ) {
  55880. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  55881. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  55882. } else {
  55883. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  55884. }
  55885. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  55886. }
  55887. if ( renderContext.stencil ) {
  55888. if ( renderContext.clearStencil ) {
  55889. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  55890. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  55891. } else {
  55892. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  55893. }
  55894. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  55895. }
  55896. //
  55897. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  55898. // shadow arrays - prepare bundle encoders for each camera in an array camera
  55899. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  55900. const cameras = renderContext.camera.cameras;
  55901. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  55902. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  55903. } else {
  55904. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  55905. }
  55906. // Create bundle encoders for each layer
  55907. renderContextData.bundleEncoders = [];
  55908. renderContextData.bundleSets = [];
  55909. // Create separate bundle encoders for each camera in the array
  55910. for ( let i = 0; i < cameras.length; i ++ ) {
  55911. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  55912. renderContext,
  55913. 'renderBundleArrayCamera_' + i
  55914. );
  55915. // Initialize state tracking for this bundle
  55916. const bundleSets = {
  55917. attributes: {},
  55918. bindingGroups: [],
  55919. pipeline: null,
  55920. index: null
  55921. };
  55922. renderContextData.bundleEncoders.push( bundleEncoder );
  55923. renderContextData.bundleSets.push( bundleSets );
  55924. }
  55925. // We'll complete the bundles in finishRender
  55926. renderContextData.currentPass = null;
  55927. } else {
  55928. const currentPass = encoder.beginRenderPass( descriptor );
  55929. renderContextData.currentPass = currentPass;
  55930. if ( renderContext.viewport ) {
  55931. this.updateViewport( renderContext );
  55932. }
  55933. if ( renderContext.scissor ) {
  55934. this.updateScissor( renderContext );
  55935. }
  55936. }
  55937. //
  55938. renderContextData.descriptor = descriptor;
  55939. renderContextData.encoder = encoder;
  55940. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  55941. renderContextData.renderBundles = [];
  55942. }
  55943. /**
  55944. * This method creates layer descriptors for each camera in an array camera
  55945. * to prepare for rendering to a depth array texture.
  55946. *
  55947. * @param {RenderContext} renderContext - The render context.
  55948. * @param {Object} renderContextData - The render context data.
  55949. * @param {Object} descriptor - The render pass descriptor.
  55950. * @param {ArrayCamera} cameras - The array camera.
  55951. *
  55952. * @private
  55953. */
  55954. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  55955. const depthStencilAttachment = descriptor.depthStencilAttachment;
  55956. renderContextData.layerDescriptors = [];
  55957. const depthTextureData = this.get( renderContext.depthTexture );
  55958. if ( ! depthTextureData.viewCache ) {
  55959. depthTextureData.viewCache = [];
  55960. }
  55961. for ( let i = 0; i < cameras.length; i ++ ) {
  55962. const layerDescriptor = {
  55963. ...descriptor,
  55964. colorAttachments: [ {
  55965. ...descriptor.colorAttachments[ 0 ],
  55966. view: descriptor.colorAttachments[ i ].view
  55967. } ]
  55968. };
  55969. if ( descriptor.depthStencilAttachment ) {
  55970. const layerIndex = i;
  55971. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  55972. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  55973. dimension: GPUTextureViewDimension.TwoD,
  55974. baseArrayLayer: i,
  55975. arrayLayerCount: 1
  55976. } );
  55977. }
  55978. layerDescriptor.depthStencilAttachment = {
  55979. view: depthTextureData.viewCache[ layerIndex ],
  55980. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  55981. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  55982. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  55983. };
  55984. if ( renderContext.stencil ) {
  55985. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  55986. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  55987. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  55988. }
  55989. } else {
  55990. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  55991. }
  55992. renderContextData.layerDescriptors.push( layerDescriptor );
  55993. }
  55994. }
  55995. /**
  55996. * This method updates the layer descriptors for each camera in an array camera
  55997. * to prepare for rendering to a depth array texture.
  55998. *
  55999. * @param {RenderContext} renderContext - The render context.
  56000. * @param {Object} renderContextData - The render context data.
  56001. * @param {ArrayCamera} cameras - The array camera.
  56002. *
  56003. */
  56004. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  56005. for ( let i = 0; i < cameras.length; i ++ ) {
  56006. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  56007. if ( layerDescriptor.depthStencilAttachment ) {
  56008. const depthAttachment = layerDescriptor.depthStencilAttachment;
  56009. if ( renderContext.depth ) {
  56010. if ( renderContext.clearDepth ) {
  56011. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  56012. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  56013. } else {
  56014. depthAttachment.depthLoadOp = GPULoadOp.Load;
  56015. }
  56016. }
  56017. if ( renderContext.stencil ) {
  56018. if ( renderContext.clearStencil ) {
  56019. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  56020. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  56021. } else {
  56022. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  56023. }
  56024. }
  56025. }
  56026. }
  56027. }
  56028. /**
  56029. * This method is executed at the end of a render call and finalizes work
  56030. * after draw calls.
  56031. *
  56032. * @param {RenderContext} renderContext - The render context.
  56033. */
  56034. finishRender( renderContext ) {
  56035. const renderContextData = this.get( renderContext );
  56036. const occlusionQueryCount = renderContext.occlusionQueryCount;
  56037. if ( renderContextData.renderBundles.length > 0 ) {
  56038. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  56039. }
  56040. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  56041. renderContextData.currentPass.endOcclusionQuery();
  56042. }
  56043. // shadow arrays - Execute bundles for each layer
  56044. const encoder = renderContextData.encoder;
  56045. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  56046. const bundles = [];
  56047. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  56048. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  56049. bundles.push( bundleEncoder.finish() );
  56050. }
  56051. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  56052. if ( i < bundles.length ) {
  56053. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  56054. const renderPass = encoder.beginRenderPass( layerDescriptor );
  56055. if ( renderContext.viewport ) {
  56056. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  56057. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  56058. }
  56059. if ( renderContext.scissor ) {
  56060. const { x, y, width, height } = renderContext.scissorValue;
  56061. renderPass.setScissorRect( x, y, width, height );
  56062. }
  56063. renderPass.executeBundles( [ bundles[ i ] ] );
  56064. renderPass.end();
  56065. }
  56066. }
  56067. } else if ( renderContextData.currentPass ) {
  56068. renderContextData.currentPass.end();
  56069. }
  56070. if ( occlusionQueryCount > 0 ) {
  56071. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  56072. //
  56073. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  56074. if ( queryResolveBuffer === undefined ) {
  56075. queryResolveBuffer = this.device.createBuffer(
  56076. {
  56077. size: bufferSize,
  56078. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  56079. }
  56080. );
  56081. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  56082. }
  56083. //
  56084. const readBuffer = this.device.createBuffer(
  56085. {
  56086. size: bufferSize,
  56087. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  56088. }
  56089. );
  56090. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  56091. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  56092. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  56093. renderContextData.occlusionQueryBuffer = readBuffer;
  56094. //
  56095. this.resolveOccludedAsync( renderContext );
  56096. }
  56097. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  56098. //
  56099. if ( renderContext.textures !== null ) {
  56100. const textures = renderContext.textures;
  56101. for ( let i = 0; i < textures.length; i ++ ) {
  56102. const texture = textures[ i ];
  56103. if ( texture.generateMipmaps === true ) {
  56104. this.textureUtils.generateMipmaps( texture );
  56105. }
  56106. }
  56107. }
  56108. }
  56109. /**
  56110. * Returns `true` if the given 3D object is fully occluded by other
  56111. * 3D objects in the scene.
  56112. *
  56113. * @param {RenderContext} renderContext - The render context.
  56114. * @param {Object3D} object - The 3D object to test.
  56115. * @return {boolean} Whether the 3D object is fully occluded or not.
  56116. */
  56117. isOccluded( renderContext, object ) {
  56118. const renderContextData = this.get( renderContext );
  56119. return renderContextData.occluded && renderContextData.occluded.has( object );
  56120. }
  56121. /**
  56122. * This method processes the result of occlusion queries and writes it
  56123. * into render context data.
  56124. *
  56125. * @async
  56126. * @param {RenderContext} renderContext - The render context.
  56127. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  56128. */
  56129. async resolveOccludedAsync( renderContext ) {
  56130. const renderContextData = this.get( renderContext );
  56131. // handle occlusion query results
  56132. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  56133. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  56134. const occluded = new WeakSet();
  56135. renderContextData.currentOcclusionQueryObjects = null;
  56136. renderContextData.currentOcclusionQueryBuffer = null;
  56137. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  56138. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  56139. const results = new BigUint64Array( buffer );
  56140. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  56141. if ( results[ i ] === BigInt( 0 ) ) {
  56142. occluded.add( currentOcclusionQueryObjects[ i ] );
  56143. }
  56144. }
  56145. currentOcclusionQueryBuffer.destroy();
  56146. renderContextData.occluded = occluded;
  56147. }
  56148. }
  56149. /**
  56150. * Updates the viewport with the values from the given render context.
  56151. *
  56152. * @param {RenderContext} renderContext - The render context.
  56153. */
  56154. updateViewport( renderContext ) {
  56155. const { currentPass } = this.get( renderContext );
  56156. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  56157. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  56158. }
  56159. /**
  56160. * Updates the scissor with the values from the given render context.
  56161. *
  56162. * @param {RenderContext} renderContext - The render context.
  56163. */
  56164. updateScissor( renderContext ) {
  56165. const { currentPass } = this.get( renderContext );
  56166. const { x, y, width, height } = renderContext.scissorValue;
  56167. currentPass.setScissorRect( x, y, width, height );
  56168. }
  56169. /**
  56170. * Returns the clear color and alpha into a single
  56171. * color object.
  56172. *
  56173. * @return {Color4} The clear color.
  56174. */
  56175. getClearColor() {
  56176. const clearColor = super.getClearColor();
  56177. // only premultiply alpha when alphaMode is "premultiplied"
  56178. if ( this.renderer.alpha === true ) {
  56179. clearColor.r *= clearColor.a;
  56180. clearColor.g *= clearColor.a;
  56181. clearColor.b *= clearColor.a;
  56182. }
  56183. return clearColor;
  56184. }
  56185. /**
  56186. * Performs a clear operation.
  56187. *
  56188. * @param {boolean} color - Whether the color buffer should be cleared or not.
  56189. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  56190. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  56191. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  56192. */
  56193. clear( color, depth, stencil, renderTargetContext = null ) {
  56194. const device = this.device;
  56195. const renderer = this.renderer;
  56196. let colorAttachments = [];
  56197. let depthStencilAttachment;
  56198. let clearValue;
  56199. let supportsDepth;
  56200. let supportsStencil;
  56201. if ( color ) {
  56202. const clearColor = this.getClearColor();
  56203. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  56204. }
  56205. if ( renderTargetContext === null ) {
  56206. supportsDepth = renderer.depth;
  56207. supportsStencil = renderer.stencil;
  56208. const descriptor = this._getDefaultRenderPassDescriptor();
  56209. if ( color ) {
  56210. colorAttachments = descriptor.colorAttachments;
  56211. const colorAttachment = colorAttachments[ 0 ];
  56212. colorAttachment.clearValue = clearValue;
  56213. colorAttachment.loadOp = GPULoadOp.Clear;
  56214. colorAttachment.storeOp = GPUStoreOp.Store;
  56215. }
  56216. if ( supportsDepth || supportsStencil ) {
  56217. depthStencilAttachment = descriptor.depthStencilAttachment;
  56218. }
  56219. } else {
  56220. supportsDepth = renderTargetContext.depth;
  56221. supportsStencil = renderTargetContext.stencil;
  56222. const clearConfig = {
  56223. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  56224. clearValue: color ? clearValue : undefined
  56225. };
  56226. if ( supportsDepth ) {
  56227. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  56228. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  56229. clearConfig.depthStoreOp = GPUStoreOp.Store;
  56230. }
  56231. if ( supportsStencil ) {
  56232. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  56233. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  56234. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  56235. }
  56236. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  56237. colorAttachments = descriptor.colorAttachments;
  56238. depthStencilAttachment = descriptor.depthStencilAttachment;
  56239. }
  56240. if ( supportsDepth && depthStencilAttachment ) {
  56241. if ( depth ) {
  56242. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  56243. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  56244. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  56245. } else {
  56246. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  56247. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  56248. }
  56249. }
  56250. //
  56251. if ( supportsStencil && depthStencilAttachment ) {
  56252. if ( stencil ) {
  56253. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  56254. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  56255. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  56256. } else {
  56257. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  56258. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  56259. }
  56260. }
  56261. //
  56262. const encoder = device.createCommandEncoder( { label: 'clear' } );
  56263. const currentPass = encoder.beginRenderPass( {
  56264. colorAttachments,
  56265. depthStencilAttachment
  56266. } );
  56267. currentPass.end();
  56268. device.queue.submit( [ encoder.finish() ] );
  56269. }
  56270. // compute
  56271. /**
  56272. * This method is executed at the beginning of a compute call and
  56273. * prepares the state for upcoming compute tasks.
  56274. *
  56275. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  56276. */
  56277. beginCompute( computeGroup ) {
  56278. const groupGPU = this.get( computeGroup );
  56279. //
  56280. const descriptor = {
  56281. label: 'computeGroup_' + computeGroup.id
  56282. };
  56283. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  56284. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  56285. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  56286. }
  56287. /**
  56288. * Executes a compute command for the given compute node.
  56289. *
  56290. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  56291. * @param {Node} computeNode - The compute node.
  56292. * @param {Array<BindGroup>} bindings - The bindings.
  56293. * @param {ComputePipeline} pipeline - The compute pipeline.
  56294. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  56295. * - A single number representing count, or
  56296. * - An array [x, y, z] representing dispatch size, or
  56297. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  56298. */
  56299. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  56300. const computeNodeData = this.get( computeNode );
  56301. const { passEncoderGPU } = this.get( computeGroup );
  56302. // pipeline
  56303. const pipelineGPU = this.get( pipeline ).pipeline;
  56304. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  56305. // bind groups
  56306. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  56307. const bindGroup = bindings[ i ];
  56308. const bindingsData = this.get( bindGroup );
  56309. passEncoderGPU.setBindGroup( i, bindingsData.group );
  56310. }
  56311. if ( dispatchSize === null ) {
  56312. dispatchSize = computeNode.count;
  56313. }
  56314. // When the dispatchSize is set with a StorageBuffer from the GPU.
  56315. if ( dispatchSize && typeof dispatchSize === 'object' && dispatchSize.isIndirectStorageBufferAttribute ) {
  56316. const dispatchBuffer = this.get( dispatchSize ).buffer;
  56317. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  56318. return;
  56319. }
  56320. if ( typeof dispatchSize === 'number' ) {
  56321. // If a single number is given, we calculate the dispatch size based on the workgroup size
  56322. const count = dispatchSize;
  56323. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  56324. // cache dispatch size to avoid recalculating it every time
  56325. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  56326. computeNodeData.count = count;
  56327. const workgroupSize = computeNode.workgroupSize;
  56328. let size = workgroupSize[ 0 ];
  56329. for ( let i = 1; i < workgroupSize.length; i ++ )
  56330. size *= workgroupSize[ i ];
  56331. const dispatchCount = Math.ceil( count / size );
  56332. //
  56333. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  56334. dispatchSize = [ dispatchCount, 1, 1 ];
  56335. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  56336. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  56337. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  56338. }
  56339. computeNodeData.dispatchSize = dispatchSize;
  56340. }
  56341. dispatchSize = computeNodeData.dispatchSize;
  56342. }
  56343. //
  56344. passEncoderGPU.dispatchWorkgroups(
  56345. dispatchSize[ 0 ],
  56346. dispatchSize[ 1 ] || 1,
  56347. dispatchSize[ 2 ] || 1
  56348. );
  56349. }
  56350. /**
  56351. * This method is executed at the end of a compute call and
  56352. * finalizes work after compute tasks.
  56353. *
  56354. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  56355. */
  56356. finishCompute( computeGroup ) {
  56357. const groupData = this.get( computeGroup );
  56358. groupData.passEncoderGPU.end();
  56359. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  56360. }
  56361. // render object
  56362. /**
  56363. * Executes a draw command for the given render object.
  56364. *
  56365. * @param {RenderObject} renderObject - The render object to draw.
  56366. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  56367. */
  56368. draw( renderObject, info ) {
  56369. const { object, material, context, pipeline } = renderObject;
  56370. const bindings = renderObject.getBindings();
  56371. const renderContextData = this.get( context );
  56372. const pipelineData = this.get( pipeline );
  56373. const pipelineGPU = pipelineData.pipeline;
  56374. if ( pipelineData.error === true ) return;
  56375. const index = renderObject.getIndex();
  56376. const hasIndex = ( index !== null );
  56377. const drawParams = renderObject.getDrawParameters();
  56378. if ( drawParams === null ) return;
  56379. // pipeline
  56380. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  56381. // pipeline
  56382. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  56383. currentSets.pipeline = pipelineGPU;
  56384. // bind groups
  56385. const currentBindingGroups = currentSets.bindingGroups;
  56386. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  56387. const bindGroup = bindings[ i ];
  56388. const bindingsData = this.get( bindGroup );
  56389. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  56390. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  56391. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  56392. }
  56393. }
  56394. // attributes
  56395. // index
  56396. if ( hasIndex === true ) {
  56397. if ( currentSets.index !== index ) {
  56398. const buffer = this.get( index ).buffer;
  56399. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  56400. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  56401. currentSets.index = index;
  56402. }
  56403. }
  56404. // vertex buffers
  56405. const vertexBuffers = renderObject.getVertexBuffers();
  56406. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  56407. const vertexBuffer = vertexBuffers[ i ];
  56408. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  56409. const buffer = this.get( vertexBuffer ).buffer;
  56410. passEncoderGPU.setVertexBuffer( i, buffer );
  56411. currentSets.attributes[ i ] = vertexBuffer;
  56412. }
  56413. }
  56414. // stencil
  56415. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  56416. passEncoderGPU.setStencilReference( material.stencilRef );
  56417. renderContextData.currentStencilRef = material.stencilRef;
  56418. }
  56419. };
  56420. // Define draw function
  56421. const draw = ( passEncoderGPU, currentSets ) => {
  56422. setPipelineAndBindings( passEncoderGPU, currentSets );
  56423. if ( object.isBatchedMesh === true ) {
  56424. const starts = object._multiDrawStarts;
  56425. const counts = object._multiDrawCounts;
  56426. const drawCount = object._multiDrawCount;
  56427. const drawInstances = object._multiDrawInstances;
  56428. if ( drawInstances !== null ) {
  56429. // @deprecated, r174
  56430. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  56431. }
  56432. let bytesPerElement = ( hasIndex === true ) ? index.array.BYTES_PER_ELEMENT : 1;
  56433. if ( material.wireframe ) {
  56434. bytesPerElement = object.geometry.attributes.position.count > 65535 ? 4 : 2;
  56435. }
  56436. for ( let i = 0; i < drawCount; i ++ ) {
  56437. const count = drawInstances ? drawInstances[ i ] : 1;
  56438. const firstInstance = count > 1 ? 0 : i;
  56439. if ( hasIndex === true ) {
  56440. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  56441. } else {
  56442. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  56443. }
  56444. info.update( object, counts[ i ], count );
  56445. }
  56446. } else if ( hasIndex === true ) {
  56447. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  56448. const indirect = renderObject.getIndirect();
  56449. if ( indirect !== null ) {
  56450. const buffer = this.get( indirect ).buffer;
  56451. const indirectOffset = renderObject.getIndirectOffset();
  56452. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  56453. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  56454. passEncoderGPU.drawIndexedIndirect( buffer, indirectOffsets[ i ] );
  56455. }
  56456. } else {
  56457. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  56458. }
  56459. info.update( object, indexCount, instanceCount );
  56460. } else {
  56461. const { vertexCount, instanceCount, firstVertex } = drawParams;
  56462. const indirect = renderObject.getIndirect();
  56463. if ( indirect !== null ) {
  56464. const buffer = this.get( indirect ).buffer;
  56465. const indirectOffset = renderObject.getIndirectOffset();
  56466. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  56467. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  56468. passEncoderGPU.drawIndirect( buffer, indirectOffsets[ i ] );
  56469. }
  56470. } else {
  56471. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  56472. }
  56473. info.update( object, vertexCount, instanceCount );
  56474. }
  56475. };
  56476. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  56477. const cameraData = this.get( renderObject.camera );
  56478. const cameras = renderObject.camera.cameras;
  56479. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  56480. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  56481. const bindingsData = this.get( cameraIndex );
  56482. const indexesGPU = [];
  56483. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  56484. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  56485. data[ 0 ] = i;
  56486. const { layoutGPU } = bindingsData.layout;
  56487. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, layoutGPU );
  56488. indexesGPU.push( bindGroupIndex );
  56489. }
  56490. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  56491. }
  56492. const pixelRatio = this.renderer.getPixelRatio();
  56493. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  56494. const subCamera = cameras[ i ];
  56495. if ( object.layers.test( subCamera.layers ) ) {
  56496. const vp = subCamera.viewport;
  56497. let pass = renderContextData.currentPass;
  56498. let sets = renderContextData.currentSets;
  56499. if ( renderContextData.bundleEncoders ) {
  56500. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  56501. const bundleSets = renderContextData.bundleSets[ i ];
  56502. pass = bundleEncoder;
  56503. sets = bundleSets;
  56504. }
  56505. if ( vp ) {
  56506. pass.setViewport(
  56507. Math.floor( vp.x * pixelRatio ),
  56508. Math.floor( vp.y * pixelRatio ),
  56509. Math.floor( vp.width * pixelRatio ),
  56510. Math.floor( vp.height * pixelRatio ),
  56511. context.viewportValue.minDepth,
  56512. context.viewportValue.maxDepth
  56513. );
  56514. }
  56515. // Set camera index binding for this layer
  56516. if ( cameraIndex && cameraData.indexesGPU ) {
  56517. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  56518. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  56519. }
  56520. draw( pass, sets );
  56521. }
  56522. }
  56523. } else {
  56524. // Regular single camera rendering
  56525. if ( renderContextData.currentPass ) {
  56526. // Handle occlusion queries
  56527. if ( renderContextData.occlusionQuerySet !== undefined ) {
  56528. const lastObject = renderContextData.lastOcclusionObject;
  56529. if ( lastObject !== object ) {
  56530. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  56531. renderContextData.currentPass.endOcclusionQuery();
  56532. renderContextData.occlusionQueryIndex ++;
  56533. }
  56534. if ( object.occlusionTest === true ) {
  56535. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  56536. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  56537. }
  56538. renderContextData.lastOcclusionObject = object;
  56539. }
  56540. }
  56541. draw( renderContextData.currentPass, renderContextData.currentSets );
  56542. }
  56543. }
  56544. }
  56545. // cache key
  56546. /**
  56547. * Returns `true` if the render pipeline requires an update.
  56548. *
  56549. * @param {RenderObject} renderObject - The render object.
  56550. * @return {boolean} Whether the render pipeline requires an update or not.
  56551. */
  56552. needsRenderUpdate( renderObject ) {
  56553. const data = this.get( renderObject );
  56554. const { object, material } = renderObject;
  56555. const utils = this.utils;
  56556. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  56557. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  56558. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  56559. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  56560. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  56561. let needsUpdate = false;
  56562. if ( data.material !== material || data.materialVersion !== material.version ||
  56563. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  56564. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  56565. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  56566. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  56567. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  56568. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  56569. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  56570. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  56571. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  56572. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  56573. data.primitiveTopology !== primitiveTopology ||
  56574. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  56575. ) {
  56576. data.material = material; data.materialVersion = material.version;
  56577. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  56578. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  56579. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  56580. data.colorWrite = material.colorWrite;
  56581. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  56582. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  56583. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  56584. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  56585. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  56586. data.sampleCount = sampleCount;
  56587. data.colorSpace = colorSpace;
  56588. data.colorFormat = colorFormat;
  56589. data.depthStencilFormat = depthStencilFormat;
  56590. data.primitiveTopology = primitiveTopology;
  56591. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  56592. needsUpdate = true;
  56593. }
  56594. return needsUpdate;
  56595. }
  56596. /**
  56597. * Returns a cache key that is used to identify render pipelines.
  56598. *
  56599. * @param {RenderObject} renderObject - The render object.
  56600. * @return {string} The cache key.
  56601. */
  56602. getRenderCacheKey( renderObject ) {
  56603. const { object, material } = renderObject;
  56604. const utils = this.utils;
  56605. const renderContext = renderObject.context;
  56606. // meshes with negative scale have a different frontFace render pipeline
  56607. // descriptor value so the following must be honored in the cache key
  56608. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  56609. return [
  56610. material.transparent, material.blending, material.premultipliedAlpha,
  56611. material.blendSrc, material.blendDst, material.blendEquation,
  56612. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  56613. material.colorWrite,
  56614. material.depthWrite, material.depthTest, material.depthFunc,
  56615. material.stencilWrite, material.stencilFunc,
  56616. material.stencilFail, material.stencilZFail, material.stencilZPass,
  56617. material.stencilFuncMask, material.stencilWriteMask,
  56618. material.side,
  56619. frontFaceCW,
  56620. utils.getSampleCountRenderContext( renderContext ),
  56621. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  56622. utils.getPrimitiveTopology( object, material ),
  56623. renderObject.getGeometryCacheKey(),
  56624. renderObject.clippingContextCacheKey
  56625. ].join();
  56626. }
  56627. // textures
  56628. /**
  56629. * Updates a GPU sampler for the given texture.
  56630. *
  56631. * @param {Texture} texture - The texture to update the sampler for.
  56632. * @return {string} The current sampler key.
  56633. */
  56634. updateSampler( texture ) {
  56635. return this.textureUtils.updateSampler( texture );
  56636. }
  56637. /**
  56638. * Creates a default texture for the given texture that can be used
  56639. * as a placeholder until the actual texture is ready for usage.
  56640. *
  56641. * @param {Texture} texture - The texture to create a default texture for.
  56642. * @return {boolean} Whether the sampler has been updated or not.
  56643. */
  56644. createDefaultTexture( texture ) {
  56645. return this.textureUtils.createDefaultTexture( texture );
  56646. }
  56647. /**
  56648. * Defines a texture on the GPU for the given texture object.
  56649. *
  56650. * @param {Texture} texture - The texture.
  56651. * @param {Object} [options={}] - Optional configuration parameter.
  56652. */
  56653. createTexture( texture, options ) {
  56654. this.textureUtils.createTexture( texture, options );
  56655. }
  56656. /**
  56657. * Uploads the updated texture data to the GPU.
  56658. *
  56659. * @param {Texture} texture - The texture.
  56660. * @param {Object} [options={}] - Optional configuration parameter.
  56661. */
  56662. updateTexture( texture, options ) {
  56663. this.textureUtils.updateTexture( texture, options );
  56664. }
  56665. /**
  56666. * Generates mipmaps for the given texture.
  56667. *
  56668. * @param {Texture} texture - The texture.
  56669. */
  56670. generateMipmaps( texture ) {
  56671. this.textureUtils.generateMipmaps( texture );
  56672. }
  56673. /**
  56674. * Destroys the GPU data for the given texture object.
  56675. *
  56676. * @param {Texture} texture - The texture.
  56677. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  56678. */
  56679. destroyTexture( texture, isDefaultTexture = false ) {
  56680. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  56681. }
  56682. /**
  56683. * Returns texture data as a typed array.
  56684. *
  56685. * @async
  56686. * @param {Texture} texture - The texture to copy.
  56687. * @param {number} x - The x coordinate of the copy origin.
  56688. * @param {number} y - The y coordinate of the copy origin.
  56689. * @param {number} width - The width of the copy.
  56690. * @param {number} height - The height of the copy.
  56691. * @param {number} faceIndex - The face index.
  56692. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  56693. */
  56694. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  56695. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  56696. }
  56697. /**
  56698. * Inits a time stamp query for the given render context.
  56699. *
  56700. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  56701. * @param {number} uid - Unique id for the context (e.g. render context id).
  56702. * @param {Object} descriptor - The query descriptor.
  56703. */
  56704. initTimestampQuery( type, uid, descriptor ) {
  56705. if ( ! this.trackTimestamp ) return;
  56706. if ( ! this.timestampQueryPool[ type ] ) {
  56707. // TODO: Variable maxQueries?
  56708. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  56709. }
  56710. const timestampQueryPool = this.timestampQueryPool[ type ];
  56711. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  56712. descriptor.timestampWrites = {
  56713. querySet: timestampQueryPool.querySet,
  56714. beginningOfPassWriteIndex: baseOffset,
  56715. endOfPassWriteIndex: baseOffset + 1,
  56716. };
  56717. }
  56718. // node builder
  56719. /**
  56720. * Returns a node builder for the given render object.
  56721. *
  56722. * @param {RenderObject} object - The render object.
  56723. * @param {Renderer} renderer - The renderer.
  56724. * @return {WGSLNodeBuilder} The node builder.
  56725. */
  56726. createNodeBuilder( object, renderer ) {
  56727. return new WGSLNodeBuilder( object, renderer );
  56728. }
  56729. // program
  56730. /**
  56731. * Creates a shader program from the given programmable stage.
  56732. *
  56733. * @param {ProgrammableStage} program - The programmable stage.
  56734. */
  56735. createProgram( program ) {
  56736. const programGPU = this.get( program );
  56737. programGPU.module = {
  56738. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  56739. entryPoint: 'main'
  56740. };
  56741. }
  56742. /**
  56743. * Destroys the shader program of the given programmable stage.
  56744. *
  56745. * @param {ProgrammableStage} program - The programmable stage.
  56746. */
  56747. destroyProgram( program ) {
  56748. this.delete( program );
  56749. }
  56750. // pipelines
  56751. /**
  56752. * Creates a render pipeline for the given render object.
  56753. *
  56754. * @param {RenderObject} renderObject - The render object.
  56755. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  56756. */
  56757. createRenderPipeline( renderObject, promises ) {
  56758. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  56759. }
  56760. /**
  56761. * Creates a compute pipeline for the given compute node.
  56762. *
  56763. * @param {ComputePipeline} computePipeline - The compute pipeline.
  56764. * @param {Array<BindGroup>} bindings - The bindings.
  56765. */
  56766. createComputePipeline( computePipeline, bindings ) {
  56767. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  56768. }
  56769. /**
  56770. * Prepares the state for encoding render bundles.
  56771. *
  56772. * @param {RenderContext} renderContext - The render context.
  56773. */
  56774. beginBundle( renderContext ) {
  56775. const renderContextData = this.get( renderContext );
  56776. renderContextData._currentPass = renderContextData.currentPass;
  56777. renderContextData._currentSets = renderContextData.currentSets;
  56778. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56779. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  56780. }
  56781. /**
  56782. * After processing render bundles this method finalizes related work.
  56783. *
  56784. * @param {RenderContext} renderContext - The render context.
  56785. * @param {RenderBundle} bundle - The render bundle.
  56786. */
  56787. finishBundle( renderContext, bundle ) {
  56788. const renderContextData = this.get( renderContext );
  56789. const bundleEncoder = renderContextData.currentPass;
  56790. const bundleGPU = bundleEncoder.finish();
  56791. this.get( bundle ).bundleGPU = bundleGPU;
  56792. // restore render pass state
  56793. renderContextData.currentSets = renderContextData._currentSets;
  56794. renderContextData.currentPass = renderContextData._currentPass;
  56795. }
  56796. /**
  56797. * Adds a render bundle to the render context data.
  56798. *
  56799. * @param {RenderContext} renderContext - The render context.
  56800. * @param {RenderBundle} bundle - The render bundle to add.
  56801. */
  56802. addBundle( renderContext, bundle ) {
  56803. const renderContextData = this.get( renderContext );
  56804. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  56805. }
  56806. // bindings
  56807. /**
  56808. * Creates bindings from the given bind group definition.
  56809. *
  56810. * @param {BindGroup} bindGroup - The bind group.
  56811. * @param {Array<BindGroup>} bindings - Array of bind groups.
  56812. * @param {number} cacheIndex - The cache index.
  56813. * @param {number} version - The version.
  56814. */
  56815. createBindings( bindGroup, bindings, cacheIndex, version ) {
  56816. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  56817. }
  56818. /**
  56819. * Updates the given bind group definition.
  56820. *
  56821. * @param {BindGroup} bindGroup - The bind group.
  56822. * @param {Array<BindGroup>} bindings - Array of bind groups.
  56823. * @param {number} cacheIndex - The cache index.
  56824. * @param {number} version - The version.
  56825. */
  56826. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  56827. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  56828. }
  56829. /**
  56830. * Updates a buffer binding.
  56831. *
  56832. * @param {Buffer} binding - The buffer binding to update.
  56833. */
  56834. updateBinding( binding ) {
  56835. this.bindingUtils.updateBinding( binding );
  56836. }
  56837. /**
  56838. * Delete data associated with the current bind group.
  56839. *
  56840. * @param {BindGroup} bindGroup - The bind group.
  56841. */
  56842. deleteBindGroupData( bindGroup ) {
  56843. this.bindingUtils.deleteBindGroupData( bindGroup );
  56844. }
  56845. // attributes
  56846. /**
  56847. * Creates the buffer of an indexed shader attribute.
  56848. *
  56849. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  56850. */
  56851. createIndexAttribute( attribute ) {
  56852. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  56853. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  56854. usage |= GPUBufferUsage.STORAGE;
  56855. }
  56856. this.attributeUtils.createAttribute( attribute, usage );
  56857. }
  56858. /**
  56859. * Creates the GPU buffer of a shader attribute.
  56860. *
  56861. * @param {BufferAttribute} attribute - The buffer attribute.
  56862. */
  56863. createAttribute( attribute ) {
  56864. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56865. }
  56866. /**
  56867. * Creates the GPU buffer of a storage attribute.
  56868. *
  56869. * @param {BufferAttribute} attribute - The buffer attribute.
  56870. */
  56871. createStorageAttribute( attribute ) {
  56872. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56873. }
  56874. /**
  56875. * Creates the GPU buffer of an indirect storage attribute.
  56876. *
  56877. * @param {BufferAttribute} attribute - The buffer attribute.
  56878. */
  56879. createIndirectStorageAttribute( attribute ) {
  56880. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56881. }
  56882. /**
  56883. * Updates the GPU buffer of a shader attribute.
  56884. *
  56885. * @param {BufferAttribute} attribute - The buffer attribute to update.
  56886. */
  56887. updateAttribute( attribute ) {
  56888. this.attributeUtils.updateAttribute( attribute );
  56889. }
  56890. /**
  56891. * Destroys the GPU buffer of a shader attribute.
  56892. *
  56893. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  56894. */
  56895. destroyAttribute( attribute ) {
  56896. this.attributeUtils.destroyAttribute( attribute );
  56897. }
  56898. // canvas
  56899. /**
  56900. * Triggers an update of the default render pass descriptor.
  56901. */
  56902. updateSize() {
  56903. this.delete( this.renderer.getCanvasTarget() );
  56904. }
  56905. // utils public
  56906. /**
  56907. * Returns the maximum anisotropy texture filtering value.
  56908. *
  56909. * @return {number} The maximum anisotropy texture filtering value.
  56910. */
  56911. getMaxAnisotropy() {
  56912. return 16;
  56913. }
  56914. /**
  56915. * Checks if the given feature is supported by the backend.
  56916. *
  56917. * @param {string} name - The feature's name.
  56918. * @return {boolean} Whether the feature is supported or not.
  56919. */
  56920. hasFeature( name ) {
  56921. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  56922. return this.device.features.has( name );
  56923. }
  56924. /**
  56925. * Copies data of the given source texture to the given destination texture.
  56926. *
  56927. * @param {Texture} srcTexture - The source texture.
  56928. * @param {Texture} dstTexture - The destination texture.
  56929. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  56930. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  56931. * @param {number} [srcLevel=0] - The mipmap level to copy.
  56932. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  56933. */
  56934. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  56935. let dstX = 0;
  56936. let dstY = 0;
  56937. let dstZ = 0;
  56938. let srcX = 0;
  56939. let srcY = 0;
  56940. let srcZ = 0;
  56941. let srcWidth = srcTexture.image.width;
  56942. let srcHeight = srcTexture.image.height;
  56943. let srcDepth = 1;
  56944. if ( srcRegion !== null ) {
  56945. if ( srcRegion.isBox3 === true ) {
  56946. srcX = srcRegion.min.x;
  56947. srcY = srcRegion.min.y;
  56948. srcZ = srcRegion.min.z;
  56949. srcWidth = srcRegion.max.x - srcRegion.min.x;
  56950. srcHeight = srcRegion.max.y - srcRegion.min.y;
  56951. srcDepth = srcRegion.max.z - srcRegion.min.z;
  56952. } else {
  56953. // Assume it's a Box2
  56954. srcX = srcRegion.min.x;
  56955. srcY = srcRegion.min.y;
  56956. srcWidth = srcRegion.max.x - srcRegion.min.x;
  56957. srcHeight = srcRegion.max.y - srcRegion.min.y;
  56958. srcDepth = 1;
  56959. }
  56960. }
  56961. if ( dstPosition !== null ) {
  56962. dstX = dstPosition.x;
  56963. dstY = dstPosition.y;
  56964. dstZ = dstPosition.z || 0;
  56965. }
  56966. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  56967. const sourceGPU = this.get( srcTexture ).texture;
  56968. const destinationGPU = this.get( dstTexture ).texture;
  56969. encoder.copyTextureToTexture(
  56970. {
  56971. texture: sourceGPU,
  56972. mipLevel: srcLevel,
  56973. origin: { x: srcX, y: srcY, z: srcZ }
  56974. },
  56975. {
  56976. texture: destinationGPU,
  56977. mipLevel: dstLevel,
  56978. origin: { x: dstX, y: dstY, z: dstZ }
  56979. },
  56980. [
  56981. srcWidth,
  56982. srcHeight,
  56983. srcDepth
  56984. ]
  56985. );
  56986. this.device.queue.submit( [ encoder.finish() ] );
  56987. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  56988. this.textureUtils.generateMipmaps( dstTexture );
  56989. }
  56990. }
  56991. /**
  56992. * Copies the current bound framebuffer to the given texture.
  56993. *
  56994. * @param {Texture} texture - The destination texture.
  56995. * @param {RenderContext} renderContext - The render context.
  56996. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  56997. */
  56998. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  56999. const renderContextData = this.get( renderContext );
  57000. let sourceGPU = null;
  57001. if ( renderContext.renderTarget ) {
  57002. if ( texture.isDepthTexture ) {
  57003. sourceGPU = this.get( renderContext.depthTexture ).texture;
  57004. } else {
  57005. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  57006. }
  57007. } else {
  57008. if ( texture.isDepthTexture ) {
  57009. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  57010. } else {
  57011. sourceGPU = this.context.getCurrentTexture();
  57012. }
  57013. }
  57014. const destinationGPU = this.get( texture ).texture;
  57015. if ( sourceGPU.format !== destinationGPU.format ) {
  57016. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  57017. return;
  57018. }
  57019. let encoder;
  57020. if ( renderContextData.currentPass ) {
  57021. renderContextData.currentPass.end();
  57022. encoder = renderContextData.encoder;
  57023. } else {
  57024. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  57025. }
  57026. encoder.copyTextureToTexture(
  57027. {
  57028. texture: sourceGPU,
  57029. origin: [ rectangle.x, rectangle.y, 0 ],
  57030. },
  57031. {
  57032. texture: destinationGPU
  57033. },
  57034. [
  57035. rectangle.z,
  57036. rectangle.w
  57037. ]
  57038. );
  57039. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  57040. // might be out-of-sync, see #31768
  57041. if ( texture.generateMipmaps ) {
  57042. this.textureUtils.generateMipmaps( texture, encoder );
  57043. }
  57044. if ( renderContextData.currentPass ) {
  57045. const { descriptor } = renderContextData;
  57046. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  57047. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  57048. }
  57049. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  57050. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  57051. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  57052. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  57053. if ( renderContext.viewport ) {
  57054. this.updateViewport( renderContext );
  57055. }
  57056. if ( renderContext.scissor ) {
  57057. this.updateScissor( renderContext );
  57058. }
  57059. } else {
  57060. this.device.queue.submit( [ encoder.finish() ] );
  57061. }
  57062. }
  57063. /**
  57064. * Checks if the given compatibility is supported by the backend.
  57065. *
  57066. * @param {string} name - The compatibility name.
  57067. * @return {boolean} Whether the compatibility is supported or not.
  57068. */
  57069. hasCompatibility( name ) {
  57070. if ( this._compatibility[ Compatibility.TEXTURE_COMPARE ] !== undefined ) {
  57071. return this._compatibility[ Compatibility.TEXTURE_COMPARE ];
  57072. }
  57073. return super.hasCompatibility( name );
  57074. }
  57075. dispose() {
  57076. this.bindingUtils.dispose();
  57077. this.textureUtils.dispose();
  57078. if ( this.occludedResolveCache ) {
  57079. for ( const buffer of this.occludedResolveCache.values() ) {
  57080. buffer.destroy();
  57081. }
  57082. this.occludedResolveCache.clear();
  57083. }
  57084. if ( this.timestampQueryPool ) {
  57085. for ( const queryPool of Object.values( this.timestampQueryPool ) ) {
  57086. if ( queryPool !== null ) queryPool.dispose();
  57087. }
  57088. }
  57089. if ( this.parameters.device === undefined && this.device !== null ) {
  57090. this.device.destroy();
  57091. }
  57092. }
  57093. }
  57094. /**
  57095. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  57096. *
  57097. * @augments SpotLight
  57098. */
  57099. class IESSpotLight extends SpotLight {
  57100. /**
  57101. * Constructs a new IES spot light.
  57102. *
  57103. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  57104. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  57105. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  57106. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  57107. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  57108. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  57109. */
  57110. constructor( color, intensity, distance, angle, penumbra, decay ) {
  57111. super( color, intensity, distance, angle, penumbra, decay );
  57112. /**
  57113. * The IES map. It's a lookup table that stores normalized attenuation factors
  57114. * (0.0 to 1.0) that represent the light's intensity at a specific angle.
  57115. *
  57116. * @type {?Texture}
  57117. * @default null
  57118. */
  57119. this.iesMap = null;
  57120. }
  57121. copy( source, recursive ) {
  57122. super.copy( source, recursive );
  57123. this.iesMap = source.iesMap;
  57124. return this;
  57125. }
  57126. }
  57127. /**
  57128. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  57129. *
  57130. * @augments SpotLight
  57131. */
  57132. class ProjectorLight extends SpotLight {
  57133. /**
  57134. * Constructs a new projector light.
  57135. *
  57136. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  57137. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  57138. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  57139. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  57140. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  57141. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  57142. */
  57143. constructor( color, intensity, distance, angle, penumbra, decay ) {
  57144. super( color, intensity, distance, angle, penumbra, decay );
  57145. /**
  57146. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  57147. *
  57148. * @type {?number}
  57149. * @default null
  57150. */
  57151. this.aspect = null;
  57152. }
  57153. copy( source, recursive ) {
  57154. super.copy( source, recursive );
  57155. this.aspect = source.aspect;
  57156. return this;
  57157. }
  57158. }
  57159. /**
  57160. * This version of a node library represents a basic version
  57161. * just focusing on lights and tone mapping techniques.
  57162. *
  57163. * @private
  57164. * @augments NodeLibrary
  57165. */
  57166. class BasicNodeLibrary extends NodeLibrary {
  57167. /**
  57168. * Constructs a new basic node library.
  57169. */
  57170. constructor() {
  57171. super();
  57172. this.addLight( PointLightNode, PointLight );
  57173. this.addLight( DirectionalLightNode, DirectionalLight );
  57174. this.addLight( RectAreaLightNode, RectAreaLight );
  57175. this.addLight( SpotLightNode, SpotLight );
  57176. this.addLight( AmbientLightNode, AmbientLight );
  57177. this.addLight( HemisphereLightNode, HemisphereLight );
  57178. this.addLight( LightProbeNode, LightProbe );
  57179. this.addLight( IESSpotLightNode, IESSpotLight );
  57180. this.addLight( ProjectorLightNode, ProjectorLight );
  57181. this.addToneMapping( linearToneMapping, LinearToneMapping );
  57182. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  57183. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  57184. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  57185. this.addToneMapping( agxToneMapping, AgXToneMapping );
  57186. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  57187. }
  57188. }
  57189. /**
  57190. * This alternative version of {@link WebGPURenderer} only supports node materials.
  57191. * So classes like `MeshBasicMaterial` are not compatible.
  57192. *
  57193. * @private
  57194. * @augments Renderer
  57195. */
  57196. class WebGPURenderer extends Renderer {
  57197. /**
  57198. * Constructs a new WebGPU renderer.
  57199. *
  57200. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  57201. */
  57202. constructor( parameters = {} ) {
  57203. let BackendClass;
  57204. if ( parameters.forceWebGL ) {
  57205. BackendClass = WebGLBackend;
  57206. } else {
  57207. BackendClass = WebGPUBackend;
  57208. parameters.getFallback = () => {
  57209. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  57210. return new WebGLBackend( parameters );
  57211. };
  57212. }
  57213. const backend = new BackendClass( parameters );
  57214. super( backend, parameters );
  57215. /**
  57216. * The generic default value is overwritten with the
  57217. * standard node library for type mapping. Material
  57218. * mapping is not supported with this version.
  57219. *
  57220. * @type {BasicNodeLibrary}
  57221. */
  57222. this.library = new BasicNodeLibrary();
  57223. /**
  57224. * This flag can be used for type testing.
  57225. *
  57226. * @type {boolean}
  57227. * @readonly
  57228. * @default true
  57229. */
  57230. this.isWebGPURenderer = true;
  57231. }
  57232. }
  57233. /**
  57234. * A specialized group which enables applications access to the
  57235. * Render Bundle API of WebGPU. The group with all its descendant nodes
  57236. * are considered as one render bundle and processed as such by
  57237. * the renderer.
  57238. *
  57239. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  57240. * With a WebGL backend, the group can technically be rendered but without
  57241. * any performance improvements.
  57242. *
  57243. * @augments Group
  57244. */
  57245. class BundleGroup extends Group {
  57246. /**
  57247. * Constructs a new bundle group.
  57248. */
  57249. constructor() {
  57250. super();
  57251. /**
  57252. * This flag can be used for type testing.
  57253. *
  57254. * @type {boolean}
  57255. * @readonly
  57256. * @default true
  57257. */
  57258. this.isBundleGroup = true;
  57259. /**
  57260. * This property is only relevant for detecting types
  57261. * during serialization/deserialization. It should always
  57262. * match the class name.
  57263. *
  57264. * @type {string}
  57265. * @readonly
  57266. * @default 'BundleGroup'
  57267. */
  57268. this.type = 'BundleGroup';
  57269. /**
  57270. * Whether the bundle is static or not. When set to `true`, the structure
  57271. * is assumed to be static and does not change. E.g. no new objects are
  57272. * added to the group.
  57273. *
  57274. * If a change is required, an update can still be forced by setting the
  57275. * `needsUpdate` flag to `true`.
  57276. *
  57277. * @type {boolean}
  57278. * @default true
  57279. */
  57280. this.static = true;
  57281. /**
  57282. * The bundle group's version.
  57283. *
  57284. * @type {number}
  57285. * @readonly
  57286. * @default 0
  57287. */
  57288. this.version = 0;
  57289. }
  57290. /**
  57291. * Set this property to `true` when the bundle group has changed.
  57292. *
  57293. * @type {boolean}
  57294. * @default false
  57295. * @param {boolean} value
  57296. */
  57297. set needsUpdate( value ) {
  57298. if ( value === true ) this.version ++;
  57299. }
  57300. }
  57301. /**
  57302. * This module is responsible to manage the rendering pipeline setups in apps.
  57303. * You usually create a single instance of this class and use it to define
  57304. * the output of your render pipeline and post processing effect chain.
  57305. * ```js
  57306. * const renderPipeline = new RenderPipeline( renderer );
  57307. *
  57308. * const scenePass = pass( scene, camera );
  57309. *
  57310. * renderPipeline.outputNode = scenePass;
  57311. * ```
  57312. *
  57313. * Note: This module can only be used with `WebGPURenderer`.
  57314. */
  57315. class RenderPipeline {
  57316. /**
  57317. * Constructs a new render pipeline management module.
  57318. *
  57319. * @param {Renderer} renderer - A reference to the renderer.
  57320. * @param {Node<vec4>} outputNode - An optional output node.
  57321. */
  57322. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  57323. /**
  57324. * A reference to the renderer.
  57325. *
  57326. * @type {Renderer}
  57327. */
  57328. this.renderer = renderer;
  57329. /**
  57330. * A node which defines the final output of the rendering
  57331. * pipeline. This is usually the last node in a chain
  57332. * of effect nodes.
  57333. *
  57334. * @type {Node<vec4>}
  57335. */
  57336. this.outputNode = outputNode;
  57337. /**
  57338. * Whether the default output tone mapping and color
  57339. * space transformation should be enabled or not.
  57340. *
  57341. * It is enabled by default by it must be disabled when
  57342. * effects must be executed after tone mapping and color
  57343. * space conversion. A typical example is FXAA which
  57344. * requires sRGB input.
  57345. *
  57346. * When set to `false`, the app must control the output
  57347. * transformation with `RenderOutputNode`.
  57348. *
  57349. * ```js
  57350. * const outputPass = renderOutput( scenePass );
  57351. * ```
  57352. *
  57353. * @type {boolean}
  57354. */
  57355. this.outputColorTransform = true;
  57356. /**
  57357. * Must be set to `true` when the output node changes.
  57358. *
  57359. * @type {Node<vec4>}
  57360. */
  57361. this.needsUpdate = true;
  57362. const material = new NodeMaterial();
  57363. material.name = 'RenderPipeline';
  57364. /**
  57365. * The full screen quad that is used to render
  57366. * the effects.
  57367. *
  57368. * @private
  57369. * @type {QuadMesh}
  57370. */
  57371. this._quadMesh = new QuadMesh( material );
  57372. this._quadMesh.name = 'Render Pipeline';
  57373. /**
  57374. * The context of the render pipeline stack.
  57375. *
  57376. * @private
  57377. * @type {?Object}
  57378. * @default null
  57379. */
  57380. this._context = null;
  57381. }
  57382. /**
  57383. * When `RenderPipeline` is used to apply rendering pipeline and post processing effects,
  57384. * the application must use this version of `render()` inside
  57385. * its animation loop (not the one from the renderer).
  57386. */
  57387. render() {
  57388. const renderer = this.renderer;
  57389. this._update();
  57390. if ( this._context.onBeforeRenderPipeline !== null ) this._context.onBeforeRenderPipeline();
  57391. const toneMapping = renderer.toneMapping;
  57392. const outputColorSpace = renderer.outputColorSpace;
  57393. renderer.toneMapping = NoToneMapping;
  57394. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  57395. //
  57396. const currentXR = renderer.xr.enabled;
  57397. renderer.xr.enabled = false;
  57398. this._quadMesh.render( renderer );
  57399. renderer.xr.enabled = currentXR;
  57400. //
  57401. renderer.toneMapping = toneMapping;
  57402. renderer.outputColorSpace = outputColorSpace;
  57403. if ( this._context.onAfterRenderPipeline !== null ) this._context.onAfterRenderPipeline();
  57404. }
  57405. /**
  57406. * Returns the current context of the render pipeline stack.
  57407. *
  57408. * @readonly
  57409. * @type {?Object}
  57410. */
  57411. get context() {
  57412. return this._context;
  57413. }
  57414. /**
  57415. * Frees internal resources.
  57416. */
  57417. dispose() {
  57418. this._quadMesh.material.dispose();
  57419. }
  57420. /**
  57421. * Updates the state of the module.
  57422. *
  57423. * @private
  57424. */
  57425. _update() {
  57426. if ( this.needsUpdate === true ) {
  57427. const renderer = this.renderer;
  57428. const toneMapping = renderer.toneMapping;
  57429. const outputColorSpace = renderer.outputColorSpace;
  57430. const context = {
  57431. renderPipeline: this,
  57432. onBeforeRenderPipeline: null,
  57433. onAfterRenderPipeline: null
  57434. };
  57435. let outputNode = this.outputNode;
  57436. if ( this.outputColorTransform === true ) {
  57437. outputNode = outputNode.context( context );
  57438. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  57439. } else {
  57440. context.toneMapping = toneMapping;
  57441. context.outputColorSpace = outputColorSpace;
  57442. outputNode = outputNode.context( context );
  57443. }
  57444. this._context = context;
  57445. this._quadMesh.material.fragmentNode = outputNode;
  57446. this._quadMesh.material.needsUpdate = true;
  57447. this.needsUpdate = false;
  57448. }
  57449. }
  57450. /**
  57451. * When `RenderPipeline` is used to apply rendering pipeline and post processing effects,
  57452. * the application must use this version of `renderAsync()` inside
  57453. * its animation loop (not the one from the renderer).
  57454. *
  57455. * @async
  57456. * @deprecated
  57457. * @return {Promise} A Promise that resolves when the render has been finished.
  57458. */
  57459. async renderAsync() {
  57460. warnOnce( 'RenderPipeline: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  57461. await this.renderer.init();
  57462. this.render();
  57463. }
  57464. }
  57465. /**
  57466. * @deprecated since r183. Use {@link RenderPipeline} instead. PostProcessing has been renamed to RenderPipeline.
  57467. *
  57468. * This class is a wrapper for backward compatibility and will be removed in a future version.
  57469. */
  57470. class PostProcessing extends RenderPipeline {
  57471. /**
  57472. * Constructs a new post processing management module.
  57473. *
  57474. * @param {Renderer} renderer - A reference to the renderer.
  57475. * @param {Node<vec4>} outputNode - An optional output node.
  57476. * @deprecated since r183. Use {@link RenderPipeline} instead.
  57477. */
  57478. constructor( renderer, outputNode ) {
  57479. warnOnce( 'PostProcessing: "PostProcessing" has been renamed to "RenderPipeline". Please update your code to use "THREE.RenderPipeline" instead.' ); // @deprecated, r183
  57480. super( renderer, outputNode );
  57481. }
  57482. }
  57483. /**
  57484. * This special type of texture is intended for compute shaders.
  57485. * It can be used to compute the data of a texture with a compute shader.
  57486. *
  57487. * Note: This type of texture can only be used with `WebGPURenderer`
  57488. * and a WebGPU backend.
  57489. *
  57490. * @augments Texture
  57491. */
  57492. class StorageTexture extends Texture {
  57493. /**
  57494. * Constructs a new storage texture.
  57495. *
  57496. * @param {number} [width=1] - The storage texture's width.
  57497. * @param {number} [height=1] - The storage texture's height.
  57498. */
  57499. constructor( width = 1, height = 1 ) {
  57500. super();
  57501. /**
  57502. * The image object which just represents the texture's dimension.
  57503. *
  57504. * @type {{width: number, height: number}}
  57505. */
  57506. this.image = { width, height };
  57507. /**
  57508. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  57509. *
  57510. * @type {number}
  57511. */
  57512. this.magFilter = LinearFilter;
  57513. /**
  57514. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  57515. *
  57516. * @type {number}
  57517. */
  57518. this.minFilter = LinearFilter;
  57519. /**
  57520. * This flag can be used for type testing.
  57521. *
  57522. * @type {boolean}
  57523. * @readonly
  57524. * @default true
  57525. */
  57526. this.isStorageTexture = true;
  57527. /**
  57528. * When `true`, mipmaps will be auto-generated after compute writes.
  57529. * When `false`, mipmaps must be written manually via compute shaders.
  57530. *
  57531. * @type {boolean}
  57532. * @default true
  57533. */
  57534. this.mipmapsAutoUpdate = true;
  57535. }
  57536. /**
  57537. * Sets the size of the storage texture.
  57538. *
  57539. * @param {number} width - The new width of the storage texture.
  57540. * @param {number} height - The new height of the storage texture.
  57541. */
  57542. setSize( width, height ) {
  57543. if ( this.image.width !== width || this.image.height !== height ) {
  57544. this.image.width = width;
  57545. this.image.height = height;
  57546. this.dispose();
  57547. }
  57548. }
  57549. }
  57550. /**
  57551. * This special type of buffer attribute is intended for compute shaders.
  57552. * It can be used to encode draw parameters for indirect draw calls.
  57553. *
  57554. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  57555. * and a WebGPU backend.
  57556. *
  57557. * @augments StorageBufferAttribute
  57558. */
  57559. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  57560. /**
  57561. * Constructs a new storage buffer attribute.
  57562. *
  57563. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  57564. * The subsequent parameter is then obsolete.
  57565. * @param {number} itemSize - The item size.
  57566. */
  57567. constructor( count, itemSize ) {
  57568. super( count, itemSize, Uint32Array );
  57569. /**
  57570. * This flag can be used for type testing.
  57571. *
  57572. * @type {boolean}
  57573. * @readonly
  57574. * @default true
  57575. */
  57576. this.isIndirectStorageBufferAttribute = true;
  57577. }
  57578. }
  57579. /**
  57580. * A loader for loading node objects in the three.js JSON Object/Scene format.
  57581. *
  57582. * @augments Loader
  57583. */
  57584. class NodeLoader extends Loader {
  57585. /**
  57586. * Constructs a new node loader.
  57587. *
  57588. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57589. */
  57590. constructor( manager ) {
  57591. super( manager );
  57592. /**
  57593. * Represents a dictionary of textures.
  57594. *
  57595. * @type {Object<string,Texture>}
  57596. */
  57597. this.textures = {};
  57598. /**
  57599. * Represents a dictionary of node types.
  57600. *
  57601. * @type {Object<string,Node.constructor>}
  57602. */
  57603. this.nodes = {};
  57604. }
  57605. /**
  57606. * Loads the node definitions from the given URL.
  57607. *
  57608. * @param {string} url - The path/URL of the file to be loaded.
  57609. * @param {Function} onLoad - Will be called when load completes.
  57610. * @param {Function} onProgress - Will be called while load progresses.
  57611. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  57612. */
  57613. load( url, onLoad, onProgress, onError ) {
  57614. const loader = new FileLoader( this.manager );
  57615. loader.setPath( this.path );
  57616. loader.setRequestHeader( this.requestHeader );
  57617. loader.setWithCredentials( this.withCredentials );
  57618. loader.load( url, ( text ) => {
  57619. try {
  57620. onLoad( this.parse( JSON.parse( text ) ) );
  57621. } catch ( e ) {
  57622. if ( onError ) {
  57623. onError( e );
  57624. } else {
  57625. error( e );
  57626. }
  57627. this.manager.itemError( url );
  57628. }
  57629. }, onProgress, onError );
  57630. }
  57631. /**
  57632. * Parse the node dependencies for the loaded node.
  57633. *
  57634. * @param {Array<Object>} [json] - The JSON definition
  57635. * @return {Object<string,Node>} A dictionary with node dependencies.
  57636. */
  57637. parseNodes( json ) {
  57638. const nodes = {};
  57639. if ( json !== undefined ) {
  57640. for ( const nodeJSON of json ) {
  57641. const { uuid, type } = nodeJSON;
  57642. nodes[ uuid ] = this.createNodeFromType( type );
  57643. nodes[ uuid ].uuid = uuid;
  57644. }
  57645. const meta = { nodes, textures: this.textures };
  57646. for ( const nodeJSON of json ) {
  57647. nodeJSON.meta = meta;
  57648. const node = nodes[ nodeJSON.uuid ];
  57649. node.deserialize( nodeJSON );
  57650. delete nodeJSON.meta;
  57651. }
  57652. }
  57653. return nodes;
  57654. }
  57655. /**
  57656. * Parses the node from the given JSON.
  57657. *
  57658. * @param {Object} json - The JSON definition
  57659. * @param {string} json.type - The node type.
  57660. * @param {string} json.uuid - The node UUID.
  57661. * @param {Array<Object>} [json.nodes] - The node dependencies.
  57662. * @param {Object} [json.meta] - The meta data.
  57663. * @return {Node} The parsed node.
  57664. */
  57665. parse( json ) {
  57666. const node = this.createNodeFromType( json.type );
  57667. node.uuid = json.uuid;
  57668. const nodes = this.parseNodes( json.nodes );
  57669. const meta = { nodes, textures: this.textures };
  57670. json.meta = meta;
  57671. node.deserialize( json );
  57672. delete json.meta;
  57673. return node;
  57674. }
  57675. /**
  57676. * Defines the dictionary of textures.
  57677. *
  57678. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  57679. * @return {NodeLoader} A reference to this loader.
  57680. */
  57681. setTextures( value ) {
  57682. this.textures = value;
  57683. return this;
  57684. }
  57685. /**
  57686. * Defines the dictionary of node types.
  57687. *
  57688. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57689. * @return {NodeLoader} A reference to this loader.
  57690. */
  57691. setNodes( value ) {
  57692. this.nodes = value;
  57693. return this;
  57694. }
  57695. /**
  57696. * Creates a node object from the given type.
  57697. *
  57698. * @param {string} type - The node type.
  57699. * @return {Node} The created node instance.
  57700. */
  57701. createNodeFromType( type ) {
  57702. if ( this.nodes[ type ] === undefined ) {
  57703. error( 'NodeLoader: Node type not found:', type );
  57704. return float();
  57705. }
  57706. return new this.nodes[ type ]();
  57707. }
  57708. }
  57709. /**
  57710. * A special type of material loader for loading node materials.
  57711. *
  57712. * @augments MaterialLoader
  57713. */
  57714. class NodeMaterialLoader extends MaterialLoader {
  57715. /**
  57716. * Constructs a new node material loader.
  57717. *
  57718. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57719. */
  57720. constructor( manager ) {
  57721. super( manager );
  57722. /**
  57723. * Represents a dictionary of node types.
  57724. *
  57725. * @type {Object<string,Node.constructor>}
  57726. */
  57727. this.nodes = {};
  57728. /**
  57729. * Represents a dictionary of node material types.
  57730. *
  57731. * @type {Object<string,NodeMaterial.constructor>}
  57732. */
  57733. this.nodeMaterials = {};
  57734. }
  57735. /**
  57736. * Parses the node material from the given JSON.
  57737. *
  57738. * @param {Object} json - The JSON definition
  57739. * @return {NodeMaterial}. The parsed material.
  57740. */
  57741. parse( json ) {
  57742. const material = super.parse( json );
  57743. const nodes = this.nodes;
  57744. const inputNodes = json.inputNodes;
  57745. for ( const property in inputNodes ) {
  57746. const uuid = inputNodes[ property ];
  57747. material[ property ] = nodes[ uuid ];
  57748. }
  57749. return material;
  57750. }
  57751. /**
  57752. * Defines the dictionary of node types.
  57753. *
  57754. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57755. * @return {NodeLoader} A reference to this loader.
  57756. */
  57757. setNodes( value ) {
  57758. this.nodes = value;
  57759. return this;
  57760. }
  57761. /**
  57762. * Defines the dictionary of node material types.
  57763. *
  57764. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  57765. * @return {NodeLoader} A reference to this loader.
  57766. */
  57767. setNodeMaterials( value ) {
  57768. this.nodeMaterials = value;
  57769. return this;
  57770. }
  57771. /**
  57772. * Creates a node material from the given type.
  57773. *
  57774. * @param {string} type - The node material type.
  57775. * @return {Node} The created node material instance.
  57776. */
  57777. createMaterialFromType( type ) {
  57778. const materialClass = this.nodeMaterials[ type ];
  57779. if ( materialClass !== undefined ) {
  57780. return new materialClass();
  57781. }
  57782. return super.createMaterialFromType( type );
  57783. }
  57784. }
  57785. /**
  57786. * A special type of object loader for loading 3D objects using
  57787. * node materials.
  57788. *
  57789. * @augments ObjectLoader
  57790. */
  57791. class NodeObjectLoader extends ObjectLoader {
  57792. /**
  57793. * Constructs a new node object loader.
  57794. *
  57795. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57796. */
  57797. constructor( manager ) {
  57798. super( manager );
  57799. /**
  57800. * Represents a dictionary of node types.
  57801. *
  57802. * @type {Object<string,Node.constructor>}
  57803. */
  57804. this.nodes = {};
  57805. /**
  57806. * Represents a dictionary of node material types.
  57807. *
  57808. * @type {Object<string,NodeMaterial.constructor>}
  57809. */
  57810. this.nodeMaterials = {};
  57811. /**
  57812. * A reference to hold the `nodes` JSON property.
  57813. *
  57814. * @private
  57815. * @type {?Object[]}
  57816. */
  57817. this._nodesJSON = null;
  57818. }
  57819. /**
  57820. * Defines the dictionary of node types.
  57821. *
  57822. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57823. * @return {NodeObjectLoader} A reference to this loader.
  57824. */
  57825. setNodes( value ) {
  57826. this.nodes = value;
  57827. return this;
  57828. }
  57829. /**
  57830. * Defines the dictionary of node material types.
  57831. *
  57832. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  57833. * @return {NodeObjectLoader} A reference to this loader.
  57834. */
  57835. setNodeMaterials( value ) {
  57836. this.nodeMaterials = value;
  57837. return this;
  57838. }
  57839. /**
  57840. * Parses the node objects from the given JSON.
  57841. *
  57842. * @param {Object} json - The JSON definition
  57843. * @param {Function} onLoad - The onLoad callback function.
  57844. * @return {Object3D}. The parsed 3D object.
  57845. */
  57846. parse( json, onLoad ) {
  57847. this._nodesJSON = json.nodes;
  57848. const data = super.parse( json, onLoad );
  57849. this._nodesJSON = null; // dispose
  57850. return data;
  57851. }
  57852. /**
  57853. * Parses the node objects from the given JSON and textures.
  57854. *
  57855. * @param {Object[]} json - The JSON definition
  57856. * @param {Object<string,Texture>} textures - The texture library.
  57857. * @return {Object<string,Node>}. The parsed nodes.
  57858. */
  57859. parseNodes( json, textures ) {
  57860. if ( json !== undefined ) {
  57861. const loader = new NodeLoader();
  57862. loader.setNodes( this.nodes );
  57863. loader.setTextures( textures );
  57864. return loader.parseNodes( json );
  57865. }
  57866. return {};
  57867. }
  57868. /**
  57869. * Parses the node objects from the given JSON and textures.
  57870. *
  57871. * @param {Object} json - The JSON definition
  57872. * @param {Object<string,Texture>} textures - The texture library.
  57873. * @return {Object<string,NodeMaterial>}. The parsed materials.
  57874. */
  57875. parseMaterials( json, textures ) {
  57876. const materials = {};
  57877. if ( json !== undefined ) {
  57878. const nodes = this.parseNodes( this._nodesJSON, textures );
  57879. const loader = new NodeMaterialLoader();
  57880. loader.setTextures( textures );
  57881. loader.setNodes( nodes );
  57882. loader.setNodeMaterials( this.nodeMaterials );
  57883. for ( let i = 0, l = json.length; i < l; i ++ ) {
  57884. const data = json[ i ];
  57885. materials[ data.uuid ] = loader.parse( data );
  57886. }
  57887. }
  57888. return materials;
  57889. }
  57890. }
  57891. /**
  57892. * In earlier three.js versions, clipping was defined globally
  57893. * on the renderer or on material level. This special version of
  57894. * `THREE.Group` allows to encode the clipping state into the scene
  57895. * graph. Meaning if you create an instance of this group, all
  57896. * descendant 3D objects will be affected by the respective clipping
  57897. * planes.
  57898. *
  57899. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  57900. *
  57901. * @augments Group
  57902. */
  57903. class ClippingGroup extends Group {
  57904. /**
  57905. * Constructs a new clipping group.
  57906. */
  57907. constructor() {
  57908. super();
  57909. /**
  57910. * This flag can be used for type testing.
  57911. *
  57912. * @type {boolean}
  57913. * @readonly
  57914. * @default true
  57915. */
  57916. this.isClippingGroup = true;
  57917. /**
  57918. * An array with clipping planes.
  57919. *
  57920. * @type {Array<Plane>}
  57921. */
  57922. this.clippingPlanes = [];
  57923. /**
  57924. * Whether clipping should be enabled or not.
  57925. *
  57926. * @type {boolean}
  57927. * @default true
  57928. */
  57929. this.enabled = true;
  57930. /**
  57931. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  57932. *
  57933. * @type {boolean}
  57934. * @default false
  57935. */
  57936. this.clipIntersection = false;
  57937. /**
  57938. * Whether shadows should be clipped or not.
  57939. *
  57940. * @type {boolean}
  57941. * @default false
  57942. */
  57943. this.clipShadows = false;
  57944. }
  57945. }
  57946. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AtomicFunctionNode, AttributeNode, BackSide, BarrierNode, BasicEnvironmentNode, BasicLightMapNode, 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, 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, Euler, EventDispatcher, EventNode, ExpressionNode, FileLoader, FlipNode, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, 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, RemapNode, 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, StorageArrayElementNode, 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, WebGLCoordinateSystem, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, WorkgroupInfoNode, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, error, log$1 as log, shaderStages, vectorComponents, warn, warnOnce };
粤ICP备19079148号